51 Commits

Author SHA1 Message Date
MG
a25800efed
feat(avm): Add Algorand (AVM) blockchain exact spec implementation and networks support for Typescript (#1560)
* Migrate all code from branch-algorand-v2-typescript-algokit

* Update format and lint pass on core and examples

* Reformat template files

* Update: Coinbase review changes applied

* Fix Paywall builder pattern

* Update: Reverted e2e/legacy, Remove: src/exact/v1 and src/v1

* Add Faucets URLs to AVM README

* Optimizing and shrinking PR

* Remove dead import

* Add optimization changes related unit tests

* Update coinbase review changes applied

* Update avm e2e, rebased to latest, linted and formatted

* Fix avm template format

* Remove python and Go AVM templates, Made AVM optional to facilitator and Add SERVER_ADDRESS

* Lint and format

* Update: made AVM optional in proxy.ts

* Rebased and Replayed some commits

* Reset e2e pnpm-lock.yaml

* Replayed correct updated lockfiles

* Reverted accidentally overwritten files during rebase replay

* Revert accidental overwritten files in examples
2026-04-11 08:01:20 +09:00
scaler
cde91514ba
feat(specs): add Keeta exact scheme (#1575)
* feat(specs): add Keeta exact scheme

* feat(schemes/keeta): add transaction simulation to verification step

This adds a few cheap checks to simulate the transaction and catch
invalid blocks early on to prevent the server from doing expensive work
unnecessarily.
2026-04-10 14:56:55 +09:00
Ethan Oroshiba
af01f26b88
docs(bazaar): clarify EXTENSION-RESPONSES header applies to verify and settle (#1922)
Made-with: Cursor
2026-04-06 09:38:39 -07:00
Carson Roscoe
2250caec83
feat: refactor coinbase/x402 references to x402-foundation/x402 (#1912)
* feat: refactor coinbase/x402 references to x402-foundation/x402

* fix: format

* chore: changeset fragments for typescript, python and go
2026-04-02 12:59:07 -07:00
Carson Roscoe
ad2658ac57
fix: evm contract deploys (#1880)
* fix: evm contract deploys

* feat: updated constants in SDKs

* feat: added changeset fragments
2026-03-30 21:06:55 -07:00
Carson Roscoe
fc11152c47
feat: add upto to go sdk (#1833)
* feat: add upto to go sdk

* feat: cleanup PR

* feat: added HTTPTransportContext to Go SDK

* fix: ai reviewer feedback

* fix: typescript tests

* fix: header parsing for HTTPTransportContext in Typescript

* feat: cleanup pr

* feat: pr cleanup

* feat: pr review

* feat: update e2e go.mod for upto debs

* fix: lint
2026-03-27 18:19:18 -07:00
Carson Roscoe
9e50ecbd2e
feat: added EXTENSION-RESPONSES header to spec (#1835)
* feat: added BAZAAR-RESPONSE header to spec

* feat: generalized header
2026-03-26 13:10:49 -07:00
Carson Roscoe
d352574bd5
feat: add upto to typescript sdk (#1773)
* feat(evm): add upto payment scheme TypeScript SDK

Implement the upto payment scheme for EVM, enabling usage-based payments
where a client authorizes a maximum amount via Permit2 and the server
settles for the actual amount used (which may be less).

Covers all three roles:
- Client: creates Permit2 payloads with max authorized amount
- Server: builds payment requirements, forces permit2 transfer method
- Facilitator: verifies permitted >= required, settles actual usage,
  supports zero-settlement path for no-charge responses

Key design decisions:
- Permit2 only (no EIP-3009, per spec)
- Shared Permit2 witness struct with exact scheme
- Re-exports shared utilities from exact (approval helpers, extensions, RPC)
- V2 protocol only

Resolves: CDPAI-714

* chore(evm): add JSDoc descriptions and fix lint errors in upto SDK

Add comprehensive JSDoc descriptions, @param, and @returns tags to all
upto scheme files to satisfy eslint jsdoc rules. Remove unused imports
in facilitator test file.

* refactor(evm): extract shared permit2 helpers to reduce duplication between exact and upto facilitators

* refactor(evm): consolidate client-side createPermit2Payload into shared helper

* refactor(evm): extract shared trySignEip2612Permit and trySignErc20Approval from scheme classes

* refactor(evm): split shared/permit2-helpers into permit2.ts and extensions.ts

* test(evm): add upto server, register, and types tests; expand client and facilitator coverage

Add 3 new test files (server.test.ts, register.test.ts, types.test.ts)
covering upto-specific server behaviors (permit2 forcing, facilitator
address injection, price parsing), registration helpers for all three
roles, and type guard validation. Expand existing client and facilitator
tests with additional edge cases.

Also includes in-progress source changes: shared permit2 helper
refactoring, upto facilitator hardening, spec clarifications, and
defaultAssets extraction.

* fix(evm): resolve lint errors for CI — add missing JSDoc descriptions and fix unused vars

* fix(evm): address PR review — align upto verify flow with exact, update spec, remove createEvmClient

* refactor(evm): move shared utils to shared/, remove upto register pattern

- Move validateErc20ApprovalForPayment to shared/erc20approval.ts
  (was in exact/facilitator/, used by both exact and upto)
- Move RPC utilities to shared/rpc.ts, rename types to drop Exact prefix
  (EvmSchemeConfig, EvmSchemeOptions, etc.) with deprecated aliases
- Remove registerUptoEvmScheme from client, facilitator, and server
  (v1 legacy pattern not needed for v2-only upto scheme)
- Backward-compat re-exports preserved at original paths

* test(e2e): add upto payment scheme e2e test coverage

Add full e2e test suite for the upto payment scheme mirroring exact
permit2 coverage: direct settle, EIP-2612 gas sponsoring, and ERC-20
approval gas sponsoring endpoints.

- Add 3 upto endpoints to Express e2e server with UptoEvmScheme
- Register UptoEvmScheme in TypeScript facilitator
- Register UptoEvmClientScheme in fetch and axios e2e clients
- Add upto Permit2 approve/revoke cycle handling in test runner
- Add upto entry points to @x402/evm tsup.config.ts
- Update test.config.json files for all components

* fix(evm): harden upto type guard, add time window validation, improve settlement comments

- Add validAfter check to isUptoPermit2Payload for stricter exact/upto discrimination
- Add deadline > validAfter guard in client permit2 payload creation
- Default simulateInSettle to true for settlement re-verification
- Expand settlement re-verification comment for reviewer clarity
- Add no-register.ts comments explaining V1 compat is not needed for upto
- Clarify e2e test config description for upto endpoint
- Add tests for validAfter type guard and buildUptoPermit2SettleArgs

* feat: added SettlementOverride

* fix: examples lock

* feat: Added upto to hono/next e2e tests

* feat: update upto tests

* feat: update tests to support fallback facilitator for non-SDK parity testing

* fix: format/lint

* fix: add linting to upto example

---------

Co-authored-by: Fabrice Cheng <fabrice.cheng@coinbase.com>
2026-03-25 16:10:04 -07:00
Carson Roscoe
067f29705f
feat: add dynamic routing to bazaar (#1664)
* feat: add dynamic routing to bazaar

* feat: fixed format/linter errors

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

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

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

* fix: updated param logic

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

* feat: updated e2e bazaar facilitators

* fix: add pathParams if not set

* fix: lint in python

* fix: typescript examples lock

* feat: pr feedback

* feat: pr feedback

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 08:49:46 -07:00
Carson Roscoe
7b7e163c15
feat: python permit2 and gas sponsorship extensions (#1686)
* feat: implement permit2 in python

* feat: added eip2612 gas sponsoring extension

* feat: added erc20 approval gas sponsoring extension

* feat: added permit2 to exact evm with gas sponsorship support

* feat: updated unit/integration tests

* feat: updated e2e clients

* feat: updated e2e servers

* feat: updated e2e facilitator

* feat: added changelog fragment

* feat: updated specs

* fix: format/lint

* fix: format

* feat: pr feedback
2026-03-19 11:17:34 -07:00
Misha Kolesnik
ff1bc50660
feat(spec): document Memo instruction and seller-defined memo for SVM scheme (#1682)
The SVM exact scheme spec was out of date with the implementation
(PR #1048 added Memo instruction support without updating the spec).

This change:
- Updates instruction layout from 3-5 to 3-6 instructions
- Documents SPL Memo as an allowed optional program alongside Lighthouse
- Adds optional extra.memo field for seller-defined memo content
- Specifies client and facilitator behavior for memo verification

The extra.memo field enables sellers to attach payment references
(e.g., invoice IDs) to on-chain transactions, allowing payment
reconciliation on a single payTo address without requiring unique
deposit addresses (ATAs) per payment.
2026-03-18 15:55:07 -07:00
Marcelo Salloum dos Santos
cae3a21607
docs: make /verify required in Stellar exact scheme spec (#1640)
The protocol flow previously sent directly to /settle and declared
/verify as optional. Per maintainer feedback on PR #1575, verify is
required — it prevents the resource server from doing unnecessary work
for invalid payloads. This aligns the Stellar spec with the SVM and
Hedera exact scheme specs.
2026-03-17 10:22:45 +09:00
Dan Finlay
13ad532b03
Add spec for ERC-7710 support to the exact_evm scheme (#732) 2026-03-13 18:59:05 +01:00
Alfred Tom
f2bbb5cb25
feat(extensions): add optional signed Offer & Receipt extension (draft, addresses #496) (#935)
* Add new folders and READMEs to spec folder to support future settlement types and extensions.

* Add the EIP-3009/Signed Transfer spec.

* Added initial draft of offer and receipt extension.

* feat(extensions): Add client and server code to support signed offers and receipts.
Server:
- offerReceiptResourceServerExtension for signing offers/receipts
- JWS and EIP-712 signature format support
- Signer factories for both formats
Client:
- createOfferReceiptExtractor() callback for wrapFetchWithPayment
- Extracts offers, acceptedOffer, receipt, and settlementResponse
- Attaches metadata to response.offerReceipt
- Generic user review attestation with receipt/offer fallback, with optional OMATrust implementation
- Receipt-attestation client demonstrating full flow

* Update PR based on feedback:
- Add network field to receipt
- Add optional transaction field to receipt
- Move offers and receipt to extensions field
- Add version
- Removed settlement field from offer (refers to a future extension).

* Move signed payload version from info into the signed offer/receipt payload.

* Move version into signed payload. Replace issuedAt + maxTimeoutSeconds with validUntil.

* Add acceptIndex to signed offers as unsigned envelope field

- Add acceptIndex to offer envelope (not signed payload)
- Update examples and JSON schemas

* chore: remove outdated settlements folder

* chore: reset core/http to main for hooks integration

* feat(offer-receipt): implement v1.0 spec for signed offers and receipts

Implements the offer-receipt extension per extension-offer-and-receipt.md v1.0 spec.

Key changes from phdargen offer-receipt implementation:
- Pass down schema to comply with extensions spec
- Add more library functions for both servers and clients
- Remove server-side offer extraction (offers flow server→client only)
- Remove OMATrust integration code (deferred to future PR)
- Client example uses raw flow, not wrapper which still needs extension hook integration
- Add comprehensive test coverage (68 tests)

* chore: fix linter errors and update pnpm-lock.yaml

* chore: add lint/format config files to receipt-attestation example

* Address PR feedback: improve offer-receipt documentation and minor code cleanup:

- Rename .env.example to .env-local for consistency
- Move verbose code comments to README (use cases, security, verification)
- Add wrapFetchWithPayment example showing offer/receipt capture
- Remove unused createOfferReceiptExtractor

* refactor(offer-receipt): rename maxTimeoutSeconds to offerValiditySeconds

* fix(offer-receipt): simplify extractResourceUrl and import HTTPRequestContext from core

* feat(offer-receipt): rename Signer to Issuer and add server example

- Rename OfferReceiptSigner to OfferReceiptIssuer (more accurate naming)
- Rename signOffer/signReceipt to issueOffer/issueReceipt
- Rename createJWSOfferReceiptSigner to createJWSOfferReceiptIssuer
- Rename createEIP712OfferReceiptSigner to createEIP712OfferReceiptIssuer
- Add offer-receipt server example in examples/typescript/servers/offer-receipt

* fix(offer-receipt): make EIP-712 signing chain-agnostic

- Hardcode chainId to 1 in EIP-712 domain
- Change payTo type from address to string to support non-EVM networks
- Update spec §3.2, §4.3, §4.5, §5.5 as well as code and tests

* feat(offer-receipt): add signature verification and DID resolution

- Add 4 verification functions to signing.ts (verifyOfferSignatureEIP712,
  verifyReceiptSignatureEIP712, verifyOfferSignatureJWS, verifyReceiptSignatureJWS)
- Add @noble/curves and @scure/base dependencies for crypto operations
- Add did.ts with extractPublicKeyFromKid supporting did:key, did:jwk, did:web
- Modify clients/offer-receipt example demonstrating full verification flow
- Change folder name of clients example to be more consistent
- Update tests with verification coverage

* Update examples/typescript/servers/offer-receipt/README.md

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

* fix: produce valid JWS compact serialization in signJWS

- Fixed signJWS to output proper base64url-encoded JWS compact serialization
- Updated tests to actually verify JWS output, surfacing the broken serialization
- Renamed misleading function names discovered during the fix

* fix: enable local did:web verification

- Change resolveDidWeb to use HTTP for localhost/127.0.0.1 (per did:web spec)
- Server example now serves /.well-known/did.json with public key
- SERVER_DOMAIN env var is now required, expects did:web identifier format
- Added tests for localhost HTTP resolution

* feat(examples): add EIP-712 signing support to offer-receipt server

- Add eip712-signer.ts using viem privateKeyToAccount
- Update jws-signer.ts to handle both PEM and DER base64 formats
- Update README with signing format table and key generation commands
- Update environment variables

* refactor(offer-receipt): use transportContext from PR #1101 instead of enrichDeclaration

* chore: update pnpm-lock.yaml for new dependencies

* Address PR feedback:

- Fix: use HTTPTransportContext instead of HTTPRequestContext
- Remove extractResourceUrl helper, inline transportContext access
- Remove specs/extensions/README.md
- Add getPaymentSettleResponse logging to offer-receipt client example
- Add changeset for @x402/extensions minor release

* fix: regenerate examples lockfile for broken solana dependency entry

---------

Co-authored-by: phdargen <pdargent@icloud.com>
2026-03-12 14:20:36 +09:00
Carson Roscoe
713907fce8
fix: remove facilitator from exact scheme witness struct (#1322)
* feat: remove facilitator from exact scheme witness struct

The facilitator field in the witness was only needed for the upto scheme
where settlement amounts are variable. For exact, the amount is always
the full permitted amount so no facilitator binding is necessary.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: re-mine vanity salts and deploy updated contracts to Base Sepolia

Exact: 0x402085c248EeA27D92E8b30b2C58ed07f9E20001
Upto: 0x402039b3d6E6BEC5A02c2C9fd937ac17A6940002
Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-03-11 16:20:20 -07:00
Notorious D.E.V.
7cd93d8bf5
Add in-memory cache for in-flight Solana txs (#1468)
* fix: add duplicate settlement mitigation for SVM across all SDKs

Introduce an in-memory SettlementCache to prevent a race condition on
Solana where the same payment transaction could be settled multiple
times before on-chain confirmation. The cache is shared across V1 and
V2 facilitator schemes so that cross-version duplicates are caught.

- Add SettlementCache with 120s TTL in TypeScript, Python, and Go
- Integrate cache check into facilitator settle paths (V1 and V2)
- Add unit tests for duplicate detection in all three languages
- Share cache across V1/V2 in Go facilitator example
- Add duplicate settlement spec to scheme_exact_svm.md
- Document SettlementCache in SVM READMEs for all three SDKs
- Document the race condition in go/FACILITATOR.md Security section
- Add merchant-facing guidance in docs/core-concepts/client-server.md
  and docs/core-concepts/facilitator.md for self-settling servers
- Fix JSDoc lint errors in TypeScript settlement-cache.ts

* refactor: optimize SettlementCache prune with early break on ordered entries

Leverage insertion-order guarantees of Map (TS) and dict (Python) to
break early once a non-expired entry is encountered, avoiding a full
scan of the cache on every isDuplicate call. Go is left unchanged since
map iteration order is not guaranteed.

Also adds prune-specific unit tests for all three SDKs covering:
- mixed expired/fresh entries
- all expired
- none expired
- insertion-order early-break correctness (Python)

* docs: add changelog entries for SVM duplicate settlement fix
2026-03-05 16:16:09 -08:00
phdargen
aeef1bff66
Custom settlement failures responses (#1430)
* py fix for 1176

* fix settle response body

* same for go/py

* fix format
2026-03-05 09:46:39 +09:00
fabda-cb
bb6174a213
Add upto payment scheme specification for EVM (#1074)
* Add upto payment scheme specification for EVM

Introduces the upto scheme which enables usage-based payments where
clients authorize a maximum amount and servers settle for the actual
amount used. This is ideal for variable-cost resources like LLM token
generation, bandwidth metering, or time-based access.

Key features:
- Uses Permit2 exclusively (permitWitnessTransferFrom)
- Client signs for max amount, server settles for actual usage
- Settlement amount can be 0 to amount (inclusive)
- Adds settledAmount field to SettlementResponse
- Reuses existing x402Permit2Proxy contract

* Link to existing x402Permit2Proxy contract instead of duplicating

* Clarify error codes: standard vs scheme-specific

- List standard x402 error codes that apply to upto scheme
- Add scheme-specific error codes following naming convention
- Add missing error codes for recipient mismatch and time validation

* Simplify error codes section and add SettlementResponse link

- Link to base SettlementResponse schema in main spec
- Reference standard error codes instead of duplicating
- Keep only the truly upto-specific error code: settlement_exceeds_amount

* docs(upto): add explicit MUST requirements for cross-network properties

- Add Core Properties (MUST) section with single-use, time-bound,
  recipient binding, and max amount enforcement requirements
- Add Out of Scope section clarifying what upto does NOT support
- Remove invalid use cases: streaming, time-based access, API rate metering
- Clarify remaining use cases as single-request patterns

Addresses PR feedback from @phdargen and @notorious-d-e-v

* docs(upto): rename settledAmount to amount in SettlementResponse

Rename for consistency with planned addition of amount field to base
SettlementResponse schema in x402-specification-v2.md (per PR feedback)

* docs(upto): clarify phase-dependent amount semantics in PaymentRequirements

The amount field in PaymentRequirements has different semantics at verify vs settle time for the upto scheme. At verification, it represents the max authorized amount. At settlement, it represents the actual amount to settle. This was ambiguous in the spec and is now explicitly documented across scheme_upto.md, scheme_upto_evm.md, and the main x402 v2 spec.
2026-03-04 02:08:38 +01:00
JumpboxTech
f41baed744
fix(specs,ts): add x402Version to facilitator verify/settle request body (#1312)
All four SDK implementations (TypeScript, Go, Go legacy, Python) include
x402Version as a top-level field in the facilitator /verify and /settle
request bodies, but neither the v1/v2 specs nor the TypeScript types
document it.

This adds x402Version to:
- v2 spec section 7.1 (POST /verify) request schema
- v1 spec section 7.1 (POST /verify) request schema
- VerifyRequest and SettleRequest types in @x402/core
- VerifyRequestV1 and SettleRequestV1 types in @x402/core

Closes #1176
2026-03-03 16:39:14 +09:00
Ryan R. Fox
5cb40cd08b
fix(exact): enforce strict amount equality per spec (#1388)
* fix(exact): enforce strict amount equality per spec

The exact scheme spec states the transferred amount MUST equal
PaymentRequirements.amount exactly. All four facilitators used < instead
of !==, silently accepting overpayments.

Changes:
- SVM V2: amount !== BigInt(requirements.amount), reason: amount_mismatch
- SVM V1: amount !== BigInt(requirementsV1.maxAmountRequired), reason: amount_mismatch
- EVM EIP-3009: authorization.value !== requirements.amount, reason: authorization_value_mismatch
- EVM Permit2: permitted.amount !== requirements.amount, reason: amount_mismatch

Error reasons renamed from _insufficient to _mismatch to cover both
directions (underpayment and overpayment).

Closes #1378

* fix(exact): also enforce strict amount equality in v1 EVM facilitator

Applies the same < to !== comparison change to the v1 EVM facilitator
for consistency with the v2 EVM and SVM facilitators.

* docs(spec): correct exact scheme amount validation description

Two inaccuracies in x402-specification-v2.md relative to the authoritative
scheme contract in specs/schemes/exact/scheme_exact.md:

- §6.1.2 step 3: 'meets or exceeds' -> 'exactly matches'
  The exact scheme requires strict equality (scheme_exact.md L24,
  scheme_exact_svm.md L143). This section describes the EVM implementation
  of the exact scheme, not the upto scheme.

- §9 error table: rename invalid_exact_evm_payload_authorization_value
  to invalid_exact_evm_payload_authorization_value_mismatch and update
  description from 'insufficient' to 'does not exactly match'.
  These error codes are EVM-scheme-layer codes; the table is updated
  to reflect the renamed code in the accompanying implementation change.

* style(evm): wrap long if condition in permit2.ts for prettier compliance
2026-03-03 14:40:07 +09:00
Cosimo Bassi
ec7e21d090
fix: JSON example syntax for transaction field in Algorand specs (#1201) 2026-02-23 12:16:02 +09:00
0x0v4
319dd8b72d
Update http.md (#1296) 2026-02-23 10:46:54 +09:00
Carson Roscoe
c4750db6d3
feat: added contracts/evm for exact evm permit2 update (#1009)
* feat: evm contracts for exact evm permit2 support

* feat: refactor permit2 proxy passing from constructor to initializer

* feat: validate EIP-2612 permit value matches Permit2 permitted amount

* feat: gate initialize() to original deployer to prevent frontrunning

* feat: add permit2 to submodule

* fix: reject zero-amount settlements to prevent no-op nonce consumption

* fix: remove extra field from Witness struct to eliminate unbounded calldata gas griefing

* refactor: rename _settle() amount parameter to settlementAmount for clarity

* fix: emit EIP2612PermitFailed event on permit failure for observability

* refactor: rename PERMIT2 state variable to permit2 per Solidity naming conventions

* fix: add facilitator to Witness struct to prevent settlement frontrunning and amount griefing

* fix: remove tx.origin from constructor to support multisig deployment

* fix: formatting

* fix: use granular try/catch for EIP-2612 permit failure observability

* fix: replace unguarded initialize() with constructor to prevent cross-chain deployment griefing

* fix: rename permit2 to PERMIT2

* feat: remined salt & redeploy to base-sepolia

* feat: updated exact evm spec

* fix: reverted gitignore change (to avoid rebase, ensure commit hashes match audit report)

* feat: added contract audit report

* chore: renamed audit report file
2026-02-20 10:42:15 -05:00
A. McDermott
15dc2cd156
feat: Add MCP tool support to bazaar extension spec (#1134)
* feat(bazaar): add MCP tool support to discovery extension spec

Add documentation for cataloging MCP tools alongside HTTP endpoints.
MCP tools use a simpler structure with just tool name and inputSchema,
without the method/body/queryParams split needed for HTTP.

* Clarify waht kind of tools

* Update spec and resource notes
2026-02-19 17:45:57 -05:00
Jon
57a5488bcb
Add Aptos payment mechanism (#966)
* Add Aptos mechanism implementation for x402

* Revert go changes

* Fix go revert

* Fix e2e imports

* Add aptos to all server e2e tests, make optional

* Make aptos optional on site

* Fix lint / format issues

* Add workflow for x402 aptos package

* Update e2e tests

* Fix facilitator manager
2026-02-19 15:29:43 -05:00
Peter Swierzy
ae26f5e1f3
feat: Implement exact payment scheme specification for Hedera HTS FT … (#792)
* feat: Implement exact payment scheme specification for Hedera HTS FT and HBAR token

Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>

* docs: Update Hedera exact scheme specification to include amount transfer details and account alias handling- Added clarification on the  field for HBAR and HTS fungible tokens.- Specified that the decompiled transaction must be a  directly.- Introduced a section on account aliases and auto-account creation, outlining potential risks and facilitator options.

Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>

---------

Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
2026-02-06 23:04:39 +09:00
A. McDermott
e07b085852
feat: Add payment-identifier extension spec (#1053)
* Add payment-identifier extension spec

* feat: add required field

---------

Co-authored-by: CarsonRoscoe <carsonroscoe7@gmail.com>
2026-02-05 11:16:46 -08:00
Carson Roscoe
b74dd05215
feat: update mcp spec (#1075)
* feat: update mcp spec

* feat: content is required, structuredContent is optional

* fix: update spec
2026-02-03 15:01:48 -08:00
Sam Ragsdale
fe42994900
feat(extensions): SIWX Extension (#921)
* feat(extensions): add Sign-In-With-X (SIWX) extension

Implements CAIP-122 compliant wallet-based identity assertions for x402 v2.

- Add SIWX types following CAIP-122 standard
- Server-side: declareSIWxExtension() for 402 response generation
- Client-side: createSIWxPayload() for proof creation and signing
- Message construction following CAIP-122 format
- Header encoding/parsing (base64 per x402 v2 spec)
- Validation: temporal, domain binding, nonce checking
- Verification: cryptographic signature validation via siwe library
- JSON Schema generation for payload validation
- Test coverage for core flows

* simplify; remove future looking code

* add integration test

* address own comments

* update readme, rm TODO.md

* add SIWS

* cleanup

* further cleanup

* split code path btwn evm and solana

* mv solana constants

* fmt

* lint

* rm .claude

* smart wallet verifier

* add domain param; support outside EVM verifier for contract wallets; Solana CAIP-2 compliant; rm clockskew slop

* fix missing type field; update lock file

* Add Sign-In-With-X extension spec

* server & client siwx examples

* chore: update pnpm-lock.yaml for sign-in-with-x examples

Update lockfile to include @types/node added to client example.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* Add wrapFetchWithSIWx helper to @x402/extensions

Adds a fetch wrapper for SIWX authentication that mirrors the
wrapFetchWithPayment pattern from @x402/fetch. The wrapper
automatically handles 402 responses with SIWX extension info.

Changes:
- Add fetch.ts with wrapFetchWithSIWx function
- Export wrapFetchWithSIWx from sign-in-with-x index
- Add DOM lib to tsconfig for Request/Response types
- Simplify client example to use the new wrapper
- Add .prettierignore and eslint globals to match other examples

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* feat(extensions/siwx): Add lifecycle hooks for simplified DevX

Adds pre-built hooks that integrate SIWX with x402's lifecycle system:

- SIWxStorage interface + InMemorySIWxStorage for tracking paid addresses
- createSIWxSettleHook: records payments after settlement
- createSIWxRequestHook: validates SIWX auth before payment processing
- createSIWxClientHook: automatically tries SIWX auth on 402 responses

Simplifies examples dramatically by removing custom middleware in favor
of composable hooks that plug into the standard x402 lifecycle.

* fix(extensions/siwx): Improve hooks robustness and add tests

- Extract payer address from multiple payload formats (EVM, Solana)
- Add onEvent callback for logging/debugging
- Handle header case-insensitivity
- Add comprehensive tests for storage and all three hooks

* fix(extensions/siwx): Only record payment if settlement succeeded

Previously, createSIWxSettleHook would record payments even when
settlement failed, allowing free access to users who attempted
payment but failed. Now checks ctx.result.success before recording.

* style: Fix JSDoc and lint errors

* style: Fix formatting and JSDoc in examples

* refactor(extensions/siwx): Migrate to supportedChains[] architecture

Implements reviewer feedback (phdargen) on multi-chain architecture for
SIWX extension, separating message metadata from authentication capabilities.

- **NEW**: SupportedChain interface with chainId, type, signatureScheme
- **CHANGED**: SIWxExtensionInfo no longer includes chainId/type/signatureScheme
- **CHANGED**: SIWxExtension now has supportedChains[] array
- **CHANGED**: declareSIWxExtension accepts string|string[] for network param
- **CHANGED**: expirationTime (absolute) → expirationSeconds (relative)

- **server.ts**: siwxResourceServerExtension with enrichDeclaration hook
  - Refreshes nonce, issuedAt, expirationTime per request
  - Fixes critical bug where time-based fields never updated after startup

- **NEW**: CompleteSIWxInfo type = SIWxExtensionInfo + chain fields
- **CHANGED**: createSIWxClientHook uses exact chain matching via supportedChains
- **CHANGED**: fetch wrapper matches signer chain with supportedChains
- Updated utility functions (message, evm, solana) to use CompleteSIWxInfo

- All 65 SIWX tests updated for supportedChains[] structure
- Added multi-chain test coverage
- All tests passing (120/120 total)

- Updated spec with supportedChains[] examples
- Added multi-chain example in spec
- Updated README with hook-based approach (recommended)
- Added manual usage examples for advanced use cases
- Updated API reference with new parameters

- Server example updated to use siwxResourceServerExtension
- Client example unchanged (hook handles supportedChains internally)

- ✅ Single shared nonce (correct replay semantics)
- ✅ No metadata duplication (domain/uri/statement shared)
- ✅ Exact chain matching (no heuristics)
- ✅ 83% wire size reduction for 10-chain configurations
- ✅ Aligns with CAIP-122 mental model

- Extension structure: info no longer has chainId/type
- Clients must use supportedChains to find matching chain
- declareSIWxExtension: expirationTime → expirationSeconds
- Servers must call .registerExtension(siwxResourceServerExtension)

BREAKING CHANGE: First version - no migration needed

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

* fix(examples): Add getChainId() to signer for proper SIWX chain matching

Without this method, the client hook falls back to eip155:1 which doesn't
match the server's eip155:84532 (Base Sepolia), preventing SIWX auth from
working.

* refactor(extensions/siwx): Extract duplicated getSignerChainId helper

- Extract getSignerChainId to sign.ts (shared location)
- Remove duplicate from hooks.ts (-16 lines)
- Remove duplicate from fetch.ts (-14 lines)
- Net: -5 lines, eliminates code duplication

Co-locates all signer utilities (getEVMAddress, getSolanaAddress,
signEVMMessage, signSolanaMessage, getSignerChainId) in sign.ts for
better discoverability and maintainability.

* feat(examples/siwx): Add payment header logging to client

Shows whether each request used payment settlement or SIWX auth
by checking for PAYMENT-RESPONSE header. Helps debug auth flow.

* fix(examples/siwx): Improve payment flow logging

- Properly distinguish between payment success, payment failure, and SIWX auth
- Check body.error to detect payment failures (no PAYMENT-RESPONSE header)
- Bug investigation: Rapid successive payments fail with transaction_failed

Investigation findings:
- Wallet has sufficient funds (0.009 ETH, 0.984 USDC)
- EIP-3009 nonces are randomly generated (no collisions possible)
- Issue only occurs with rapid successive requests
- 2-second delay between requests works around the issue
- Facilitator returns generic 'transaction_failed' without detailed error

Likely cause: Race condition in facilitator's blockchain transaction
submission when handling concurrent payment authorizations.

Next steps: Need facilitator-level debugging to see actual error details.

* fix(examples/siwx): Add 300ms delay to avoid facilitator race condition

Testing shows 300ms is sufficient to work around the rapid payment issue.
Without delay: second payment fails with transaction_failed.
With 300ms: both payments succeed consistently.

This minimal delay allows the facilitator to properly handle concurrent
payment authorizations without blockchain transaction nonce conflicts.

* refactor(extensions/siwx): Use payment network instead of signer chain detection

Simplify SIWX by deriving chain from paymentRequired.accepts[0].network
instead of requiring signers to implement getChainId(). This removes
the need for the Object.assign hack in client code.

- Update createSIWxClientHook to use network from payment requirements
- Update wrapFetchWithSIWx similarly
- Remove unused getSignerChainId helper
- Simplify example client code

* refactor(extensions/siwx): Auto-derive network/domain/uri from context

Make declareSIWxExtension fields optional - they're now derived automatically
from request context by siwxResourceServerExtension:
- network: from accepts[].network in route config
- resourceUri: from request URL
- domain: parsed from resourceUri

This eliminates redundant configuration and reduces chance of mismatches.
Explicit values still override automatic derivation.

* refactor(extensions/siwx): Remove time-based fields from declareSIWxExtension

Time-based fields (nonce, issuedAt, expirationTime) are now generated
per-request by enrichPaymentRequiredResponse instead of at declaration
time. This ensures fresh nonces and accurate timestamps for each request.

- Remove nonce/issuedAt generation from declareSIWxExtension
- Store expirationSeconds in _options for per-request calculation
- Update tests to use generateTimeBasedFields helper to simulate
  server extension behavior

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

* docs(extensions/siwx): Add smart wallet docs, align signature schemes

- Remove sep10 and eip712 from supported signature schemes (not implemented)
- Add documentation for EIP-1271/EIP-6492 smart wallet verification
- Show how to use verifyOptions with createSIWxRequestHook
- Fix domain validation to use hostname instead of host (removes port)
- Add logging to example server for SIWX events
- Add tests for siwxResourceServerExtension

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

* chore: regenerate pnpm lockfile

Fixes ERR_PNPM_LOCKFILE_CONFIG_MISMATCH error in CI where the
"overrides" configuration didn't match the lockfile.

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

* fix(examples/siwx): Add missing JSDoc to onEvent function

* fix(extensions/siwx): Use result.payer instead of extracting from payload

The SVM payment payload is just `{ transaction: string }` with no payer
field. The payer address is extracted by the facilitator during settlement
and returned in the SettleResponse.payer field.

This fix:
- Removes extractPayerAddress() which incorrectly assumed payload.payer exists
- Uses ctx.result.payer from the facilitator's settle response
- Updates tests to pass payer in result object

This ensures SIWX works correctly for both EVM and SVM payment flows.

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

* feat(extensions/siwx): Add optional nonce tracking to prevent replay attacks

Adds optional hasUsedNonce/recordNonce methods to SIWxStorage interface
to prevent signature replay attacks. When a valid SIWX signature is
intercepted, it could be reused by an attacker to access resources
without paying.

Changes:
- Add optional hasUsedNonce?(nonce) and recordNonce?(nonce) to SIWxStorage
- Update createSIWxRequestHook to check/record nonces if methods exist
- Add nonce_reused event type for logging
- InMemorySIWxStorage unchanged (servers implement if they want protection)

This is opt-in: servers that want replay protection implement the
nonce methods in their storage. Servers without nonce tracking continue
to work as before.

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

* chore: Add changeset for SIWX extension

* fix(examples/siwx): Add missing JSDoc params for onEvent function

* fix(extensions/siwx): Require both nonce methods or neither

Throw error at hook creation if only one of hasUsedNonce/recordNonce
is implemented, preventing silent failure of replay protection.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-03 08:39:02 +09:00
Marcelo Salloum dos Santos
ae8be5062e
Add Stellar scheme specification for x402 v2 exact (#941)
* Add Stellar scheme specification for x402 v2 exact

* Add link to the sequence number definition, and remove unused link

* Polish flow based on internal review from the Stellar Development Foundation

1. Remove `maxLedgerOffset` and calculate expiration ledger based on `maxTimeoutSeconds`.
2. Make it clear that facilitator's `/settle` should not assume prior validation and the flow doesn't need to go through `/validate`
3. Add an important check that ensures the simulation emits the expected transfer/balance events

* Updated scheme_exact.md with the latest changes of scheme_exact_stellar.md

* Address review suggestions.
2026-01-29 09:40:34 +09:00
aptum11
ff9e20311a
feat(svm): allow Phantom and Solflare Lighthouse instructions in transaction verification (#991)
Phantom and Solflare wallets inject Lighthouse program instructions for user
protection on Solana mainnet transactions. This causes x402 verification to fail
because the scheme expects exactly 3 instructions.

This change allows optional 4th and 5th instructions specifically from the
Lighthouse program (L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95):
- 4th instruction: Phantom wallet protection (1 Lighthouse instruction)
- 5th instruction: Solflare wallet protection (adds 2 Lighthouse instructions)

Changes:
- Add LIGHTHOUSE_PROGRAM_ADDRESS constant (TypeScript and Go)
- Update ExactSvmScheme verify to allow 3-5 instructions
- Update ExactSvmSchemeV1 verify to allow 3-5 instructions
- Reject any 4th/5th instruction that is not from Lighthouse program
- Add error constants for unknown 4th/5th instructions
- Update scheme_exact_svm.md spec to reflect changes

Fixes: #828
2026-01-27 11:38:59 -08:00
ehanoc
ce1b9fcf0f
docs: Algorand scheme spec proposal (#361)
Co-authored-by: cusma <cosimo.bassi@algorand.foundation>
Co-authored-by: tasosbit <tasos.bitsios@algorand.foundation>
Co-authored-by: nullun <steve.ferrigno@algorand.foundation>
Co-authored-by: emg110 <emg110@gmail.com>
2026-01-26 14:34:58 -08:00
phdargen
29aa4135c4
New hooks for extensions to enrich payment-required and payment-response (#1003)
* new extension hooks

* updated hook args

* update tests

* remove verify hook

* fix workflows

* update specs
2026-01-23 11:24:20 -08:00
Carson Roscoe
a28f9dcae1
feat: added bazaar extension spec (#956)
* feat: added bazaar extension spec

* feat: pr feedback
2026-01-16 08:31:19 +09:00
Jon
07a5491015
Add Aptos exact scheme (#896)
* Add Aptos exact scheme specification

Adds the exact payment scheme specification for Aptos blockchain:
- Uses Aptos fungible asset transfer (0x1::primary_fungible_store::transfer)
- Supports sponsored transactions via extra.sponsored field
- Facilitators can implement as direct fee payer or gas station service
- Follows x402 v2 protocol with CAIP-2 network identifiers (aptos:1, aptos:2)
- Includes security notes on fee payer mechanism

* Update Aptos spec to use sponsored: true instead of gasStation URL

- Replace gasStation URL with simple sponsored: true boolean in extra
- Clarify facilitator can use direct fee payer or gas station service internally
- Add security note about fee payer mechanism
- Link to Aptos sponsored transactions documentation
- Remove version field from PAYMENT-RESPONSE (consistent with other chains)
- Separate sponsored vs non-sponsored flows in appendix

* Adjust spec
2026-01-13 04:05:17 -08:00
fabda-cb
f9e675ad0a
Feature: Add Permit2 Support to Exact EVM Scheme (#769)
* Add Permit2 Spec + Extension Specs

* merge master

* add Permit2 Exact EVM

* fix typos

* update text

* patch react/next (#772)

* update from permit2 scheme to permitType

* fix payload scheme to remain exact and put permitType in extra

* rename permitType to AssetTranserMethod

* enforce batch for gas sponsoring textensions

* add canonical address reference + x402PermitProxy deployment processes

---------

Co-authored-by: phdargen <p.dargent@cern.ch>
2026-01-08 11:57:55 +01:00
Notorious D.E.V.
d5e516fd2f
Update exact scheme requirements for SVM (#903)
Removed optional ATA Create from the exact scheme requirements.
2026-01-05 16:49:09 +01:00
iPLAY888
719680037a
docs: fixes broken path to file (#840)
* Update http.md

* Update http.md
2025-12-22 15:27:29 +01:00
Carson Roscoe
1a79feaf94
Development v2 (#705)
* chore: move packages, examples and e2e clients/servers/facilitators to legacy subfolders

* feat: added @x402/core to /typescript/packages

* feat: added @x402/evm to /typescript/packages/mechanism

* feat: added @x402/svm to /typescript/packages/mechanism

* feat: added @x402/extensions to /typescript/packages

* feat: added @x402/fetch to /typescript/packages/http

* feat: added @x402/axios to /typescript/packages/http

* feat: added @x402/paywall to /typescript/packages/http

* feat: added @x402/express to /typescript/packages/http

* feat: added @x402/hono to /typescript/packages/http

* feat: added @x402/next to /typescript/packages/http

* chore: update /typescript pnpm packaging

* feat: added core files to /go

* feat: added evm mechanism to /go

* feat: added svm mechanism to /go

* feat: added extensions to /go

* feat: added gin to /go/http

* feat: added tests to /go

* feat: rewrote e2e test suite system

* feat: added axios client to e2e suite

* feat: added fetch client to e2e suite

* feat: added go http client to e2e suite

* feat: added express server to e2e suite

* feat: added hono server to e2e suite

* feat: added next server to e2e suite

* feat: added gin server to e2e suite

* feat: added typescript facilitator to e2e suite

* feat: added go facilitator to e2e suite

* feat: added fetch example to examples/typescript/clients

* feat: added axios example to examples/typescript/clients

* feat: added advanced example to examples/typescript/clients

* feat: added custom example to examples/typescript/clients

* feat: added express example to examples/typescript/servers

* feat: added hono example to examples/typescript/servers

* feat: added advanced example to examples/typescript/servers

* feat: added custom example to examples/typescript/servers

* feat: added facilitator example to examples/typescript

* chore: update /examples/typescript pnpm packaging

* feat: added http client to examples/go/clients

* feat: added advanced client to examples/go/clients

* feat: added custom client to examples/go/clients

* feat: added gin server to examples/go/servers

* feat: added advanced server to examples/go/servers

* feat: added custom server to examples/go/servers

* feat: added facilitator to examples/go

* chore: updated github workflows

* fix: typescript examples fotmat/lint

* v2: next example (#706)

* fix legacy example builds

* add next example

* fix format

* upgrade to next 16

* fix legacy build

* fix e2e tests

* V2: next api wrapper (#707)

* add next route wrapper

* add protected api to example page

* add unit tests

* fix missing settle failure check

* added e2e tests for withX402

* add SettleResponse to ProcessSettleResultResponse

* add requirements to payment-header

* feat: add v2 support to x402.org facilitator

* feat: dynamically load bazaar extension in Next only when used

* fix: x402Facilitator in typescript calling onAfterVerify instead on onVerifyFailure on failure

* feat: add ERC1271 and ERC6492 support to Typescript facilitator

* feat: update typescript facilitator example & e2e test for ERC1271/ERC6492 support

* feat: add ERC1271 and ERC6492 support to Go facilitators

* feat: update go facilitator example & e2e test for ERC1271/ERC6492 support

* v2: express fixes + unit tests  (#712)

* add express fixes from v1

* add units test for express/hono

* added fetch/axios unit tests

* v2: Clean up paywall (#710)

* Remove cdpClientKey and sessionTokenEndpoint from PaywallConfig

Remove Onramp functionality from EvmPaywall

Remove Coinbase fields from paywall template generation

* Migrate site to @x402/next with v2 protocol support

* Clean up tests

* remove CDP onramp from core paywall

* Update templates and build process

* Format

* Lockfile

* mock templates for CI

* Format

* Generate new templates

* Format

* v2: facilitator sync fix (#716)

* update next/react versions

* update site to next 16, tailwind 4 and fix env vars

* fix initializeOnStart pattern

* security: bump quic-go dependency for security fix GHSA-47m2-4cr7-mhcw

* v2:fix ts advanced/custom examples (#717)

* fix ts examples

* add clients/advanced/preferred-network example

* feat: improved e2e cli for external facilitator testing

* feat: updated evm & svm signer interfaces in go

* feat: updated evm & svm signer interfaces in typescript

* feat: reverted SupportedKind's kinds structure in go

* feat: reverted SupportedKind's kinds structure in typescript

* feat: refactor facilitator SVM signer interface in typescript

* go example fixes (#719)

* feat: cleanup go bazaar extension

* V2: docs update (#729)

* ts example docs

* improve ts package docs

* feat: dynamic bazaar import for all server middleware

* feat: allow dynamic response building for 402 response in typescript

* feat: allow dynamic response building for 402 response in go

* feat: added withBazaar HTTPFacilitatorClient wrapper

* feat: added linting to go

* fix: lint go

* improve go example docs (#733)

* feat: Solana PR review feedback in typescript

* feat: Solana PR review feedback in go

* fix: locks & paywall gen after rebase off main

* fix: format

* docs: improve @x402/extensions README with comprehensive documentation (#731)

* First draft of contributor docs (#738)

Correct ts contributing

Clean up contribution guidelines

* feat: updated specs for v2

* fix: merge with main, fixed lock

* v2: go settlement failure and initOnStart fixes (#720)

* go settlement failure and initOnStart fixes

* update go unit tests

* update readmes

* feat: review & improve examples & READMEs

* v2: add multiple payment options for go (#743)

* add multiple payment options for go

* fix SyncFacilitatorOnStart

* v2: add hooks for advanced go example (#745)

* add hooks for advanced go example

* fix legacy ts deps

* feat: added server initialization validation

* feat: added @x402 package workflows

* v2: add miniapp and mcp examples (#746)

* add miniapp example

* fix format

* add mcp example

* fix format

* v2: add manifest to miniapp example (#751)

* add manifest to miniapp

* fix format

* feat: x402 website redesign (#750)

* port new website to public repo

* chore: update pnpm-lock.yaml with motion dependency

* feat: add x402 V2 launch blog post and update hero code snippet

- Add /writing/x402-v2-launch blog post page
- Add blog images (blog_intro.png, blog_x402_layers.png, homepage_build5.png)
- Enable Writing nav link in NavBar and Footer
- Update hero code snippet to show V2 SDK usage
- Fix CodeSnippet to support multi-line code

* feat: edit nav for mobile

* Revert "feat: edit nav for mobile"

This reverts commit 475999a2a84f1fab875cd0fe2bb74d44dba7e1bd.

* feat: add ecosystem page and minor home page tweaks

* feat: fix typography in ecosystem

* homepage qa fixes

* feat: add ecosystem icons and fix halftone

* cleanup assets

* fix: minor bug on faq

* feat: add hamburger menu to mobile

* Update README (#755)

* Update readme

* Install instructions and typos

* feat: update site sample code & reduce supported networks

* fix: v1 header in README updated to v2

---------

Co-authored-by: phdargen <p.dargent@cern.ch>
Co-authored-by: A. McDermott <amanda.p.mcdermott@gmail.com>
Co-authored-by: Vedant Anand <136731196+VedantAnand17@users.noreply.github.com>
Co-authored-by: Faris Habib <frs@hbb.dev>
Co-authored-by: erikreppel-cb <erik.reppel@coinbase.com>
2025-12-11 07:41:57 -08:00
Notorious D.E.V.
8b54700a08
docs: Revise instruction count to 3 for SVM payments (#667)
Updated instruction count requirement for exact-scheme SVM payments.
2025-11-25 13:57:47 -05:00
Notorious D.E.V.
d7042f3208
docs(svm): document facilitator fee payer guards; tests(svm): add fee payer validation tests and fix mocks to Instruction accounts array; chore: align high-level tests with signer-aware verification (#546) 2025-10-29 15:14:19 -07:00
Ethan Niser
1f860be651
Transport-Agnostic x402 (#417) 2025-10-03 10:22:38 -07:00
Alfred Tom
fd3cbf7fb1
docs: Add x402 protocol specification to specs folder. This was derived from the current state of the repository. (#354) 2025-09-17 16:20:55 -04:00
Notorious D.E.V.
26f132bf4f
131 add solana support (#283)
* feat: implement exact payment scheme for Solana Virtual Machine (SVM)

- Added new SVM payment scheme documentation.
- Added stubs for client and facilitator logic for the exact payment scheme.
- Updated facilitator to support both EVM and SVM networks.
- Enhanced network type definitions to include Solana networks.
- Updated .gitignore to exclude cursor directory.

* feat: enhance payment processing for Solana and EVM networks

- Updated payment verification and settlement functions to support ExactSvmPayload for SVM networks.
- Refactored facilitator logic to handle both EVM and SVM networks more effectively.
- Introduced new SPLTokenAmount type for Solana token handling.
- Enhanced network type definitions to include enums for better clarity and usage.
- Added new utility functions for encoding and decoding payment payloads.
- Implemented middleware updates to accommodate new payment structures and requirements.
- Improved error handling and validation for payment payloads across different networks.

* feat: enhance SVM payment processing and utility functions

- Added support for the @solana/kit package to facilitate payment processing for Solana networks.
- Introduced getFeePayer function to retrieve the fee payer address for SVM payments.
- Updated payment requirements validation to include SVM address regex.
- Refactored existing functions to improve clarity and maintainability.
- Added new regex utilities for SVM address and transaction signature validation.
- Enhanced the useFacilitator hook to include fee payer retrieval functionality.
- Removed the facilitator-driven flow because it won't be possible since the client (buyer's) address is not known in the first request to the server.

* chore: moved "examples/typescript/facilitator" to "examples/typescript/facilitators/evm/express" in preparation for adding an express solana facilitator example

* feat: add SVM express facilitator example and enhance package structure

- Introduced a new SVM express facilitator example with endpoints for payment verification, settlement, and getting the fee payer address.
- Updated package.json files to reflect new naming conventions and dependencies.
- Added ESLint and Prettier configurations for code quality and formatting.
- Created .env and README files for setup instructions and environment variable management.
- Enhanced pnpm workspace configuration to include all facilitators.
- Updated pnpm-lock.yaml with new dependencies and versions for improved compatibility.

* fix: Introduced a new mixedAddressOrSvmAddress regex for improved asset validation in PaymentRequirementsSchema.
- Updated getFeePayer function to accept PaymentRequirements and changed the HTTP method to POST for fee payer retrieval.

* feat: enhance x402-express tests to test that a feePayer is returned to the client when the client does not provide an X-PAYMENT header.

* feat: enhance x402 package with SVM support for the client

- Added support for the Solana Virtual Machine (SVM) in the x402 package, including new client and utility functions for payment processing.
- Introduced a new payment header creation function for SVM and refactored existing functions to accommodate both EVM and SVM networks.
- Updated package dependencies and configurations to include necessary libraries for SVM functionality.
- Enhanced tests to cover new SVM features and ensure robust payment processing across different networks.

* fix: update feePayer handling in paymentMiddleware to ensure correct response structure

- Modified the paymentMiddleware function to correctly assign the feePayer from the response object.
- Updated tests to reflect changes in feePayer handling, ensuring that the feePayer is accessed from the response structure.

* fix: export signer module in SVM index

* feat: implement SVM payment verification

- Updated the `verify` function to support SVM networks, including validation of transaction payloads and instructions.
- Added new error reasons for SVM payload validation failures to improve error handling.
- Introduced transaction message creation and signing processes to accommodate both token-2022 and legacy token programs.
- Enhanced middleware to ensure compatibility with updated network enums for Solana.

* feat: enhance facilitator verification and testing for SVM transactions

- Added the `@solana-program/token` dependency to support spl-token operations.
- Refactored the `verify` function to streamline transaction decoding and validation processes.
- Introduced a new `decodeTransaction` function for better transaction handling.
- Enhanced error handling in the `verify` function to provide more specific error reasons.
- Updated tests to cover new transaction decoding and validation logic, ensuring robust functionality for SVM payments.

* feat: enhance SVM settlement functionality and error handling

- Updated the `settle` function in the SVM facilitator to handle transaction signing and confirmation with blockhash lifetime constraints.
- Improved error handling for transaction confirmation timeouts and block height exceedance.
- Added new error reasons for SVM payload validation failures to enhance feedback during settlement processes.

* feat: refactor SVM facilitator structure and enhance testing

- Removed the old `facilitator.test.ts` file and replaced it with a new structure under `facilitator/` for better organization.
- Introduced new `feePayer.ts` and `verify.ts` modules to encapsulate related functionalities and improve code maintainability.
- Updated the `index.ts` file to reflect the new module structure, enhancing clarity and accessibility of the SVM facilitator's exports.

* feat: enhance SVM facilitator testing around settle function

- added tests covering various scenarios including payment settlement and transaction confirmation.
- Improved the structure of the `settle` function to utilize the new transaction confirmation features, ensuring robust error handling and feedback during settlement processes.

* feat: add RPC subscription functionality

- Introduced a new `getRpcSubscriptions` function in `rpc.ts` to manage RPC subscriptions for different networks, enhancing modularity and reusability.
- Added TODO comments in `settle.ts` to consider moving some transaction handling functionality to the new `rpc.ts` file for better organization and maintainability.

* feat: enhance paymentMiddleware error handling and testing

- Added tests to verify the behavior of the paymentMiddleware when payment verification and settlement throw errors, ensuring proper 402 responses with detailed error information.
- Updated the paymentMiddleware function to handle unsuccessful settlements and log errors to the console for better debugging.

* feat: update svm facilitator example to call settle with the correct values.

Added logging to the evm facilitator example for unexpected errors.

* refactor: update and resolve TODO comments

* format: pnpm format and pnpm lint

* refactor: verify exact svm function to be more readable

* feat: add unit tests for paymentUtils encoding and decoding functions

* format: lint and format new changes

* format: pnpm format

* format: pnpm format && pnpm lint

* fix: update pnpm-lock.yaml

* fix: failing tests after merging main

* fix: failing tests after merging main, and format and lint.

* fix: refactor payment middleware to send a defined paymentRequirement payload to the getFeePayer call

* format: pnpm format

* fix: polishing up code for pull request

* format: pnpm format

* fix: remove NetworkEnum type and all of its references

* format: pnpm format && pnpm lint

* chore: update pnpm lock files for TypeScript and examples

* fix: Batched RPC calls during verification for fetching sender and receiver ATAs, saving 1 RPC call

* feat: Enhance SVM client by making 1 RPC call to fetch token info and decimals instead of 2

* feat: enhance the verification performed by the facilitator to check for a compute budget limit (gas limit) and compute budget price (priority fee) in the transaction.

Update the client to include compute budget limit and compute budget price instructions  in the transaction.

* feat: enhance transaction verification on SVM by adding support for create ATA instructions.

* feat: implement create ATA functionality for both token and token-2022 in SVM client, enhancing transaction instructions and error handling for missing feePayer.

* chore: update pnpm-lock.yaml

* chore: rename solana-mainnet to solana

* chore: refactored facilitator example for SVM to be one file instead of an entire package

* chore: undo some unnecessary changes

* chore: pnpm format

* chore: undo the refactor of paymentUtils location and add a TODO for it to be done in a separate issue

* chore: remove uncalled for refactoring

* feat: enhance the SVM priority fee logic to be a flat 1 microlamport per compute unit. More complex logic can be implemented in the future.

Set an upper limit of 5 lamports per compute unit on the facilitator so that the client cannot abuse the facilitator for priority fees.

* fix: facilitator waits for a commitment of 'confirmed' instead of 'finalized' before letting the server know that the tx has been included. Transactions with commitment level 'confirmed' can't be rolled back so it is good enough and faster.

* refactor: update the solana create ATA function and transfer function to accept the token program address, leading to 2 functions instead of 4

* chore: remove unnecessary mock

* chore: remove unnecessary change

* feat: add 'supported' method in useFacilitator to make a GET /supported request to the given (or default) facilitator.

* feat: enhance the PaymentKindsResponse from the facilitator to include an optional 'extra' field that contains metadata from the facilitator to the server regarding the selected network and scheme

- Update the useFacilitator function to support the '/supported' endpoint from the facilitator.

- Update the facilitator express example for solana to show how to return the feePayer as part of the GET /supported response

- Add an example for a server/merchant to run the express middleware on solana

* fix: failing tests after merging main branch

* chore: update pnpm-lock.yaml for examples after adding @solana/addresses to the examples for express servers

* feat: remove the get fee payer endpoint from the facilitator as part of the refactor to use the /supported endpoint instead, returning the feePayer as part of the extra field

* chore: unify evm and svm express server examples

* feat: refactor x402 facilitator and client examples to support new signer and wallet structure

- Unified the interface for signers/wallets and connected clients between evm and svm, and updated examples to use the new unified interface.
- Updated the facilitator example to use the new `createSigner` and `createConnectedClient` functions for better integration with both EVM and SVM networks.
- Removed the Solana-specific implementation from the facilitator and client examples,.
- Enhanced the `README` files to reflect the changes in API endpoints and setup instructions.
- Updated `pnpm-lock.yaml` to include new dependencies and versions for the x402 and x402-fetch packages.

* feat: enhance facilitator to support multiple private keys for EVM and SVM networks

- Updated the facilitator example to allow the use of separate private keys for Ethereum (EVM) and Solana (SVM) networks.
- Modified the environment variable requirements in the README to reflect the new private key structure.
- Adjusted the logic in the facilitator's API endpoints to dynamically select the appropriate client or signer based on the requested network.
- Improved type definitions for signers to ensure compatibility with both EVM and SVM networks.

* feat: add support for svm networks in x402-hono and x402-next and update the tests and examples to match.

* chore: update dependencies and refactor imports in TypeScript examples

- Removed unused dependencies from clients/fetch and updated package.json accordingly.
- Consolidated imports in clients/fetch/index.ts for cleaner code.
- Added new dependency '@scure/base' to support base58 decoding in wallet.ts.
- Updated pnpm-lock.yaml to reflect the changes in dependencies and versions.

* feat: enhance payment header functions to support multi-network signers

- Updated `selectPaymentRequirements` function to accept an array of networks for more flexible filtering.
- Refactored `createPaymentHeader` and `signPaymentHeader` functions to accept `Signer` and `MultiNetworkSigner` types, improving compatibility with both EVM and SVM networks.
- Added validation checks for the provided client type to ensure correct wallet usage.
- Introduced a new test file for `selectPaymentRequirements` to validate the selection logic across different network scenarios, including prioritization of USDC requirements.

* feat: update axios client example to utilize new signer structure and enhance payment handling

- Integrated the `createSigner` function to support both EVM and SVM networks in the axios client example.
- Removed the dependency on `viem` and adjusted the private key handling to accommodate the new type definitions.
- Updated the example to include detailed comments on environment variable requirements for better clarity.
- Enhanced the test suite for `withPaymentInterceptor` to validate the handling of multi-network signers and payment requirements.

* feat: add multi-network signer examples for axios and fetch clients

- Introduced new example files for multi-network signing using both axios and fetch clients, demonstrating how to handle requests requiring payment across EVM and SVM networks.
- Updated package.json for both clients to include new scripts for the multi-network signer examples.
2025-08-29 17:43:13 -07:00
Brandon Williams
bce47eeebc
feat: define 'exact' scheme for sui (#165)
* feat: define 'exact' scheme for sui

Define the initial specification to be used for the 'exact' scheme for
the Sui Blockchain.

This specification is designed to be optimially flexible for clients to
be able to fully leverage PTBs (Programmable Transaction Blocks) to
either provide a direct payment or perform a set of operations to swap
from one asset to the asset expected by the resource server. It also
provides the optionality for leveraging sponsorship/gas-less
transactions.

* sui: add flow diagram for sui exact scheme
2025-06-18 09:09:54 -07:00
Xavier Leprêtre
4161095926
Fix typos, readability. (#171) 2025-05-15 16:29:51 -04:00
Carson Roscoe
22ef54628c
feat: review readmes (#94)
* feat: cleaned up READMEs in examples

* fix: exact scheme readme

* feat: added philosophy and goal sections to readme

* feat: improved running the example section

* feat: renamed payToAddress to payTo as middleware param

* fix: moved terms below principals

* fead: improved x402 README for manual server and client integrations

* feat: tightened up the package READMEs

* fix: hono .env-local

* Updates to readmes  (#95)

* Updated readmes and code snippets

* fixed agent readme (but not working code)

* lint and formatting

* adding back env-localk

* fixing env-local

* fix: removed philosophy/principals section as another PR will introduce it

---------

Co-authored-by: murrlincoln <65836530+murrlincoln@users.noreply.github.com>
2025-04-30 16:27:34 -04:00
Carson Roscoe
e5b90b4841
feat: initial npm modules (#68)
* first pass implementing gha for publishing packages

* feat: updated core types to align with updated protocol spec

* feat: package/x402 refactor

* feat: restructured x402 core

* feat: x402 refactor in preparation for middleware

* feat: middleware workspace project template

* feat: refactor x402-express into its own package

* feat: x402-express updated to new spec

* feat: express server example

* feat: facilitator express server example

* feat: added axios interceptor

* chore: refactor express server example down a folder

* feat: client script example using axios

* fix: improved env variable handling in examples

* fix: site paths now that site is not within the turbo repo

* fix: parsing of types per updated spec

* fix: tweaked examples

* feat: x402-xios and x402-express unit tests

* feat: added test to turbo commands

* chore: reformat

* chore: docstrings

* chore: updated docstring

* feat: added x402-fetch package and fetch client example

* feat: unit test fetch wrapper

* chore: docstring

* chore: reformat

* chore: updated docstring

* feat: x402-hono and hono server example

* feat: added unit tests

* chore: added docstring

* chore: removed excess comments

* chore: updated docstring

* feat: added lint and format to typescript monorepo

* feat: added check_format, check_lint and check_package_lock workflows

* feat: tighten up and improve linting checks

* chore: lint/format x402

* chore: expand tigthened linting to all packages/examples

* fix: format/lint x402

* fix: format/lint x402-axios

* fix: format/lint x402-express

* fix: format/lint x402-fetch

* fix: format/lint x402-hono

* fix: format/lint middleware-template

* fix: format/lint example facilitator

* fix: format/lint example express server

* fix: format/lint example hono server

* fix: eslint unused var false positives

* fix: format/lint example axios client

* fix: format/lint example fetch client

* fix: format/lint whole project

* fix: added explicit dev dependencies on eslint-plugin

* chore: updated package lock workflow name

* chore: format package.jsons

* fix: added explicit dev dependencies on eslint parser

* fix: define paymentRequirements type from toJsonSafe

* fix: added explicit dev dependencies on eslint plugin import

* feat: README for express and express example

* fix: README code snippet syntax

* chore: unit test github workflow

* fix: test -> test:watch, added new test scripts

* chore: removed build from examples

* fix: added missing dependencies

* fix: renamed unit test workflow

* fix: missing dev dependency on express types in x402-express

* fix: added explicite vite dev dependency, as its a peer dep of vitest

* feat: x402-hono and servers/hono example READMEs (#52)

* feat: x402-hono and servers/hono example READMEs

* fix: updated npm to pnpm in example readme

* feat: refactor server middleware to decode X-PAYMENT header

* feat: middleware returns array of PaymentRequirements

* fix: unit tests

* fix: paywall html takes array of paymentRequirements, but just uses first item in list

* feat: added selector logic for selecting payment requirements client side

* feat: support generic ERC20Permit contracts

* fix: toJsonSafe for arrays

* fix: paywall selector usage

* feat: jwt signing & createAuthHeader

* fix: wrap api keys in auth object and include paths

* fix: route paths updated to specs

* fix: format

* feat: using @coinbase/cdp-sdk/auth for generateJwt

* feat: middleware takes an array to generate auth headers

* feat: change routes to /verify and /settle, change default resource to include /v2/x402

* fix: removed duplicate import

* chore: drop node 18 unit tests

* feat: rename function and descriptions to createAuthHeaders

* fix: pr feedback

* feat: improved default behavior for facilitator auth

* feat: dev demo test changes

* feat: moved cdp logic to separate export

* fix: format/lint

* feat: added x402-next and examples/fullstack/next

* feat: added readmes and updated exported types

* fix: format/lint

* fix: updated next demo to type: module

* fix: format

* fix: updated x402-next to new spec

* fix: demo

* fix: format/lint

* feat: improved handling of default asset

* fix: added missing dependencies

* fix: added explicite vite dev dependency, as its a peer dep of vitest

* feat: migrated site to monorepo subproject

* fix: regenerate lock

* feat: added format/lint

* fix: package type is module

* fix: package type is module

* fix: removed npm from prerequisites

* chore: rebased

* feat: migrated site example to latest spec

* fix: regenerate lock file

* feat: added mcp client demo

* feat: migrated agent client

* feat: Added x402-fetch and clients/fetch example readmes

* feat: rename export to wrapFetchWithPayment

* feat: x402-axios and clients/axios example readmes

* fix: increased node version in readme

* feat: removed packages/typescript

* feat: removed middleware-template

* feat: migrated clients/agent example

* feat: migrated clients/axios example

* feat: migrated clients/fetch example

* feat: migrated clients/mcp example

* feat: migrated facilitator example

* feat: migrated fullstack/next example

* feat: migrated servers/express example

* feat: migrated servers/hono example

* feat: structured dual-workspace for turbo

* feat: deleted example root folder

* fix: removed old package-lock and normalized express types used

* feat: removed x402 dependency on hono

* feat: migrated x402/cdp to @coinbase/x402

* feat: add payerAddress to verify responses

* feat: added README to examples/typescript

* chore: format/lint

* feat: migrate site example to root

* second pass implementing gha for publishing packages

* refinements

* enabling debugging

* disabling git check for publishing dryrun

* package npm token isolation

* removing degugging

* chore: Update Go Middleware Package to Latest Spec

* feat: updated README to spec

* feat: updated exact evm scheme

* fix: updated missed paymentDetails -> paymentRequirements in refactor

* fix: quotes to match our linter

* feat: readded supported

* fix: pr feedback

* fix: pr feedback

* update go fields: accepts, paymentPayload, paymentRequirements

* fix: readme example

* fix: site readme node version

* fix: removed package-lock.json

* feat: added package manager to package json

* fix: json

* feat: moved site back to typescript

* fix: lock file

* feat: updated packageManager

* feat: updated package manager

* testing root package.json

* fix: x402 depedency in site

* feat: added build:vercel script

* fix: github workflow detecting packageManager from package.json

* feat: removed dotenv dependency in x402 for edge compatibility

* feat: inject facilitator url via vercel env vars

* feedback

* pnpm version

* removing debugging

* first pass adding payer to verify response

* feat: initial devx draft

* fix: format/lint

* feat: rename facilitator exported config

* fix: x402-next middleware routing supports verbs

* feat: devx feedback

* feat: updated examples

* fix: removed bad dependency

* feat: regenerated lock after rebase

* fix: pnpm-lock

* fix: middleware resource url fallback

* fix: README 1-liner example for correctness

* feat: updated READMEs

* feat: bump x402 to 0.2.0

* feat: added legacy route support to hosted test facilitator

* fix: moved client definition out of global scope

* feat: rename TokenAmount to ERC20TokenAmount

* fix: remove unused ts-expect-error

* feat: temporarily removed @coinbase/x402 package

* fix: examples

---------

Co-authored-by: Christopher Gerber <csgerber@gmail.com>
Co-authored-by: John Peterson <john.peterson@coinbase.com>
2025-04-25 12:05:40 -04:00
erik
b405f0815d Update exact scheme spec 2025-02-27 09:09:43 -07:00
erikreppel-cb
0b041b5da3
[refactor] Cleaner separation between protocol and schemes (#1)
* Update readme with more technical details

* Refactor folder structure

* Refactor types

* Verify tests pass

* settle payment test passes

* Need some work to remove src from import path when installed
2025-02-22 19:50:54 -08:00