The committed @x402/paywall bundle on main was last generated against an
older viem than the lockfile currently pins. pnpm install --frozen-lockfile
resolves viem 2.47.12 (via #2013), but the bundled src/evm/gen/template.ts
(and its Python + Go siblings) were built against an earlier resolution
that pre-dated chain definitions for Mezo, MegaETH, Stable, Radius (each
with a testnet variant), and 33 others. EvmPaywall.tsx throws
"Unsupported chain ID" at init for any eip155:<id> whose chain isn't in
the bundled viem/chains.
This PR:
1. Regenerates all nine auto-generated template files (TypeScript,
Python, and Go for EVM/SVM/AVM) against the current lockfile. No
source changes on any runtime path.
2. Teaches build:paywall to emit output matching the repo's formatters
(prettier / ruff), so generated files stay clean under pnpm run
format + uvx ruff format.
3. Adds a PR-time drift check
(.github/workflows/check_paywall_template.yml) so a future lockfile
or @x402/evm change that invalidates the bundle fails loudly
instead of shipping silently.
Scope is limited to @x402/paywall because it is the only package in this
repo that bakes viem chain definitions into a built artifact.
Verified on a fork-internal test PR running on ubuntu-latest
(Node 24, pnpm 10.7.0): check_format, check_lint, check_go, check_python,
check_package_lock, and the new check_paywall_template drift check all
pass. Additional local evidence:
- Chain-presence in regenerated bundle: Mezo 31612/31611, MegaETH
4326/6343, Stable 988/2201, Radius 723487/72344, Base/Arbitrum/
Polygon all present (mainnet/testnet ordering).
- Cross-platform determinism: a clean-slate rebuild on macOS produces
byte-identical output to ubuntu-latest CI.
- Tarball install into a throwaway consumer: all expected chain IDs
present in the published dist/esm/evm/index.js.
- Browser smoke test (Chrome, served from a local HTTP server):
EvmPaywall mounts without Unsupported-chain throw for
eip155:31611 (Mezo Testnet) and eip155:723487 (Radius); DOM
renders the expected token/chain labels.
Fixes#1971.
* 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:~`.
* 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
* docs: add Documentation Checklist + surface chain-contribution flow
DEFAULT_ASSETS.md's 'Adding a New Chain' numbered flow stopped at 'Update
all three SDKs' → 'Submit a PR' and did not mention the user-facing docs
surfaces that also enumerate every chain with default-asset support. As a
result, recent onboarding PRs have shipped with stale docs (e.g. the
Radius PR #2038 updated the SDKs but not the docs table or Go README).
The existing Cross-SDK Checklist at the bottom enumerates only the three
code registries, mirroring the same gap.
network-and-token-support.mdx has a parallel discoverability problem:
the pointer to DEFAULT_ASSETS.md used a repo-relative path that resolves
to a broken link on docs.x402.org, and the pointer sat inside the
'Default Assets for Dollar-String Pricing' intro rather than under
'Adding Support for New Networks' where a would-be contributor actually
looks. The 'Adding' section itself described only runtime registration
(server.register from consumer code) and did not mention the separate
upstream-contribution path, and it also contained a 'Running Your Own
Facilitator' subsection that is about facilitator infrastructure, not
about adding networks — a topical mismatch. The page also ordered the
'Facilitators' section before 'Adding Support for New Networks', which
inverts the natural read → use → extend → operate narrative.
Changes:
* DEFAULT_ASSETS.md:
- Promote 'Update user-facing documentation' to a numbered step in
'Adding a New Chain' (new step 3, between 'Update all three SDKs'
and 'Submit a PR'), with a cross-reference to the new checklist.
- Append a new 'Documentation Checklist' section below the existing
Cross-SDK Checklist, naming the two hot docs surfaces
(network-and-token-support.mdx and go/mechanisms/evm/README.md)
that must also be updated on a new chain onboarding.
* docs/core-concepts/network-and-token-support.mdx:
- Remove the oddly-placed 'See DEFAULT_ASSETS.md' link from the
Dollar-String Pricing intro; replace with an in-page anchor
pointing at the new contribution subsection.
- Split 'Adding Support for New Networks' into two subsections:
'Runtime Registration' (the existing content, unchanged) and
a new 'Contributing a New Default Asset' subsection that links
to DEFAULT_ASSETS.md via an absolute github.com URL (so the
link works on the published docs site) and explicitly names
the cross-SDK + docs checklist.
- Move 'Running Your Own Facilitator' out of 'Adding Support for
New Networks' into the existing 'Facilitators' section, where
it belongs topically.
- Swap top-level section order: 'Adding Support for New Networks'
now precedes 'Facilitators', matching the read → use → extend →
operate narrative.
No code changes. Documentation only.
* docs: revert DEFAULT_ASSETS.md, unify SDK READMEs to link docs
Address review feedback: the Mintlify agent (.github/workflows/update-docs.yml)
keeps docs/ in sync with code, so contributors should only update the three SDK
constants files. Remove the Documentation Checklist and Step 3 from
DEFAULT_ASSETS.md. Apply a consistent two-link block to all three SDK READMEs
(Go/TS/Python) pointing at the mdx default-assets list and the mdx
Adding Support for New Networks section. Soften the mdx Contributing a New
Default Asset blurb to drop manual mdx/README update instructions.
Implement the spec change from PR #1682, adding optional seller-defined
memo support to the SVM exact scheme across all three SDKs.
Client changes (TypeScript, Go, Python - both v1 and v2):
- When extra.memo is present, use its UTF-8 value as memo instruction data
- When absent, fall back to existing random 16-byte nonce behavior
- Validate memo does not exceed MAX_MEMO_BYTES (256) limit
Facilitator changes (TypeScript, Go, Python - both v1 and v2):
- When extra.memo is present in requirements, verify exactly one memo
instruction exists and its data matches the expected value
- Return specific error codes: memo_count / memo_mismatch
Constants added:
- MAX_MEMO_BYTES / MaxMemoBytes (256) across all languages
- ERR_MEMO_MISMATCH, ERR_MEMO_COUNT (Python/Go)
- ErrMemoExceedsMaxSize (Go client)
Tests added:
- TypeScript: 4 memo tests in duplicateTx.test.ts
- Go: TestSellerMemo with 4 subtests in duplicate_tx_test.go
- Python: TestSellerMemo class with 4 tests in test_duplicate_tx.py
Closes#1682
The EVM paywall hardcodes "USDC" as the token label in all display
text. The payment requirements already carry the token name in
extra.name (populated by the server from the default asset registry),
but the paywall ignores it.
Read extra.name from the first payment requirement and use it for
all user-facing token text. Falls back to "USDC" when extra.name
is absent (backward compatible with EIP-3009 tokens).
5 display strings updated:
- Header: "please pay $X {tokenName}" (was "USDC")
- Testnet prompt: "Need {tokenName} on {chainName}?" (was "USDC")
- Balance: "$X {tokenName}" (was "USDC")
- Amount row: "$X {tokenName}" (was "USDC")
- Error: "Make sure you have {tokenName} on {chainName}" (was "USDC")
Regenerated Go, Python, and TS paywall templates.
* test(python): add missing sync test scenarios to existing test_server.py
Add edge case coverage for: missing/malformed _meta, no matching
requirements, MCPToolResult direct return, non-dict handler return,
structuredContent preservation, empty accepts validation, verification
failure without reason, and hook context field verification.
* fix: apply ruff format to test_server.py
* fix formatting: match existing test style, inline data construction, fix import order
Add native USDC (0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359) as the
default stablecoin for Polygon mainnet across all three SDKs:
- Go: ChainIDPolygon constant, v2 NetworkConfigs, v1 NetworkConfigs
- TypeScript: v2 stablecoins map in ExactEvmScheme
- Python: v2 NETWORK_CONFIGS with supported_assets
Update Go v1 unit tests that previously used "polygon" as a network
without a default asset config. Replace with "iotex" and add positive
test coverage for Polygon config and asset resolution.
Contract details (verified on-chain via PolygonScan):
- Token: Circle native USDC (FiatTokenV2_2)
- EIP-712 domain: name="USD Coin", version="2"
- EIP-3009: transferWithAuthorization supported
- x402 proxy deployed at canonical CREATE2 address
* Fix race condition in lazy facilitator initialization for FastAPI and Flask middleware
Under concurrent requests, multiple coroutines/threads could see init_done=False
simultaneously and all call http_server.initialize(), causing redundant init calls
and inconsistent error propagation.
- FastAPI: guard with asyncio.Lock using double-checked locking pattern
- Flask: guard with threading.Lock using double-checked locking pattern
- Add concurrency tests proving single-flight initialization for both frameworks
- Add tests verifying failed init does not permanently block retries
Closes#1584
* fix: remove unused variables to pass ruff lint
* fix(go): add omitempty to QueryInput/BodyInput.Method to prevent spurious enum validation failure
When external JSON omits info.input.method (valid when method is not in the schema's
required list), Go zero-initializes the Method field to "" and re-marshaling produces
"method":"", which fails the enum constraint in ValidateDiscoveryExtension.
Adding omitempty ensures absent method fields remain absent after round-trip serialization.
Fixes#1830
Made-with: Cursor
* enforce method is required in TS and Python discovery extension schemas
Per spec, the method field must always be present in a discovery extension's
info.input. Add "method" to the required array in schemas built by the TS
and Python resource service builders, so ValidateDiscoveryExtension rejects
extensions missing method with a clear error.
Also reverts the Go omitempty workaround from the prior commit; the Go SDK
was already producing a validation error for absent method (via the enum
constraint), and the schema-level required enforcement is the correct fix.
Closes#1830
Made-with: Cursor
* style: format resourceService.ts type union per Prettier
Made-with: Cursor
* fix: auto-populate HTTP method from adapter in all SDKs
The SDK entry points (processHTTPRequest, requiresPayment,
processSettlement) now derive the HTTP method from the adapter
when it is not explicitly set on the request context. This ensures
direct x402HTTPResourceServer users do not need to manually assign
the method field — the SDK computes it at runtime, matching the
behavior middleware users already get.
Made-with: Cursor
* test: add declare → enrich → validate flow tests for bazaar extension
Verify the real middleware path: extensions are declared without method,
enrichDeclaration injects method from the HTTP context at request time,
and the enriched extension passes schema validation. Covers GET and
POST in all three SDKs (TypeScript, Go, Python).
Made-with: Cursor
* feat(evm): add Stable mainnet (chain ID 988) network support
* chore: add changelog fragments for Stable mainnet support
* feat(evm): add Stable mainnet to Go v1 legacy network config
* 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
Two fixes for the Python SDK:
1. Add serialize_by_alias=True to BaseX402Model so model_dump_json()
produces spec-compliant camelCase by default. Users no longer need
to pass by_alias=True manually. (Fixes#1120)
2. Auto-wrap eth_account LocalAccount in EthAccountSigner when passed
to ExactEvmScheme or ExactEvmSchemeV1. This prevents the confusing
ValueError from mismatched sign_typed_data signatures. (Fixes#1121)
Add Monad (chain ID 143) to the EVM network chain ID map across
TypeScript, Python, and Go SDKs. Monad has native Circle USDC with
EIP-3009 (transferWithAuthorization) support.
- TypeScript: add to EVM_NETWORK_CHAIN_ID_MAP
- Python: add to V1_NETWORKS, V1_NETWORK_CHAIN_IDS, NETWORK_CONFIGS, NETWORK_ALIASES
- Go: add ChainIDMonad, NetworkConfigs entries (CAIP-2 + legacy)
USDC on Monad: 0x754704Bc059F8C67012fEd69BC8A327a5aafb603
* 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
Add MegaETH (chain ID 4326) with USDM as the default stablecoin.
TypeScript, Go, and Python SDK support added.
Changelog fragments included for all SDKs.