* 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>
X402 TypeScript Examples
This directory contains a collection of TypeScript examples demonstrating how to use the X402 protocol in various contexts. These examples are designed to work with the X402 npm packages and share a workspace with the main X402 packages.
Setup
Before running any examples, you need to install dependencies and build the packages:
# From the examples/typescript directory
pnpm install
pnpm build
Example Structure
The examples are organized into several categories:
Clients
Examples of different client implementations for interacting with X402 services:
clients/axios/- Axios client with x402 payment interceptor fromx402-axios.clients/fetch/- Client using thex402-fetchwrapper around the native fetch API.clients/cdp-sdk/- Client that uses CDP Server Wallets as the signer withx402-axios.clients/chainlink-vrf-nft/- Example using Chainlink to mint a randomized NFT (see them on Opensea). Demonstrates verify/settle flow withx402-axios.
Agents
agent/- Anthropic agent that pays via a Go proxy usingx402-fetch.dynamic_agent/- Agent that discovers tools dynamically and pays per-request using x402.
Discovery
discovery/- Uses the facilitator to list available x402-protected resources (Bazaar).
MCP
mcp/- MCP server that makes paid API requests viax402-axios(Claude Desktop compatible).mcp-embedded-wallet/- Electron-based MCP server with an embedded wallet that signs requests via IPC.
Facilitator
facilitator/- Example implementation of an x402 payment facilitator exposing/verifyand/settle.
Fullstack
fullstack/next/- Next.js app demonstrating route protection withx402-nextmiddleware.fullstack/mainnet/- Next.js app configured for Base mainnet using the Coinbase hosted facilitator.fullstack/next-advanced/- [WIP] Deep Next.js integration using a paywall + session cookie after verify/settle.fullstack/browser-wallet-example/- Browser wallet template: Hono server + React client with session and one-time payments.fullstack/farcaster-miniapp/- Farcaster Mini App template with x402-protected APIs using MiniKit.fullstack/auth_based_pricing/- SIWE + JWT with conditional pricing ($0.01 with JWT vs $0.10 without) using x402.
Servers
Examples of different server implementations:
servers/express/- Express.js server usingx402-expressmiddleware.servers/hono/- Hono server usingx402-honomiddleware.servers/advanced/- Express server without middleware: delayed settlement, dynamic pricing, multiple requirements.servers/mainnet/- Server example for accepting real USDC on Base mainnet using the Coinbase hosted facilitator.
Running Examples
Each example directory contains its own README with specific instructions for running that example. Navigate to the desired example directory and follow its instructions.
Development
This workspace uses:
- pnpm for package management
- Turborepo for monorepo management
- TypeScript for type safety
The examples are designed to work with the main X402 packages, so they must be built before running any examples.
A note on private keys
The examples in this folder commonly use private keys to sign messages. Never put a private key with mainnet funds in a .env file. This can result in keys getting checked into codebases and being drained.
There are many ways to generate a keypair to use exclusively for development, one way is via foundry:
# install foundry
curl -L https://foundry.paradigm.xyz | bash
# generate a new wallet
cast w new
You can fund your new wallet on most networks via the testnet CDP Faucet, simply provide the address generated by cast.