64 Commits

Author SHA1 Message Date
A1igator
850e3cefef
Add authCapture scheme specification (#1425)
* Add escrow scheme specification

Introduces the `escrow` scheme for x402, built on Base's Commerce Payments
Protocol. Supports two settlement paths: authorize (funds held in escrow)
and charge (direct to receiver), both refundable post-settlement.

Refs: #834, #1011

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

* Address review feedback on escrow scheme specs

- Generalize scheme_escrow.md to be network-agnostic
- Tighten verification: strict amount equality, tokenCollector
  recipient check, settlement simulation
- Add error codes section and assetTransferMethod note
- Simplify nonce derivation explanation

* Rename scheme to commerce and align spec with implementation

- Rename escrow → commerce per reviewer feedback
- Add expiry fields to PaymentRequirements example
- Align expiry field descriptions and example values

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* spec: rename escrow/commerce scheme to authCapture, add EVM payload schema

Renames the scheme directory from commerce/ to authCapture/ and rewrites
the EVM spec to cover both ERC-3009 and Permit2 payment-collector paths.

Key spec additions:
- extra field schema (captureAuthorizer, captureDeadline, refundDeadline,
  feeRecipient, min/maxFeeBps, autoCapture, assetTransferMethod)
- Wire format + EIP-712 derivation tables for ERC-3009 and Permit2
- Spec -> on-chain PaymentInfo field mapping (preserves canonical Solidity
  names so EIP-712 typehash matches the AuthCaptureEscrow contract)
- Universal contract addresses block (CREATE2-deterministic)
- Verification step list aligned with facilitator implementation:
  preApprovalExpiry <= captureDeadline <= refundDeadline (>= allowed,
  matching contract _validatePayment)

* spec: use canonical base/commerce-payments addresses

Defer to the live deployment from base/commerce-payments@v1.0.0 instead
of redeploying via CREATE2. Drop the now-obsolete inline address tables
and salt-scheme paragraph; the Canonical Addresses annex now links to
the upstream release notes (and Uniswap deployments docs for Permit2),
matching scheme_exact_evm.md's third-party 'Canonical Permit2' annex
pattern.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-12 17:40:43 -07:00
phdargen
3df5223968
update-bazaar-docs (#2263) 2026-05-11 09:16:22 -07:00
jnix.base.eth
2e54665f47
Docs/batch settlement and cleanup (#2261)
* Adding batch settlement details, plus a general cleanup of some stale content and onchain vs on-chain typos

* Additional minor polishing updates

* Merging SDK features mechanisms table with main and adding batch-settlement to resolve conflict
2026-05-11 13:19:10 +02:00
Shinya Fujino
cd87caaed3
docs: fix indentation in x402 v2 spec examples (#2260) 2026-05-10 14:16:26 +02:00
aayushijain-cb
608034f15a
feat: add service metadata on resource to all 3 SDKs (#2200)
* docs: add repo move note to README (#40)

* add service metadata on resource to all 3 SDKs

* lint

* changelog

* review: harden iconUrl validators + tighten signatures

* review: constrain serviceName/tags to printable ASCII

* add checks to harden iconurl + tag/name validators

* update v2 spec + python lint

* python format

---------

Co-authored-by: Ash <105402607+Must-be-Ash@users.noreply.github.com>
2026-05-06 14:13:33 -04:00
phdargen
c763d05adc
Batch-settlement scheme specification for EVM (#2051)
* batch-settlement on EVM

* update refund flow and payloads

* move corrective 402 info from errorDetails to requirements.extra.ChannelState and compute channelID from EIP712Hash

* align payment-response for all payloads

* post audit updates

* add deposit collector addresses

* update error codes
2026-05-05 07:55:33 -04:00
phdargen
45d7d19250
Batch-settlement TS sdk (#2061)
* spec + sdk

* add auto recover and topUp; add filestorage

* add session manager

* fix nonce reset

* add cooperativeWithdraw to spec/contract

* add cooperative withdraw to sdk

* update sdk to match spec v1.2

* change to auto-generated getters

* improve server devx

* improve client devx

* added concurrent request example

* minor fixes

* add cas

* add streaming example

* rename files to batched*

* updated scheme name deferred -> batched

* update to new contracts

* align paymentresponse.extra for all payloads

* fix recovery after refund

* fix withdraw -> refund flag

* fix channel manager

* rename to batch-settlement

* align with cloudflare specs

* remove claim/refund without sign

* add tx sim

* improve specs

* specs ready

* add unit/integration tests

* fix tests

* improve typing, remove dead code

* add readmes

* add e2e tests

* fix fileStorage

* increase depositMultiplier for streaming

* refund without paid request

* refactor convertToTokenAmount

* refactor scheme

* fix recovery for refund flow

* refactor client scheme

* rename session -> channel

* remove chargedCumulativeAmount from deposit payload

* scheme hook adapters

* add enrichSettlementPayload/enrichSettlementResponse hooks

* move batch-settlement scheme to scheme hook adapters and enrichSettlementResponse

* refactor refund and other payloads

* add client hook adapters

* align payment-response shapes

* move corrective 402 info from errorDetails to requirements.extra.channelState

* fix corrective deposit flow

* update to latest deployment and change channelId computation to EIP-712

* add hook to handle route handler failures

* add atomic channel update and request context primitives

* guard channels with pending reservations

* fix concurrent claim/settle

* skip facilitator and verify locally if onchain state fresh

* add redis storage

* add fullstack next example with redis and fix settlementOverride for next package

* align payment-response for all payloads

* add permit2 support and fix extra enrichment for nested objects

* fix DEPOSIT_WITNESS_TYPE_STRING

* test client state-loss recovery scenario in e2e

* fix recovery for axios

* improve channel manager

* update client deposit policy

* clean up examples

* add to testnet facilitator

* update READMEs

* for the culture

* add changesets

* update to latest deployment

* align error codes

* remove receiverAuthorizer fallback
2026-05-04 16:43:57 -04:00
Cloud
1e0434b18e
docs: add builder_code.md spec (#2050)
* docs: add builder_code.md spec

* support services array
2026-05-04 14:18:52 -04:00
Daniil Okhlopkov
01abe6cc6b
specs(exact): propose TON exact scheme for x402 v2 (spec-only) (#1455)
* specs(exact): propose TON exact scheme for x402 v2 (spec-only)

Adds scheme_exact_ton.md defining the exact payment scheme for TON blockchain.
Uses W5 wallet internal_signed messages for gasless Jetton (TEP-74) transfers.
Updates scheme_exact.md with TON-specific validation rules.

* specs(exact/ton): address review feedback — exact amounts, commission bounds, stateInit verification

- Change amount verification from >= to == (exact match), aligning with
  all other chain specs (SVM, Stellar, EVM). The relay commission is a
  separate jetton_transfer in the W5 batch, not bundled into the payment.
- Add extra.maxRelayCommission field to PaymentRequirements, allowing
  resource servers to cap the relay commission amount.
- Add stateInit verification rule: when seqno == 0, facilitator must
  verify contract code against a known W5 wallet code hash allowlist.
- Tighten action count: W5 message must contain exactly the payment
  transfer and optionally a relay commission transfer, nothing else.

* specs(exact/ton): rewrite to self-relay architecture — address all review comments

* chore(spec): simplify TON spec — remove external_signed, condense references

- Remove external_signed (0x7369676e) mode — all x402 payments use
  gasless internal_signed. External mode deferred to future extension.
- Remove on-chain proof table (7 tx links) — promotional, not normative.
  Proofs already linked in PR comments.
- Condense Reference Implementations to 3 lines (was 20+).
- Settlement Logic now single-path (no dual-mode branching).
- 349 → 320 lines. Closer to SVM/Stellar spec size.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(spec): remove 50% gas buffer — emulation is already worst-case

* specs(exact/ton): address all review comments — remove /prepare, add RPC

Changes:
- Remove /prepare endpoint: client resolves seqno + jetton wallet via
  TON RPC directly (same pattern as SVM/Stellar/Aptos)
- Remove nonce field: dedup uses BoC hash, not nonce
- Transfer amount: strict equality (== not >=)
- Add jetton wallet verification: recipient MUST match
  get_wallet_address(payTo) on the asset master
- Seqno check: MUST NOT be less than on-chain seqno (was SHOULD)
- Add client balance check requirement
- Move simulation to /verify (was optional pre-settlement)
- Remove HTTP header references (transport-agnostic)
- Replace hardcoded 600s with maxTimeoutSeconds
- Add Client RPC Requirements appendix section

* specs(exact/ton): add facilitator safety, explicit jetton wallet check

- Add section 3 (Facilitator Safety): facilitator address MUST NOT
  appear as sender or Jetton transfer source. Matches SVM/Stellar.
- Make get_wallet_address check explicit per @skywardboundd: the
  destination in the deserialized BoC must match the resolved wallet.
- Align verification intro phrasing with SVM/Stellar style.

* specs(exact/ton): add areFeesSponsored flag per Stellar pattern

Follows Stellar's approach: extra.areFeesSponsored boolean, currently
always true. Non-sponsored flow (client pays gas) to be added later.

* specs(exact/ton): fix validUntil duplication, add stateInit code hash check

- Remove duplicate validUntil check from section 2 (already in section 5)
- Add stateInit code hash verification for seqno==0 deployments
  (per arjun215-eng's earlier feedback)

* specs(exact/ton): add payload.to and source Jetton wallet checks

Per @skywardboundd review:
1. payload.to MUST equal requirements.payTo (explicit metadata check)
2. Source Jetton wallet (W5 internal msg destination) MUST match
   get_wallet_address(from) — prevents substitute source contract
3. jetton_transfer body destination MUST equal requirements.payTo

Tested against deployed facilitator with real on-chain data.
Facilitator commit: ohld/x402-ton-facilitator@6f92320

* specs(exact/ton): remove facilitatorUrl, fix dedup TTL, add canonical W5R1 hash

- Remove facilitatorUrl from extra (implementation detail, not protocol field)
- Fix dedup TTL: use fixed 300s instead of per-request maxTimeoutSeconds
- Add canonical W5R1 code hash for stateInit verification
- Note simulation as alternative to code hash checks for seqno>0

Per @phdargen review on coinbase/x402#1455

* specs(exact/ton): internal message BoC, minimal payload, strict seqno

Major rework based on TON Core team review:
- settlementBoc is now an internal message (not external)
- Payload reduced to {settlementBoc, asset}, all fields derived from BoC
- Public key derived from stateInit or on-chain get_public_key
- Seqno check changed to strict equality (TON requirement)
- Internal message must be bounceable
- Removed facilitatorUrl, nonce, walletPublicKey
- Clarified simulation in /verify, extensibility for non-gasless flows
- Updated parent scheme_exact.md TON section

* spec: address skywardboundd review -- account states, asset clarification, simulation chain

- Replace seqno==0 with proper TON account states (nonexist/uninit) for stateInit condition
- Clarify that payload.asset is a JSON field, not a BoC-internal field (TEP-74 has no asset)
- Add full TEP-74 transfer chain verification to simulation section
- Remove non-normative timing note from settlement step 7
- Add W5 gasless transactions reference link

* spec: address remaining review comments from skywardboundd

- Narrow wallet scope to W5 v5r1 (not v5r1+), only version that exists today
- Remove redundant "x402 protocol-level requirement" sentence
- Add get_jetton_data hint for decimal resolution
- Add walletId to derived fields list
- Rename section 2 to "Message and signature verification"
- Move balance check from Replay protection to Payment intent
- Remove redundant seqno explanation sentence

* spec: clarify TON exact flow for optional jetton transfer params

Refine the TON `exact` scheme spec to better describe how client-signed W5 jetton transfers are verified and relayed by the facilitator.

This update expands the TON payment requirements and verification rules to account for optional jetton transfer parameters exposed through `extra`, and clarifies how those parameters are interpreted when they are omitted.

Changes included:
- add optional `extra.forwardPayload` and `extra.forwardTonAmount` to TON
  `PaymentRequirements` and define their effective defaults as zero-bit payload and `"0"`
- add optional `extra.responseDestination` and define its effective default as `addr_none`
- require facilitators to compare the effective values of `responseDestination`, `forwardPayload`, and `forwardTonAmount` between `accepted.extra` and `requirements.extra`
- extend payment intent validation so the facilitator derives and checks `response_destination`, `forward_payload`, and `forward_ton_amount` from the signed W5 action
- clarify that the facilitator-funded relay must cover both outer relay execution and the value expected by the client-signed inner transfer
- clarify that the client-signed inner message must carry enough TON to fund payer-side execution from the payer jetton wallet to the source jetton wallet
- specify that the outbound internal message from the client W5 wallet to the source jetton wallet must be bounceable
- specify that the `settlementBoc` wrapper itself does not need to be bounceable
- clean up terminology and consistency across the document: `BoC`, `zero-bit`, `forwardPayload`, `forwardTonAmount`, and derived field descriptions

This is a spec clarification/update only. It does not introduce a new TON payment scheme, but makes the existing gas-sponsored W5 relay flow more precise.

* specs(exact/ton): clarify W5 account states and extra field semantics

* soec(exact/ton): clarify code hash check

* spec(exact/ton): update reference implementations

* spec(exact/ton): allow sending mode 3

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Arkadiy Stena <arkadiystena@gmail.com>
2026-05-01 19:30:02 +09:00
Ethan Oroshiba
7ec7815257
feat(bazaar): update WithBazaar SDK wrappers with search, unified auth, and Python alignment (#2094)
* update withBazaar

* Fix bazaar MCP discovery parity across TS/Python/Go; tighten e2e validation; update docs/examples.

* python format

* remove formatting-only changes

* remove formatting-only changes

* reinstate old comments

* clean up response shape

* revert pagination to object instead of top level fields

* address review comments
2026-04-30 02:19:09 +09:00
Alfred Tom
05f0e0489f
feat: add auth-hints extension to streamline scheme-level authentication (#1902)
* feat: add auth-hints extension to streamline scheme-level authentication

- Described general auth scheme for x402, mainly on HTTP transports
- Initial support for two auth method types: oauth2 (Bearer/DPoP) and sign-in-with-x
- Defined scheme and acceptIndex hints.

* feat: settle on acceptIndexes, schemeAuth->authRequirements, remove references to scheme-based hints
2026-04-24 08:57:32 -07:00
Fabian Bormann
4840c8dfb8
Cardano x402 Protocol Specification (#1093)
* Create scheme_exact_cardano.md

* Update scheme_exact_cardano.md

* Update and rename scheme_exact_cardano.md to scheme_exact_cardano-masumi.md

* Added Address-To-Address on Cardano Specs

* Update scheme_exact_cardano.md

* feat: add optional session management to final response

* chore: add instructions for script flavor

* feat: update cardano schema according to x402 v2 migration guide

* chore: update mermaid diagram for x402 v2

* chore: reapply v2 changes that might got lost in the merging process

* chore: address x402 schema feedback around nonce, legacy v1 fields, flavor and session tokens

* chore: add warning for mempool status, rewrite facilitator verification rules

---------

Co-authored-by: Patrick Tobler <129864078+PatrickTobler@users.noreply.github.com>
2026-04-22 19:17:50 -07:00
Cameron Whiteside
2a690c7e04
feat: add batch-settlement payment scheme and Cloudflare network specification (#1145) 2026-04-15 16:03:05 -07:00
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