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
2026-01-29 12:52:02 -08:00
2026-01-28 09:29:17 -08:00
2025-07-30 12:44:54 -04:00
2025-04-25 12:05:40 -04:00
2025-04-30 16:27:34 -04:00
2026-01-26 17:13:58 -08:00
2025-12-11 07:41:57 -08:00
2025-02-28 09:43:03 -08:00

x402

x402 is an open standard for internet native payments. It aims to support all networks (both crypto & fiat) and forms of value (stablecoins, tokens, fiat).

app.use(
  paymentMiddleware(
    {
      "GET /weather": {
        accepts: [...],                 // As many networks / schemes as you want to support
        description: "Weather data",    // what your endpoint does
      },
    },
  ),
);
// That's it! See examples/ for full details
Installation

Typescript

# All available reference sdks
npm install @x402/core @x402/evm @x402/svm @x402/axios @x402/fetch @x402/express @x402/hono @x402/next @x402/paywall @x402/extensions

# Minimal Fetch client
npm install @x402/core @x402/evm @x402/svm @x402/fetch

# Minimal express Server
npm install @x402/core @x402/evm @x402/svm @x402/express

Python

pip install x402

Go

go get github.com/coinbase/x402/go

Principles

  • Open standard: x402 is an open standard, freely accessible and usable by anyone. It will never force reliance on a single party.
  • HTTP / Transport Native: x402 is meant to seamlessly complement existing data transportation. It should whenever possible not mandate additional requests outside the scope of a typical client / server flow.
  • Network, token, and currency agnostic: we welcome contributions that add support for new networks (both crypto and fiat), signing standards, or schemes, so long as they meet our acceptance criteria laid out in CONTRIBUTING.md. x402 may extend support to fiat based networks, but will never deprioritize onchain payments in favor of fiat payments.
  • Backwards Compatible: x402 will not deprecate support for any existing networks unless such removal is deemed necessary for the security of the standard
  • Trust minimizing: all payment schemes must not allow for the facilitator or resource server to move funds, other than in accordance with client intentions
  • Easy to use: x402 needs to be 10x better than existing ways to pay on the internet. This means abstracting as many details of crypto as possible away from the client and resource server, and into the facilitator. This means the client/server should not need to think about gas, rpc, etc.

Ecosystem

The x402 ecosystem is growing! Check out our ecosystem page to see projects building with x402, including:

  • Client-side integrations
  • Services and endpoints
  • Ecosystem infrastructure and tooling
  • Learning and community resources

Want to add your project to the ecosystem? See our demo site README for detailed instructions on how to submit your project.

Roadmap: see ROADMAP.md

Documentation: see docs/ for the GitBook documentation source

Terms:

  • resource: Something on the internet. This could be a webpage, file server, RPC service, API, any resource on the internet that accepts HTTP / HTTPS requests.
  • client: An entity wanting to pay for a resource.
  • facilitator: A server that facilitates verification and execution of payments for one or many networks.
  • resource server: An HTTP server that provides an API or other resource for a client.

Technical Goals:

  • Permissionless and secure for clients, servers, and facilitators
  • Minimal friction to adopt for both client and resource servers
  • Minimal integration for the resource server and client (1 line for the server, 1 function for the client)
  • Ability to trade off speed of response for guarantee of payment
  • Extensible to different payment flows and networks

Specification

See specs/ for full documentation of the x402 standard/

Typical x402 flow

x402 payments typically adhere to the following flow, but servers have a lot of flexibility. See advanced folders in examples/.

The following outlines the flow of a payment using the x402 protocol. Note that steps (1) and (2) are optional if the client already knows the payment details accepted for a resource.

  1. Client makes an HTTP request to a resource server.

  2. Resource server responds with a 402 Payment Required status and a PaymentRequired b64 object return as a PAYMENT-REQUIRED header.

  3. Client selects one of the PaymentRequirements returned by the server response and creates a PaymentPayload based on the scheme & network of the PaymentRequirements they have selected.

  4. Client sends the HTTP request with the PAYMENT-SIGNATURE header containing the PaymentPayload to the resource server.

  5. Resource server verifies the PaymentPayload is valid either via local verification or by POSTing the PaymentPayload and PaymentRequirements to the /verify endpoint of a facilitator.

  6. Facilitator performs verification of the object based on the scheme and network of the PaymentPayload and returns a Verification Response.

  7. If the Verification Response is valid, the resource server performs the work to fulfill the request. If the Verification Response is invalid, the resource server returns a 402 Payment Required status and a Payment Required Response JSON object in the response body.

  8. Resource server either settles the payment by interacting with a blockchain directly, or by POSTing the Payment Payload and Payment PaymentRequirements to the /settle endpoint of a facilitator server.

  9. Facilitator server submits the payment to the blockchain based on the scheme and network of the Payment Payload.

  10. Facilitator server waits for the payment to be confirmed on the blockchain.

  11. Facilitator server returns a Payment Execution Response to the resource server.

  12. Resource server returns a 200 OK response to the Client with the resource they requested as the body of the HTTP response, and a PAYMENT-RESPONSE header containing the Settlement Response as Base64 encoded JSON if the payment was executed successfully.

Schemes

A scheme is a logical way of moving money.

Blockchains allow for a large number of flexible ways to move money. To help facilitate an expanding number of payment use cases, the x402 protocol is extensible to different ways of settling payments via its scheme field.

Each payment scheme may have different operational functionality depending on what actions are necessary to fulfill the payment. For example exact, the first scheme shipping as part of the protocol, would have different behavior than upto. exact transfers a specific amount (ex: pay $1 to read an article), while a theoretical upto would transfer up to an amount, based on the resources consumed during a request (ex: generating tokens from an LLM).

See specs/schemes for more details on schemes, and see specs/schemes/exact/scheme_exact_evm.md to see the first proposed scheme for exact payment on EVM chains.

Schemes vs Networks

Because a scheme is a logical way of moving money, the way a scheme is implemented can be different for different blockchains. (ex: the way you need to implement exact on Ethereum is very different from the way you need to implement exact on Solana).

Clients and facilitators must explicitly support different (scheme, network) pairs in order to be able to create proper payloads and verify / settle payments.

Description
A payments protocol for the internet. Built on HTTP.
Readme Apache-2.0 506 MiB
Languages
Python 45.1%
Go 36.5%
TypeScript 17.6%
JavaScript 0.3%
Java 0.3%