Metadata-Version: 2.1
Name: uvd-x402-sdk
Version: 0.114.0
Summary: Python SDK for x402 payments - gasless crypto payments across 31 networks (including HashKey Chain mainnet/testnet, native Hedera mainnet/testnet, Circle Arc mainnet/testnet, Robinhood Chain, XRPL, Scroll, SKALE). Features: ERC-8004 Trustless Agents, Escrow/Refunds, multi-stablecoin (USDC, EURC, AUSD, PYUSD, USDT, USDG)
Author-email: Ultravioleta DAO <dev@ultravioletadao.xyz>
Project-URL: Homepage, https://github.com/UltravioletaDAO/uvd-x402-sdk-python
Project-URL: Documentation, https://docs.ultravioletadao.xyz/x402-sdk
Project-URL: Repository, https://github.com/UltravioletaDAO/uvd-x402-sdk-python
Project-URL: Issues, https://github.com/UltravioletaDAO/uvd-x402-sdk-python/issues
Keywords: x402,payments,crypto,usdc,eurc,stablecoin,web3,evm,solana,near,stellar,algorand,sui,xrpl,xrp,scroll,skale,robinhood,hashkey,arc,circle-arc,usdg,facilitator,gasless,eip-712,eip-3009,erc-8004,trustless-agents,escrow,refund
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business :: Financial :: Point-Of-Sale
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: near
Requires-Dist: cryptography>=42.0.0; extra == "near"
Provides-Extra: ows
Requires-Dist: cryptography>=42.0.0; extra == "ows"
Requires-Dist: open-wallet-standard==1.4.2; extra == "ows"
Provides-Extra: receipts
Requires-Dist: cryptography>=42.0.0; extra == "receipts"
Provides-Extra: hedera
Requires-Dist: hiero-sdk-python<0.3,>=0.2.10; python_version >= "3.10" and extra == "hedera"
Provides-Extra: signer
Requires-Dist: eth-account>=0.11.0; extra == "signer"
Provides-Extra: dx402
Requires-Dist: cryptography>=42.0.0; extra == "dx402"
Requires-Dist: eth-utils>=4.0.0; extra == "dx402"
Requires-Dist: eth-keys>=0.5.0; extra == "dx402"
Requires-Dist: eth-hash[pycryptodome]>=0.7.0; extra == "dx402"
Provides-Extra: wallet
Requires-Dist: eth-account>=0.11.0; extra == "wallet"
Provides-Extra: web3
Requires-Dist: web3>=6.0.0; extra == "web3"
Requires-Dist: eth-account>=0.11.0; extra == "web3"
Provides-Extra: escrow
Requires-Dist: web3>=6.0.0; extra == "escrow"
Requires-Dist: eth-account>=0.11.0; extra == "escrow"
Provides-Extra: reputation
Requires-Dist: eth-account>=0.13.0; extra == "reputation"
Provides-Extra: solana
Requires-Dist: cryptography>=42.0.0; extra == "solana"
Provides-Extra: flask
Requires-Dist: flask>=2.0.0; extra == "flask"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == "fastapi"
Requires-Dist: starlette>=0.27.0; extra == "fastapi"
Requires-Dist: eth-account>=0.11.0; extra == "fastapi"
Provides-Extra: django
Requires-Dist: django>=4.0.0; extra == "django"
Provides-Extra: aws
Requires-Dist: boto3>=1.26.0; extra == "aws"
Provides-Extra: algorand
Requires-Dist: py-algorand-sdk>=2.0.0; extra == "algorand"
Provides-Extra: interop
Requires-Dist: jsonschema>=4.18.0; extra == "interop"
Provides-Extra: all
Requires-Dist: uvd-x402-sdk[algorand,aws,django,escrow,fastapi,flask,hedera,near,signer,solana,wallet,web3]; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: httpx>=0.24.0; extra == "dev"
Requires-Dist: jsonschema>=4.18.0; extra == "dev"
Requires-Dist: moto[dynamodb]>=5.0.0; extra == "dev"
Requires-Dist: pyyaml>=6.0; extra == "dev"
Requires-Dist: uvicorn>=0.23.0; extra == "dev"
Requires-Dist: requests>=2.28.0; extra == "dev"
Requires-Dist: aiohttp>=3.9.0; extra == "dev"
Requires-Dist: open-wallet-standard==1.4.2; (python_version < "3.14" and ((sys_platform == "linux" and (platform_machine == "x86_64" or platform_machine == "aarch64")) or (sys_platform == "darwin" and (platform_machine == "x86_64" or platform_machine == "arm64")))) and extra == "dev"

# uvd-x402-sdk

Python SDK for integrating **x402 cryptocurrency payments** via the Ultravioleta DAO facilitator.

Accept **gasless cryptocurrency payments** across **31 blockchain networks** with a single integration. The SDK handles signature verification, on-chain settlement, and all the complexity of multi-chain payments.

See the [CHANGELOG](CHANGELOG.md) for release history.

**EURC on Arc**: Mainnet and testnet support six-decimal euro amounts and token-specific signatures. Gas remains USDC. Funded EURC payments confirmed on Arc mainnet (x402 v1 and v2, 2026-09-22); Arc testnet funded acceptance pending. [Arc EURC guide](docs/networks/arc.md#eurc-prices-in-euros).

**Native Hedera payments**: Hedera mainnet and testnet accept native USDC only with x402 v2/exact. HBAR funds sponsor network fees and is rejected as payment. Includes offline signing, buyer 402 retries and merchant request builders. [Hedera guide](docs/networks/hedera.md).

**Arc USDC payments**: Arc mainnet (`arc`, `eip155:5042`) and testnet (`arc-testnet`, `eip155:5042002`) support direct USDC `exact` payments. Both use 6-decimal ERC-20 amounts and the `USDC` / `2` EIP-712 domain. See [Arc usage and validation](docs/networks/arc.md).

## NEAR signing with Open Wallet Standard

For identity and reputation, see the [NEAR ERC-8004 guide](docs/near-erc8004.md):
separate registries on `near:mainnet` and `near:testnet`, with payment-backed
Arras feedback. Execution Market uses NEAR ERC-8004; the earlier Arras
client is documented in the [legacy registry-v1 guide](docs/near-registry.md).

Install `pip install 'uvd-x402-sdk[ows]'` for `OwsNearSigner` (pins
`open-wallet-standard==1.4.2`). Its wheels support CPython 3.9–3.13 on Linux
with glibc and macOS; OWS does not publish Windows wheels for this version.
The base SDK and the `near` extra remain independent of OWS.

Provision the wallet and its API token outside the agent runtime. Supply the
selected 32-byte public access key, an explicit vault path and the API token;
owner passphrases are rejected. For example, inside an async application:

```python
from uvd_x402_sdk import OwsNearSigner, send_near_transaction, sign_storage_transaction
from uvd_x402_sdk.near_storage import build_usdc_storage_deposit

signer = OwsNearSigner(
    "agent-wallet", network="near:testnet", token=agent_api_token,
    public_key=selected_public_key, vault_path=vault_path,
)
tx = build_usdc_storage_deposit(network="near:testnet", payer_id="agent.testnet")
signed = sign_storage_transaction(
    tx, signer, next_nonce, recent_block_hash, network="near:testnet",
)
journal.persist(signed)  # Durably store the exact signed bytes before sending.
outcome = await send_near_transaction(signed, rpc_url=trusted_rpc_url)
# Inspect outcome["status"] and its receipts: inclusion can contain a Failure.
```

The application obtains `next_nonce` and `recent_block_hash` from its trusted
RPC and checks that `selected_public_key` is authorized for the account.
`journal.persist` represents the application's durable journal. On restart or
an ambiguous RPC error, reconcile the original transaction hash and replay
those persisted bytes; signing a replacement may pay twice.

`sign_erc8004_transaction` and `sign_storage_transaction` give OWS the complete
Borsh transaction through `ows.sign_transaction`; each signature is verified
locally before return. `sign_nep413`, `sign_escrow_authorization` and
`sign_exact_near_delegate` accept the same signer. Until OWS provides native
NEP-413/366 envelopes, their SDK-built digest goes through OWS
`sign_message(encoding="hex")`. A token must permit that operation; transaction
policy parsing does not apply to a raw message digest. This OWS version also
lacks NEAR receiver/method/deposit transaction policy context; enforce those
limits in the application before signing, including when OWS receives the
whole transaction. `near_registry.sign_registry_transaction` (the legacy registry-v1 client)
is not on that path yet: it still asks the signer for `sign(sha256(wire))`, so an
`OwsNearSigner` gets the digest through `sign_message`, and it does not compare
the signer's network with the transaction's. Give it a signer for the
registry's network.

`send_near_transaction` has no signing capability. It retries only the same
bytes (at most three attempts) after transport errors, HTTP 429/5xx or RPC
`TIMEOUT_ERROR`. Other RPC refusals and malformed outcomes, including an answer
whose body cannot be decoded, raise
`NearTransactionError` with the original `transaction_hash` and
`uncertain=True`; a replay's invalid nonce alone cannot prove whether the
first send landed. Final execution failures are returned once for the caller
to handle. Shared deterministic vectors are in `tests/fixtures/near-ows.json`;
`python scripts/near_ows_vectors.py --check` detects drift.

## NEAR HTTP authentication (NEP-413)

An agent that holds only a NEAR account authenticates its HTTP requests to
Execution Market with `sign_near_http_request`. The headers are the ERC-8128
envelope (RFC 9421 `Signature-Input` / `Signature`, label `near`,
`keyid="near:<account>:ed25519:<base58 key>"`, `alg="ed25519-nep413"`), and the
signature is NEP-413 over the exact signature base, with
`nonce = sha256(<RFC 9421 nonce>)` and the verifier's `recipient`. The server
reads the identity as `near:<account>`. Signing is offline (no RPC, no nonce
fetch) and needs the `near` extra (or `ows` for an `OwsNearSigner`).

```python
import secrets

import httpx

from uvd_x402_sdk import (
    EXECUTION_MARKET_NEP413_RECIPIENT, NearEd25519Signer, sign_near_http_request,
)

signer = NearEd25519Signer(agent_secret_key)  # or an OwsNearSigner
url = "https://api.execution.market/api/v1/tasks"
body = '{"title":"Check the store hours"}'
headers = sign_near_http_request(
    signer, "agent.near", "POST", url,
    nonce=secrets.token_urlsafe(32),
    recipient=EXECUTION_MARKET_NEP413_RECIPIENT,
    body=body,
)
response = httpx.post(
    url, content=body, headers={**headers, "Content-Type": "application/json"}
)
```

- The key must be a **FullAccess** key of the account on NEAR mainnet: EM reads
  `view_access_key` at `finality: final` and refuses a FunctionCall key, an
  account that does not exist (an implicit one included) and a key not on it.
  The signer cannot check that offline.
- One nonce per request. EM consumes `near:<account>:<nonce>` before it checks
  the signature, so a retry, including after `503 near_rpc_unavailable`, needs
  a new nonce and a new signature, never the same headers.
- Send exactly the body that was signed (`str` is UTF-8); `Content-Digest`
  covers it, the empty body included. `None` means no body.
- `recipient` is required: a signature names the one service it is for. EM's
  is `execution.market`, for both `api.` and `mcp.` hosts.
- The window is `validity_sec` (1..300, EM's maximum) from `created` (now).
- Refused before the key is read: any URL one of the measured clients (httpx,
  requests, urllib, aiohttp) would send as other bytes than the ones signed,
  because EM spends the nonce before it checks the signature (measured against
  EM's verifier). That is: percent-encoded octets in the path (EM reads the
  decoded path); dot segments (httpx, requests and aiohttp remove them); a port
  written empty or with leading zeros, an upper-case host and the scheme's
  default port (httpx, requests and aiohttp rewrite them in `Host`, urllib
  sends them as written); a host that ends in `.` (requests and aiohttp send
  it without the dot); an IPv6 literal other than its `ipaddress` compressed
  form (aiohttp compresses it); in the query, a percent-encoded octet in
  lower-case hex (requests and aiohttp upper-case it) or one that encodes an
  unreserved character or one of `/ ? : @ ! $ ' ( ) * ,` (sent decoded: write
  the character itself, it means the same to a form parser); brackets outside
  the host and a `%` that starts no octet (requests and aiohttp re-encode
  them). `%26 %2B %3B %3D %25 %23 %20` and non-ASCII octets in upper-case hex
  are signed. Also refused, as policy: an upper-case scheme, a `%` in the host,
  user info, a fragment, any non-RFC 3986 character, a nonce outside
  `[A-Za-z0-9._~+/=-]{1,256}`, an account outside NEAR's lowercase grammar.
  The authority signed is the URL's `host[:port]` as written, which is what
  every measured client sends in `Host` for a URL that passes, unless the
  client refuses the URL and sends nothing (requests, for a host that starts
  with `.` or `*`).
- EM is NEAR mainnet only. The signed bytes carry no network, so an
  `OwsNearSigner` configured for `near:testnet` signs them, but EM will not
  find a testnet key on a mainnet account (and the nonce is spent).

The header values are pinned byte for byte to EM's public vector
(`tests/fixtures/near-http-auth.json`, a copy of EM's
`shared/test-vectors/near-http-auth.json`) with the in-memory signer and with
OWS, and verified by a transcription of EM's verifier
(`tests/near_http_auth_em.py`), as httpx, requests, urllib and aiohttp send
each request (`tests/http_clients_wire.py`). Every RFC 3986 character of the
path, the query and the host, and every spelling of every percent-encoded octet
of the query, is signed exactly when none of the four clients rewrites it
(`test_signed_iff_every_client_sends_it_as_written`).

## Features

- **31 Networks**: EVM chains (19 including HashKey mainnet/testnet, Circle Arc mainnet/testnet, Robinhood, Scroll, SKALE), SVM chains (Solana, Fogo), NEAR, Stellar, Algorand, Sui, XRPL (native XRP), and Hedera (native USDC; HBAR for sponsor fees)
- **6 Stablecoins**: USDC, EURC, AUSD, PYUSD, USDT, USDG; XRPL settles in native XRP (networks per token: [Supported Tokens](#supported-tokens))
- **x402 v1 & v2**: Protocol auto-detection; native Hedera supports v2/exact only
- **Framework Integrations**: Flask, FastAPI, Django, AWS Lambda
- **Gasless Payments**: Users sign EIP-712/EIP-3009 authorizations, facilitator pays all network fees
- **Simple API**: Decorators and middleware for quick integration
- **Type Safety**: Full Pydantic models and type hints
- **Extensible**: Register custom networks and tokens easily
- **ERC-8004 Trustless Agents**: On-chain reputation and identity for AI agents (25 networks: 23 EVM + Solana + Solana-devnet)
- **Escrow & Refunds**: Hold payments in escrow with dispute resolution (14 registered EVM escrow deployments, including SKALE via CREATE3 and Arc, Arc Testnet and Robinhood mainnet on the canonical x402r operator; Robinhood uses USDG; Base Sepolia and Ethereum Sepolia are testnet deployments outside the payment-network table)
- **Commerce Scheme**: Supports `"exact"`, `"escrow"`, and `"commerce"` schemes (facilitator v1.43.0+)
- **Server-Side Signing**: `connect_with_private_key()` for backend EIP-3009 signing without browser wallet
- **`/accepts` Negotiation**: Discover facilitator capabilities before constructing payments
- **Bazaar Discovery**: Register and discover paid resources across the x402 network
- **x402 v2 Envelopes**: the client picks v1 or v2 from the wire (`x402_version="auto"`); `build_verify_request_v2` / `build_settle_request_v2` remain for hand-built bodies
- **Live Traffic Stream**: Subscribe to `GET /events` (SSE) for settlements as they happen — lossy live hint, not a ledger
- **Facilitator Info**: Query version, supported networks, blacklist, and health
- **WalletAdapter**: Abstract protocol for wallet signing (EnvKeyAdapter, OWSWalletAdapter)
- **ERC-8128 Signed HTTP Requests**: RFC 9421 request signing with any WalletAdapter — authenticate against wallet-signed APIs like Execution Market
- **Escrow Pre-Auth Builder**: `build_escrow_pre_auth()` / `compute_escrow_nonce()` — sign the ADR-002 sign-on-assignment escrow lock (`X-Payment-Auth` header) with any WalletAdapter, no web3 required
- **Signed escrow lifecycle orders**: `build_lifecycle_auth()` — sign the EIP-712 order that entitles a `release` / `refundInEscrow`, and pass a `lifecycle_signer` to `release_via_facilitator()` / `refund_via_facilitator()`, or a `lifecycle_auth` when someone else already signed it
- **Purchase policy**: `PurchasePolicy` — what the buyer may sign, evaluated against the offer in hand BEFORE signing, with six refusal codes in a fixed order and the seller's own `validUntil`; same contract as the facilitator's `x402-reqwest` 2.25.0

## Quick Start (5 Lines)

```python
from decimal import Decimal
from uvd_x402_sdk import X402Client

client = X402Client(recipient_address="0xYourWallet...")
result = client.process_payment(request.headers["X-PAYMENT"], Decimal("10.00"))
print(f"Paid by {result.payer_address}, tx: {result.transaction_hash}")
```

## Complete Usage Example

Here's a complete example showing the full x402 payment flow - returning a 402 response when no payment is provided, and processing the payment when it arrives:

```python
from decimal import Decimal
from uvd_x402_sdk import (
    X402Client,
    X402Config,
    create_402_response,
    PaymentRequiredError,
)

# 1. Configure the client with your recipient addresses
config = X402Config(
    recipient_evm="0xYourEVMWallet...",           # For Base, Ethereum, etc.
    recipient_solana="YourSolanaAddress...",      # For Solana, Fogo
    recipient_near="your-account.near",           # For NEAR
    recipient_stellar="G...YourStellarAddress",   # For Stellar
    recipient_algorand="YOUR_ALGO_ADDRESS...",    # For Algorand
    recipient_sui="0xYourSuiAddress...",          # For Sui
    recipient_xrpl="r...YourXRPLAddress",         # For XRP Ledger (native XRP)
)

client = X402Client(config=config)

def handle_api_request(request):
    """
    Handle an API request that requires payment.
    """
    price = Decimal("1.00")  # $1.00 USD

    # Check if payment header exists
    x_payment = request.headers.get("X-PAYMENT")

    if not x_payment:
        # No payment provided - return 402 Payment Required
        return {
            "status": 402,
            "headers": {
                "Content-Type": "application/json",
            },
            "body": create_402_response(
                amount_usd=price,
                config=config,
                resource="/api/premium",
                description="Premium API access",
            )
        }

    # Payment provided - verify and settle
    try:
        result = client.process_payment(x_payment, price)

        # Payment successful!
        return {
            "status": 200,
            "body": {
                "success": True,
                "message": "Payment verified and settled!",
                "payer": result.payer_address,
                "network": result.network,
                "transaction_hash": result.transaction_hash,
                "amount_paid": str(result.amount),
            }
        }

    except PaymentRequiredError as e:
        # Payment verification failed
        return {
            "status": 402,
            "body": {"error": str(e)}
        }

# The 402 response includes payment options for all configured networks:
# {
#     "x402Version": 1,
#     "accepts": [
#         {"network": "base", "asset": "0x833589fCD...", "amount": "1000000", "payTo": "0xYour..."},
#         {"network": "solana", "asset": "EPjFWdd5...", "amount": "1000000", "payTo": "Your..."},
#         {"network": "near", "asset": "17208628...", "amount": "1000000", "payTo": "your.near"},
#         {"network": "stellar", "asset": "CCW67Q...", "amount": "10000000", "payTo": "G..."},
#         {"network": "algorand", "asset": "31566704", "amount": "1000000", "payTo": "YOUR..."},
#         {"network": "sui", "asset": "0xdba346...", "amount": "1000000", "payTo": "0xYour..."},
#     ],
#     "payTo": "0xYour...",
#     "maxAmountRequired": "1000000",
#     "resource": "/api/premium",
#     "description": "Premium API access"
# }
```

### Using the Decorator (Simpler)

For even simpler integration, use the `@require_payment` decorator:

```python
from decimal import Decimal
from uvd_x402_sdk import require_payment, configure_x402

# Configure once at startup
configure_x402(
    recipient_address="0xYourEVMWallet...",
    recipient_solana="YourSolanaAddress...",
)

@require_payment(amount_usd=Decimal("1.00"))
def premium_endpoint(payment_result):
    """
    This function only runs if payment is verified.
    Returns 402 automatically if no valid payment.
    """
    return {
        "data": "Premium content here!",
        "paid_by": payment_result.payer_address,
        "tx": payment_result.transaction_hash,
    }
```

## Supported Networks

| Network | Type | Chain ID | CAIP-2 | Status |
|---------|------|----------|--------|--------|
| Base | EVM | 8453 | `eip155:8453` | Active |
| Ethereum | EVM | 1 | `eip155:1` | Active |
| Polygon | EVM | 137 | `eip155:137` | Active |
| Arbitrum | EVM | 42161 | `eip155:42161` | Active |
| Optimism | EVM | 10 | `eip155:10` | Active |
| Avalanche | EVM | 43114 | `eip155:43114` | Active |
| Celo | EVM | 42220 | `eip155:42220` | Active |
| HyperEVM | EVM | 999 | `eip155:999` | Active |
| Unichain | EVM | 130 | `eip155:130` | Active |
| Monad | EVM | 143 | `eip155:143` | Active |
| Scroll | EVM | 534352 | `eip155:534352` | Active |
| SKALE | EVM | 1187947933 | `eip155:1187947933` | Active |
| SKALE Testnet | EVM | 324705682 | `eip155:324705682` | Active |
| HashKey | EVM | 177 | `eip155:177` | Active |
| HashKey Testnet | EVM | 133 | `eip155:133` | Active |
| Robinhood | EVM | 4663 | `eip155:4663` | Active |
| Robinhood Testnet | EVM | 46630 | `eip155:46630` | Active |
| Arc | EVM | 5042 | `eip155:5042` | Active |
| Arc Testnet | EVM | 5042002 | `eip155:5042002` | Active |
| Solana | SVM | - | `solana:5eykt...` | Active |
| Fogo | SVM | - | `solana:fogo` | Active |
| NEAR | NEAR | - | `near:mainnet` | Active |
| Stellar | Stellar | - | `stellar:pubnet` | Active |
| Algorand | Algorand | - | `algorand:mainnet` | Active |
| Algorand Testnet | Algorand | - | `algorand:testnet` | Active |
| Sui | Sui | - | `sui:mainnet` | Active |
| Sui Testnet | Sui | - | `sui:testnet` | Active |
| XRP Ledger | XRPL | - | _(no CAIP-2)_ `xrpl` | Active |
| XRP Ledger Testnet | XRPL | - | _(no CAIP-2)_ `xrpl-testnet` | Active |
| Hedera | Hedera (native) | - | `hedera:mainnet` | Active (v2/exact) |
| Hedera Testnet | Hedera (native) | - | `hedera:testnet` | Active (v2/exact) |

> **HashKey Chain** (`hashkey` / `hashkey-testnet`) uses HSK for gas and USDC with 6 decimals for payments. Mainnet signs with `Bridged USDC / 2`; testnet uses `USD Coin / 2`. HashKey USDT is not supported because it lacks EIP-3009.

### Supported Tokens

| Token | Networks | Decimals |
|-------|----------|----------|
| USDC | All listed networks except Robinhood mainnet/testnet and XRPL mainnet/testnet | 6 (7 on Stellar) |
| EURC | Ethereum, Base, Avalanche, Arc mainnet/testnet | 6 |
| AUSD | Ethereum, Arbitrum, Avalanche, Polygon, Monad, Solana, Sui | 6 |
| PYUSD | Ethereum | 6 |
| USDT | Arbitrum, Optimism, Celo, Monad | 6 |
| USDG | Robinhood, Robinhood Testnet | 6 |
| XRP (native, not a stablecoin) | XRP Ledger, XRP Ledger Testnet | 6 |

> **Arc uses one USDC balance at two precisions.** Native gas uses 18 decimals; ERC-20 payments use 6. Both Arc networks sign `$0.01` as `10000` atomic units. Do not add the native and ERC-20 balance readings together.

> **Robinhood Chain settles in Paxos USDG, not USDC.** USDG's on-chain `version()` getter reverts, so clients MUST send the EIP-712 domain `{"name": "Global Dollar", "version": "1"}` in `PaymentRequirements.extra`. The SDK carries this automatically for the `robinhood` / `robinhood-testnet` networks.

### Payment request headers

All server integrations (FastAPI, Flask, Django, Lambda and `require_payment`)
accept `X-PAYMENT` or `PAYMENT-SIGNATURE`, with case-insensitive header names.
When both are present, their values must be identical after removing surrounding
HTTP spaces and tabs (SP/HTAB) for comparison; distinct values return HTTP 400 before verification
or settlement. An empty header or
a payload without a non-empty `network` (v1) or `accepted.network` (v2), or a
network with surrounding whitespace, also returns 400. With neither header the
server returns 402. The selected original header bytes are preserved for purchase
bindings, verification and settlement, so existing bound payments remain recoverable.
Lambda also reads API Gateway
`multiValueHeaders`; a custom `require_payment(header_name=...)` is an alias
subject to the same conflict rule.

## Installation

```bash
# Core SDK (minimal dependencies)
pip install uvd-x402-sdk

# With wallet signing support (EIP-3009)
pip install uvd-x402-sdk[wallet]     # WalletAdapter + EnvKeyAdapter
pip install uvd-x402-sdk[signer]     # Alias for wallet (backward compat)

# With framework support
pip install uvd-x402-sdk[flask]      # Flask integration
pip install uvd-x402-sdk[fastapi]    # FastAPI/Starlette integration + ERC-8128 verifier
pip install uvd-x402-sdk[django]     # Django integration
pip install uvd-x402-sdk[aws]        # AWS Lambda helpers
pip install uvd-x402-sdk[algorand]   # Algorand atomic group helpers

# All integrations
pip install uvd-x402-sdk[all]
```

---

## Paying a `batch-settlement` seller (buyer side)

A seller that answers 402 with `scheme: "batch-settlement"` asks for a payment channel instead of one transfer per
request. `BatchSettlementClient` signs the deposit (first request) and then one cumulative voucher per request:

```python
from uvd_x402_sdk.batch_settlement import BatchSettlementClient, FileChannelStorage
from uvd_x402_sdk.wallet import EnvKeyAdapter

client = BatchSettlementClient(EnvKeyAdapter(), storage=FileChannelStorage("channels.json"), max_deposit=100_000)
prepared = client.create_payment(accepts[0])          # accepts[0] is the 402's batch-settlement offer
resp = httpx.post(url, json=body, headers={"PAYMENT-SIGNATURE": prepared.header()})
if resp.status_code == 200:
    client.confirm(prepared, settle_extra_from(resp))  # PAYMENT-RESPONSE.extra: chargedAmount, channelState
```

The deposit is capped by `max_deposit` (a seller's `minDeposit` is a target, never an order), the cumulative lives in
the storage you give it (persist it: a process that forgets it signs vouchers the seller rejects), and only USDC-style
ERC-3009 deposits on `eip155` networks are signed. Permit2, cooperative refund and corrective-402 resync are not
implemented.

---

## Framework Examples

### Flask

```python
from decimal import Decimal
from flask import Flask, g, jsonify
from uvd_x402_sdk.integrations import FlaskX402

app = Flask(__name__)
x402 = FlaskX402(
    app,
    recipient_address="0xYourEVMWallet...",
    recipient_solana="YourSolanaAddress...",
    recipient_near="your-account.near",
    recipient_stellar="G...YourStellarAddress",
)

@app.route("/api/premium")
@x402.require_payment(amount_usd=Decimal("5.00"))
def premium():
    return jsonify({
        "message": "Premium content!",
        "payer": g.payment_result.payer_address,
        "tx": g.payment_result.transaction_hash,
        "network": g.payment_result.network,
    })

@app.route("/api/basic")
@x402.require_payment(amount_usd=Decimal("0.10"))
def basic():
    return jsonify({"data": "Basic tier data"})

if __name__ == "__main__":
    app.run(debug=True)
```

### FastAPI

```python
from decimal import Decimal
from fastapi import FastAPI, Depends
from uvd_x402_sdk.config import X402Config
from uvd_x402_sdk.models import PaymentResult
from uvd_x402_sdk.integrations import FastAPIX402

app = FastAPI()
x402 = FastAPIX402(
    app,
    recipient_address="0xYourEVMWallet...",
    recipient_solana="YourSolanaAddress...",
    recipient_near="your-account.near",
    recipient_stellar="G...YourStellarAddress",
)

@app.get("/api/premium")
async def premium(
    payment: PaymentResult = Depends(x402.require_payment(amount_usd="5.00"))
):
    return {
        "message": "Premium content!",
        "payer": payment.payer_address,
        "network": payment.network,
    }

@app.post("/api/generate")
async def generate(
    body: dict,
    payment: PaymentResult = Depends(x402.require_payment(amount_usd="1.00"))
):
    # Dynamic processing based on request
    return {"result": "generated", "payer": payment.payer_address}
```

To charge by path instead, add `X402Middleware`. Its `protected_paths` are request paths, written
with or without the app's mount (`root_path`), matched exactly (case and a trailing slash count)
against the ASGI scope path (the one the app routes on), independent of the `Host` header:

```python
from starlette.middleware.trustedhost import TrustedHostMiddleware
from uvd_x402_sdk.integrations.fastapi_integration import X402Middleware

app.add_middleware(X402Middleware, config=config, protected_paths={"/api/premium": Decimal("5.00")})
# Good practice for any public app: answer only for the hosts you serve.
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com"])
```

### Django

```python
# settings.py
X402_FACILITATOR_URL = "https://facilitator.ultravioletadao.xyz"
X402_RECIPIENT_EVM = "0xYourEVMWallet..."
X402_RECIPIENT_SOLANA = "YourSolanaAddress..."
X402_RECIPIENT_NEAR = "your-account.near"
X402_RECIPIENT_STELLAR = "G...YourStellarAddress"
X402_PROTECTED_PATHS = {
    "/api/premium/": "5.00",
    "/api/basic/": "1.00",
}

MIDDLEWARE = [
    # ...other middleware...
    "uvd_x402_sdk.integrations.django_integration.DjangoX402Middleware",
]

# views.py
from django.http import JsonResponse
from uvd_x402_sdk.integrations import django_x402_required

@django_x402_required(amount_usd="5.00")
def premium_view(request):
    payment = request.payment_result
    return JsonResponse({
        "message": "Premium content!",
        "payer": payment.payer_address,
    })
```

### AWS Lambda

```python
import json
from decimal import Decimal
from uvd_x402_sdk.config import X402Config
from uvd_x402_sdk.integrations import LambdaX402

config = X402Config(
    recipient_evm="0xYourEVMWallet...",
    recipient_solana="YourSolanaAddress...",
    recipient_near="your-account.near",
    recipient_stellar="G...YourStellarAddress",
)
x402 = LambdaX402(config=config)

def handler(event, context):
    # Calculate price based on request
    body = json.loads(event.get("body", "{}"))
    quantity = body.get("quantity", 1)
    price = Decimal(quantity) * Decimal("0.01")

    # Process payment or return 402
    result = x402.process_or_require(event, price)

    # If 402 response, return it
    if isinstance(result, dict) and "statusCode" in result:
        return result

    # Payment verified!
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({
            "success": True,
            "payer": result.payer_address,
            "tx": result.transaction_hash,
            "network": result.network,
            "quantity": quantity,
        })
    }
```

---

## Network-Specific Examples

### EVM Chains (Base, Ethereum, Polygon, etc.)

EVM chains use ERC-3009 `TransferWithAuthorization` with EIP-712 signatures.

```python
from uvd_x402_sdk import X402Client, X402Config

# Accept payments on Base and Ethereum only
config = X402Config(
    recipient_evm="0xYourEVMWallet...",
    supported_networks=["base", "ethereum"],
)

client = X402Client(config=config)
result = client.process_payment(x_payment_header, Decimal("10.00"))

# The payload contains EIP-712 signature + authorization
payload = client.extract_payload(x_payment_header)
evm_data = payload.get_evm_payload()
print(f"From: {evm_data.authorization.from_address}")
print(f"To: {evm_data.authorization.to}")
print(f"Value: {evm_data.authorization.value}")
```

### Solana & Fogo (SVM Chains)

SVM chains use partially-signed VersionedTransactions with SPL token transfers.

```python
from uvd_x402_sdk import X402Client, X402Config

# Accept payments on Solana and Fogo
config = X402Config(
    recipient_solana="YourSolanaAddress...",
    supported_networks=["solana", "fogo"],
)

client = X402Client(config=config)
result = client.process_payment(x_payment_header, Decimal("5.00"))

# The payload contains a base64-encoded VersionedTransaction
payload = client.extract_payload(x_payment_header)
svm_data = payload.get_svm_payload()
print(f"Transaction: {svm_data.transaction[:50]}...")

# Fogo has ultra-fast finality (~400ms)
if result.network == "fogo":
    print("Payment confirmed in ~400ms!")
```

### Stellar

Stellar uses Soroban Authorization Entries with fee-bump transactions.

```python
from uvd_x402_sdk import X402Client, X402Config

config = X402Config(
    recipient_stellar="G...YourStellarAddress",
    supported_networks=["stellar"],
)

client = X402Client(config=config)
result = client.process_payment(x_payment_header, Decimal("1.00"))

# Stellar uses 7 decimals (stroops)
payload = client.extract_payload(x_payment_header)
stellar_data = payload.get_stellar_payload()
print(f"From: {stellar_data.from_address}")
print(f"Amount (stroops): {stellar_data.amount}")
print(f"Token Contract: {stellar_data.tokenContract}")
```

### NEAR Protocol

NEAR uses NEP-366 meta-transactions with Borsh serialization.

Arras escrow helpers (`uvd_x402_sdk.near_escrow`, extra `near`) sign local Ed25519
`ft_transfer_call` authorizations and `release`/`refund`/`reclaim`/`withdraw`/`withdraw_for`
delegates offline. See [the public API and facilitator request examples](docs/near-escrow.md).
Signing requires a contract in `NEAR_ESCROW_CONTRACTS` for its network and advertised facilitator support.
The registry contains `arras-v1b-1101.testnet` on testnet and `v1.arras-escrow.near` and
`v2.arras-escrow.near` on mainnet. Arras v2 (`NEAR_ESCROW_V2_CONTRACTS`: `v2.arras-escrow.near`; none
on testnet) adds the optional `dispute_deadline` and `operator_ticket` to the authorize msg;
`sign_operator_ticket` / `check_operator_ticket` / `verify_operator_ticket` sign and check the
operator's Ed25519 ticket (vectors T-1/T-2). ERC-8004 rates each payment with the verifier of its
escrow (`near_erc8004_verifier`): v1's is `erc8004-verifier.arras-escrow.near`, v2's
`payment-proof.arras-escrow.near` (0.114.0). Pass the payment's `escrow=` to the proof builders,
signing and views, and a verifier of the other escrow is refused before signing
([guide](docs/near-erc8004.md)).

```python
from uvd_x402_sdk import X402Client, X402Config

config = X402Config(
    recipient_near="your-recipient.near",
    supported_networks=["near"],
)

client = X402Client(config=config)
result = client.process_payment(x_payment_header, Decimal("2.00"))

# NEAR payload contains a SignedDelegateAction
payload = client.extract_payload(x_payment_header)
near_data = payload.get_near_payload()
print(f"SignedDelegateAction: {near_data.signedDelegateAction[:50]}...")

# Validate NEAR payload structure
from uvd_x402_sdk.networks.near import validate_near_payload
validate_near_payload(payload.payload)  # Raises ValueError if invalid
```

### Algorand

Algorand uses atomic groups with ASA (Algorand Standard Assets) transfers.

```python
from uvd_x402_sdk import X402Client, X402Config

config = X402Config(
    recipient_algorand="NCDSNUQ2QLXDMJXRALAW4CRUSSKG4IS37MVOFDQQPC45SE4EBZO42U6ZX4",
    supported_networks=["algorand"],
)

client = X402Client(config=config)
result = client.process_payment(x_payment_header, Decimal("1.00"))

# Algorand uses atomic groups: [fee_tx, payment_tx]
from uvd_x402_sdk.networks.algorand import (
    validate_algorand_payload,
    get_algorand_fee_payer,
    build_atomic_group,
)

# Get the facilitator fee payer address
fee_payer = get_algorand_fee_payer("algorand")
print(f"Fee payer: {fee_payer}")  # KIMS5H6Q...

# Validate payload structure
payload = client.extract_payload(x_payment_header)
validate_algorand_payload(payload.payload)  # Raises ValueError if invalid
```

#### Building Algorand Payments (requires `pip install uvd-x402-sdk[algorand]`)

```python
from uvd_x402_sdk.networks.algorand import (
    build_atomic_group,
    build_x402_payment_request,
    get_algorand_fee_payer,
)
from algosdk.v2client import algod

# Connect to Algorand node
client = algod.AlgodClient("", "https://mainnet-api.algonode.cloud")

# Build atomic group
payload = build_atomic_group(
    sender_address="YOUR_ADDRESS...",
    recipient_address="MERCHANT_ADDRESS...",
    amount=1000000,  # 1 USDC (6 decimals)
    asset_id=31566704,  # USDC ASA ID on mainnet
    facilitator_address=get_algorand_fee_payer("algorand"),
    sign_transaction=lambda txn: txn.sign(private_key),
    algod_client=client,
)

# Build x402 payment request
request = build_x402_payment_request(payload, network="algorand")
```

### Sui

Sui uses sponsored transactions with Move-based programmable transaction blocks.

```python
from uvd_x402_sdk import X402Client, X402Config

config = X402Config(
    recipient_sui="0xYourSuiAddress...",
    supported_networks=["sui"],
)

client = X402Client(config=config)
result = client.process_payment(x_payment_header, Decimal("1.00"))

# Sui payload contains a user-signed PTB that the facilitator sponsors
payload = client.extract_payload(x_payment_header)
sui_data = payload.get_sui_payload()
print(f"From: {sui_data.from_address}")
print(f"To: {sui_data.to}")
print(f"Amount: {sui_data.amount}")
print(f"Coin Object ID: {sui_data.coinObjectId}")
print(f"Transaction Bytes: {sui_data.transactionBytes[:50]}...")

# Sui uses sponsored transactions (user pays ZERO SUI for gas)
# Facilitator adds sponsor signature and pays gas fees
```

#### Sui-Specific Utilities

```python
from uvd_x402_sdk.networks.sui import (
    validate_sui_payload,
    is_valid_sui_address,
    is_valid_sui_coin_type,
    get_sui_fee_payer,
    get_sui_usdc_coin_type,
    get_sui_ausd_coin_type,
    SUI_FEE_PAYER_MAINNET,
    SUI_USDC_COIN_TYPE_MAINNET,
    SUI_AUSD_COIN_TYPE_MAINNET,
)

# Validate Sui addresses (0x + 64 hex chars)
assert is_valid_sui_address("0xe7bbf2b13f7d72714760aa16e024fa1b35a978793f9893d0568a4fbf356a764a")

# Validate coin types (package::module::type format)
assert is_valid_sui_coin_type(SUI_USDC_COIN_TYPE_MAINNET)

# Get fee payer (sponsor) address
fee_payer = get_sui_fee_payer("sui")  # Returns mainnet sponsor
print(f"Sui sponsor: {fee_payer}")

# Get USDC coin type
usdc_type = get_sui_usdc_coin_type("sui")
# '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'

# Get AUSD coin type (mainnet only)
ausd_type = get_sui_ausd_coin_type("sui")
# '0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD'

# Validate Sui payment payload
payload = client.extract_payload(x_payment_header)
validate_sui_payload(payload.payload)  # Raises ValueError if invalid
```

### XRPL (XRP Ledger)

XRPL uses the t54 scheme. The user signs a Payment transaction sending native XRP to the merchant; the facilitator submits it to the ledger and pays the network fee. Payment details (`payTo`, `amount`, `asset`) travel in `PaymentRequirements`/`extra`, so the payload carries only the signed transaction blob.

**XRPL settles in XRP, and XRP is not a dollar.** A price written in USD cannot be
scaled by the network's 6 decimals — that charges 1 XRP for `Decimal("1.00")`. Since
0.77.0 the SDK refuses that conversion and asks you to name a dollar-pegged token the
facilitator settles on XRPL (it lists them in `GET /supported`; USDC is there), or to
price the call in drops yourself.

```python
from uvd_x402_sdk import X402Client, X402Config

config = X402Config(
    recipient_xrpl="r...YourXRPLAddress",
    supported_networks=["xrpl"],
)

client = X402Client(config=config)

# USDC on XRPL — a dollar really is a dollar here.
XRPL_USDC = "5553444300000000000000000000000000000000.rGm7WCVp9gb4jZHWTEtGUr4dd74z2XuWhE"
result = client.process_payment(
    x_payment_header, Decimal("1.00"),
    asset=XRPL_USDC, token_decimals=6,
)

# Charging in native XRP means pricing in XRP, not in dollars:
#   result = client.process_payment(header, Decimal("2.5"), asset="XRP", token_decimals=6)

# XRPL payload carries only the signed Payment transaction blob (hex)
payload = client.extract_payload(x_payment_header)
xrpl_data = payload.get_xrpl_payload()
print(f"Signed tx blob: {xrpl_data.signed_tx_blob[:50]}...")
```

#### XRPL-Specific Utilities

```python
from uvd_x402_sdk.networks.xrpl import (
    drops_to_xrp,
    xrp_to_drops,
    is_valid_xrpl_address,
    get_xrpl_fee_payer,
)
from uvd_x402_sdk import XRPL_FEE_PAYER_MAINNET, XRPL_FEE_PAYER_TESTNET

# Native XRP uses 6 decimals (drops): 1 XRP = 1,000,000 drops
assert xrp_to_drops(1.5) == 1_500_000
assert drops_to_xrp(1_000_000) == 1.0

# Validate classic addresses (start with 'r', base58, 25-35 chars)
assert is_valid_xrpl_address("rfADKkVXBNqK3z72tVSS3LVzAR3psYkonp")

# Get the facilitator fee payer (submits the tx + pays the network fee)
fee_payer = get_xrpl_fee_payer("xrpl")
print(f"XRPL fee payer: {fee_payer}")  # rfADKkVXBNqK3z72tVSS3LVzAR3psYkonp
```

---

## x402 v1 vs v2

The SDK supports both x402 protocol versions with automatic detection.

### Version Differences

| Aspect | v1 | v2 |
|--------|----|----|
| Network ID | String (`"base"`) | CAIP-2 (`"eip155:8453"`) |
| Payment delivery | JSON body | `PAYMENT-REQUIRED` header |
| Multiple options | Limited | `accepts` array |
| Discovery | Implicit | Optional extension |

### Auto-Detection

```python
from uvd_x402_sdk import PaymentPayload

# The SDK auto-detects based on network format
payload = PaymentPayload(
    x402Version=1,
    scheme="exact",
    network="base",  # v1 format
    payload={"signature": "...", "authorization": {...}}
)

print(payload.is_v2())  # False

payload_v2 = PaymentPayload(
    x402Version=2,
    scheme="exact",
    network="eip155:8453",  # v2 CAIP-2 format
    payload={"signature": "...", "authorization": {...}}
)

print(payload_v2.is_v2())  # True

# Both work the same way
print(payload.get_normalized_network())  # "base"
print(payload_v2.get_normalized_network())  # "base"
```

### Creating v2 Responses

```python
from uvd_x402_sdk import X402Config, create_402_response_v2, Payment402BuilderV2

config = X402Config(
    recipient_evm="0xYourEVM...",
    recipient_solana="YourSolana...",
    recipient_near="your.near",
    recipient_stellar="G...Stellar",
)

# Simple v2 response
response = create_402_response_v2(
    amount_usd=Decimal("5.00"),
    config=config,
    resource="/api/premium",
    description="Premium API access",
)
# Returns:
# {
#     "x402Version": 2,
#     "scheme": "exact",
#     "resource": "/api/premium",
#     "accepts": [
#         {"network": "eip155:8453", "asset": "0x833...", "amount": "5000000", "payTo": "0xYour..."},
#         {"network": "solana:5eykt...", "asset": "EPjF...", "amount": "5000000", "payTo": "Your..."},
#         {"network": "near:mainnet", "asset": "1720...", "amount": "5000000", "payTo": "your.near"},
#         ...
#     ]
# }

# Builder pattern for more control
response = (
    Payment402BuilderV2(config)
    .amount(Decimal("10.00"))
    .resource("/api/generate")
    .description("AI generation credits")
    .networks(["base", "solana", "near"])  # Limit to specific networks
    .build()
)
```

---

## Payload Validation

Each network type has specific payload validation:

### EVM Validation

```python
from uvd_x402_sdk.models import EVMPayloadContent, EVMAuthorization

# Parse and validate EVM payload
payload = client.extract_payload(x_payment_header)
evm_data = payload.get_evm_payload()

# Validate authorization fields
auth = evm_data.authorization
assert auth.from_address.startswith("0x")
assert auth.to.startswith("0x")
assert int(auth.value) > 0
assert int(auth.validBefore) > int(auth.validAfter)
```

### SVM Validation

```python
from uvd_x402_sdk.networks.solana import validate_svm_payload, is_valid_solana_address

# Validate SVM payload
payload = client.extract_payload(x_payment_header)
validate_svm_payload(payload.payload)  # Raises ValueError if invalid

# Validate Solana addresses
assert is_valid_solana_address("YourSolanaAddress...")
```

### NEAR Validation

```python
from uvd_x402_sdk.networks.near import (
    validate_near_payload,
    is_valid_near_account_id,
    BorshSerializer,
)

# Validate NEAR payload
payload = client.extract_payload(x_payment_header)
validate_near_payload(payload.payload)  # Raises ValueError if invalid

# Validate NEAR account IDs
assert is_valid_near_account_id("your-account.near")
assert is_valid_near_account_id("0xultravioleta.near")
```

### Stellar Validation

```python
from uvd_x402_sdk.networks.stellar import (
    is_valid_stellar_address,
    is_valid_contract_address,
    stroops_to_usd,
)

# Validate Stellar addresses
assert is_valid_stellar_address("G...YourStellarAddress")  # G...
assert is_valid_contract_address("C...USDCContract")  # C...

# Convert stroops to USD (7 decimals)
usd = stroops_to_usd(50000000)  # Returns 5.0
```

---

## Configuration

### Environment Variables

```bash
# Core configuration
X402_FACILITATOR_URL=https://facilitator.ultravioletadao.xyz
X402_VERIFY_TIMEOUT=30
X402_SETTLE_TIMEOUT=55

# Recipient addresses (at least one required)
X402_RECIPIENT_EVM=0xYourEVMWallet
X402_RECIPIENT_SOLANA=YourSolanaAddress
X402_RECIPIENT_NEAR=your-account.near
X402_RECIPIENT_STELLAR=G...YourStellarAddress
X402_RECIPIENT_XRPL=r...YourXRPLAddress

# Optional
X402_FACILITATOR_SOLANA=F742C4VfFLQ9zRQyithoj5229ZgtX2WqKCSFKgH2EThq
X402_RESOURCE_URL=https://api.example.com
X402_DESCRIPTION=API access payment
```

### Programmatic Configuration

```python
from uvd_x402_sdk import X402Config, MultiPaymentConfig

# Full configuration
config = X402Config(
    facilitator_url="https://facilitator.ultravioletadao.xyz",

    # Recipients
    recipient_evm="0xYourEVMWallet",
    recipient_solana="YourSolanaAddress",
    recipient_near="your-account.near",
    recipient_stellar="G...YourStellarAddress",

    # Timeouts
    verify_timeout=30.0,
    settle_timeout=55.0,

    # Limit to specific networks
    supported_networks=["base", "solana", "near", "stellar"],

    # Metadata
    resource_url="https://api.example.com/premium",
    description="Premium API access",

    # Protocol version (1, 2, or "auto")
    x402_version="auto",
)

# From environment
config = X402Config.from_env()
```

### One facilitator per network

Some deployments cannot settle every chain through the same facilitator —
Coinbase's CDP facilitator, for example, does not settle Avalanche. Map the
networks that need a different one; everything else is unchanged.

```python
from uvd_x402_sdk import X402Client

client = X402Client(
    recipient_address="0xYourEVMWallet",
    supported_networks=["base", "avalanche"],
    facilitator_by_network={
        "base": "https://api.cdp.coinbase.com/platform/v2/x402",
        "avalanche": "https://facilitator.ultravioletadao.xyz",
    },
)

client.facilitator_url_for("base")          # -> the CDP URL
client.facilitator_url_for("eip155:43114")  # -> the UVD URL (CAIP-2 works too)
```

Three rules make this safe to run in production:

1. **Not configured = nothing changes.** Without `facilitator_by_network` every
   network resolves to `facilitator_url`, exactly as before.
2. **It never guesses.** A network that is not in the table raises
   `ConfigurationError` instead of falling back to `facilitator_url` — silently
   settling on a facilitator that does not support that chain is a money bug.
   Declare a fallback explicitly with the reserved `"*"` key:
   `{"base": CDP, "*": UVD}`.
3. **It fails at boot, not at the first payment.** An enabled network with no
   route raises in the constructor. Either route every network in
   `supported_networks`, narrow that list, or add `"*"`. Pass
   `verify_facilitator_support=True` to also probe each facilitator's
   `GET /supported` at construction and refuse a route the facilitator itself
   does not advertise (available on demand as `client.verify_routes()`).

From the environment, as a JSON object:

```bash
X402_FACILITATOR_BY_NETWORK='{"base":"https://api.cdp.coinbase.com/platform/v2/x402","avalanche":"https://facilitator.ultravioletadao.xyz"}'
```

`/verify`, `/settle` (including the post-timeout re-check, which always asks the
same facilitator the settle went to) and `/accepts` follow the table. The
endpoints that are not network-scoped — `/version`, `/blacklist`, `/api/stats`,
`/transactions` — use `facilitator_url`; `get_supported()` and `health_check()`
accept an optional `network=` to target one facilitator.

### Stack key (`X-UVD-Stack-Key`) — services of Ultravioleta DAO only

The Ultravioleta facilitator exempts the services of its own stack from its
policy rate limits (the `429`s of its per-address budgets) when a request
carries the service's key. Ultravioleta DAO issues one key per service
(`uvdsk_` followed by 43 to 128 base64url characters); the service keeps it in
its secret store and hands it to the SDK as `UVD_STACK_KEY`:

```python
import os
from uvd_x402_sdk import X402Client, X402Config
from uvd_x402_sdk.erc8004 import Erc8004Client

client = X402Client(config=X402Config.from_env())  # reads UVD_STACK_KEY
erc8004 = Erc8004Client(stack_key=os.environ.get("UVD_STACK_KEY"))
```

- **Not for third parties.** There is nothing to request or configure: without
  a key the SDK sends no header and every request is made exactly as before. A
  facilitator that does not know the header ignores it.
- **Only to a facilitator of Ultravioleta DAO.** The key travels over `https`
  to `facilitator.ultravioletadao.xyz` and to no other host: not to a
  third-party facilitator that `facilitator_by_network` routes to, not over
  plain `http`, not to a look-alike (`facilitator.ultravioletadao.xyz.evil`,
  a subdomain, the name in a path). The host is the one the HTTP library will
  contact, read with its own parser (httpx, and urllib3 for a `requests`
  session); a URL they read differently gets the key only if every reading is
  allowed. `stack_key_hosts=[...]` ADDS hosts (a staging facilitator); it
  never removes the default. Plain `http` is accepted only to `127.0.0.1` or
  `localhost` named there, for a local test double. A request to any other
  host goes without the key, and one warning per process names its origin
  (`stack key not sent: <origin> is not a house facilitator`).
- **The key does not follow redirects.** A redirect answered to a request that
  carries it raises `StackKeyRedirectError` (a `FacilitatorError`), and
  nothing is sent again. The functions that never raise report it their own
  way (`success=False`, `anchor_failed`, `[]`).
- **Every client of the facilitator carries it, and nothing else does.**
  `X402Client` (`/verify`, `/settle` and its re-check after a timeout,
  `/accepts`, `/supported`, `/version` and the other reads), `Erc8004Client`
  (every read and write), `AdvancedEscrowClient` (escrow settles and
  `/escrow/state`), `EscrowClient`, `BazaarClient`, `TrafficEventStream`,
  `anchor_evidence()` / `available_backends()` and `get_receipt()` all take
  `stack_key=` and `stack_key_hosts=`. The key is a header of each request,
  never a default of an HTTP client, so the sellers `fetch()` reaches and the
  URL `resolve_agent_uri()` fetches never see it.
- **A key read badly never breaks a payment.** A leading byte order mark and
  the whitespace at both ends (a trailing `\r\n` from a file) go away, and the
  rest is checked against the format. One that does not match is not sent:
  the request goes as a third party's, the payment goes through, and the SDK
  logs one warning per process, without the value. The key is never in a
  `repr()`, `to_dict()`, `vars()`, `dataclasses.asdict()`, a pickle, an error
  or a log (a pickled or deep-copied config carries no key).

---

## Facilitator Addresses

The SDK includes all facilitator addresses as embedded constants. You don't need to configure them manually.

### Fee Payer Addresses (Non-EVM)

Non-EVM chains require a fee payer address for gasless transactions:

```python
from uvd_x402_sdk import (
    # Algorand
    ALGORAND_FEE_PAYER_MAINNET,  # KIMS5H6QLCUDL65L5UBTOXDPWLMTS7N3AAC3I6B2NCONEI5QIVK7LH2C2I
    ALGORAND_FEE_PAYER_TESTNET,  # 5DPPDQNYUPCTXRZWRYSF3WPYU6RKAUR25F3YG4EKXQRHV5AUAI62H5GXL4

    # Solana
    SOLANA_FEE_PAYER_MAINNET,    # F742C4VfFLQ9zRQyithoj5229ZgtX2WqKCSFKgH2EThq
    SOLANA_FEE_PAYER_DEVNET,     # 6xNPewUdKRbEZDReQdpyfNUdgNg8QRc8Mt263T5GZSRv

    # Fogo
    FOGO_FEE_PAYER_MAINNET,      # F742C4VfFLQ9zRQyithoj5229ZgtX2WqKCSFKgH2EThq
    FOGO_FEE_PAYER_TESTNET,      # 6xNPewUdKRbEZDReQdpyfNUdgNg8QRc8Mt263T5GZSRv

    # NEAR
    NEAR_FEE_PAYER_MAINNET,      # uvd-facilitator.near
    NEAR_FEE_PAYER_TESTNET,      # uvd-facilitator.testnet

    # Stellar
    STELLAR_FEE_PAYER_MAINNET,   # GCHPGXJT2WFFRFCA5TV4G4E3PMMXLNIDUH27PKDYA4QJ2XGYZWGFZNHB
    STELLAR_FEE_PAYER_TESTNET,   # GBBFZMLUJEZVI32EN4XA2KPP445XIBTMTRBLYWFIL556RDTHS2OWFQ2Z

    # Sui
    SUI_FEE_PAYER_MAINNET,       # 0xe7bbf2b13f7d72714760aa16e024fa1b35a978793f9893d0568a4fbf356a764a
    SUI_FEE_PAYER_TESTNET,       # 0xabbd16a2fab2a502c9cfe835195a6fc7d70bfc27cffb40b8b286b52a97006e67

    # XRPL
    XRPL_FEE_PAYER_MAINNET,      # rfADKkVXBNqK3z72tVSS3LVzAR3psYkonp
    XRPL_FEE_PAYER_TESTNET,      # rGhTioKAFHe75KgVnQtacRiKFuPv28Wbwk

    # Helper function
    get_fee_payer,               # Get fee payer for any network
)

# Get fee payer for any network
fee_payer = get_fee_payer("algorand")  # Returns KIMS5H6Q...
fee_payer = get_fee_payer("solana")    # Returns F742C4VfF...
fee_payer = get_fee_payer("sui")       # Returns 0xe7bbf2b...
fee_payer = get_fee_payer("base")      # Returns None (EVM doesn't need fee payer)
```

### EVM Facilitator Addresses

EVM chains use EIP-3009 transferWithAuthorization (gasless by design), but the facilitator wallet addresses are available for reference:

```python
from uvd_x402_sdk import (
    EVM_FACILITATOR_MAINNET,  # 0x103040545AC5031A11E8C03dd11324C7333a13C7
    EVM_FACILITATOR_TESTNET,  # 0x34033041a5944B8F10f8E4D8496Bfb84f1A293A8
)
```

### Helper Functions

```python
from uvd_x402_sdk import (
    get_fee_payer,           # Get fee payer address for a network
    requires_fee_payer,      # Check if network needs fee payer
    get_all_fee_payers,      # Get all registered fee payers
    build_payment_info,      # Build payment info with auto feePayer
    DEFAULT_FACILITATOR_URL, # https://facilitator.ultravioletadao.xyz
)

# Check if network needs fee payer
requires_fee_payer("algorand")  # True
requires_fee_payer("base")      # False

# Build payment info with automatic fee payer
info = build_payment_info(
    network="algorand",
    pay_to="MERCHANT_ADDRESS...",
    max_amount_required="1000000",
    description="API access"
)
# info = {
#     'network': 'algorand',
#     'payTo': 'MERCHANT_ADDRESS...',
#     'maxAmountRequired': '1000000',
#     'description': 'API access',
#     'asset': '31566704',
#     'extra': {
#         'token': 'usdc',
#         'feePayer': 'KIMS5H6QLCUDL65L5UBTOXDPWLMTS7N3AAC3I6B2NCONEI5QIVK7LH2C2I'
#     }
# }
```

---

## Registering Custom Networks

```python
from uvd_x402_sdk.networks import NetworkConfig, NetworkType, register_network

# Register a custom EVM network
custom_chain = NetworkConfig(
    name="mychain",
    display_name="My Custom Chain",
    network_type=NetworkType.EVM,
    chain_id=12345,
    usdc_address="0xUSDCContractAddress",
    usdc_decimals=6,
    usdc_domain_name="USD Coin",  # Check actual EIP-712 domain!
    usdc_domain_version="2",
    rpc_url="https://rpc.mychain.com",
    enabled=True,
)

register_network(custom_chain)

# Now you can use it
config = X402Config(
    recipient_evm="0xYourWallet...",
    supported_networks=["base", "mychain"],
)
```

---

## Multi-Token Support

The SDK supports 6 stablecoins on EVM chains. Use the token helper functions to query and work with different tokens.

### Querying Token Support

```python
from uvd_x402_sdk import (
    TokenType,
    get_token_config,
    get_supported_tokens,
    is_token_supported,
    get_networks_by_token,
)

# Check which tokens a network supports
tokens = get_supported_tokens("ethereum")
print(tokens)  # ['usdc', 'eurc', 'ausd', 'pyusd']

tokens = get_supported_tokens("base")
print(tokens)  # ['usdc', 'eurc']

# Check if a specific token is supported
if is_token_supported("ethereum", "eurc"):
    print("EURC is available on Ethereum!")

# Get token configuration
config = get_token_config("ethereum", "eurc")
if config:
    print(f"EURC address: {config.address}")
    print(f"Decimals: {config.decimals}")
    print(f"EIP-712 name: {config.name}")
    print(f"EIP-712 version: {config.version}")

# Find all networks that support a token
networks = get_networks_by_token("eurc")
for network in networks:
    print(f"EURC available on: {network.display_name}")
# Output: EURC available on: Base, Ethereum, Avalanche C-Chain, Arc, Arc Testnet
```

### Token Configuration

Each token has specific EIP-712 domain parameters required for signing:

```python
from uvd_x402_sdk import TokenConfig, get_token_config

# TokenConfig structure
# - address: Contract address
# - decimals: Token decimals (6 for all supported stablecoins)
# - name: EIP-712 domain name (e.g., "USD Coin", "EURC", "Gho Token")
# - version: EIP-712 domain version

# Example: Get EURC config on Base
eurc = get_token_config("base", "eurc")
# TokenConfig(
#     address="0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42",
#     decimals=6,
#     name="EURC",
#     version="2"
# )

# Example: Get PYUSD config on Ethereum
pyusd = get_token_config("ethereum", "pyusd")
# TokenConfig(
#     address="0x6c3ea9036406852006290770BEdFcAbA0e23A0e8",
#     decimals=6,
#     name="PayPal USD",
#     version="1"
# )
```

### Available Tokens

| Token | Description | Decimals | Issuer |
|-------|-------------|----------|--------|
| `usdc` | USD Coin | 6 | Circle |
| `eurc` | Euro Coin | 6 | Circle |
| `ausd` | Agora USD | 6 | Agora Finance |
| `pyusd` | PayPal USD | 6 | PayPal/Paxos |

### Critical Implementation Notes

#### EIP-712 Domain Names Vary by Chain

The same token may use **different EIP-712 domain names on different chains**. This affects signature verification.

| Token | Ethereum | Base | Avalanche |
|-------|----------|------|-----------|
| EURC | `"Euro Coin"` | `"EURC"` | `"Euro Coin"` |
| USDC | `"USD Coin"` | `"USD Coin"` | `"USD Coin"` |
| AUSD | `"Agora Dollar"` | N/A | `"Agora Dollar"` |
| PYUSD | `"PayPal USD"` | N/A | N/A |

**Important:** Always use `get_token_config()` to get the correct domain name. Never hardcode domain names.

```python
# CORRECT: Use get_token_config for each chain
eurc_base = get_token_config("base", "eurc")
# TokenConfig(name="EURC", version="2", ...)

eurc_ethereum = get_token_config("ethereum", "eurc")
# TokenConfig(name="Euro Coin", version="2", ...)
```

#### PYUSD Signature Format (PayPal USD)

PYUSD uses the Paxos implementation which only supports the **v,r,s signature variant** of `transferWithAuthorization`. This is different from Circle's USDC/EURC which support both compact bytes and v,r,s variants.

**Backend implications:**
- The x402 facilitator (v1.9.0+) automatically handles this by detecting PYUSD and using `transferWithAuthorization_1(v,r,s)` instead of `transferWithAuthorization_0(bytes signature)`
- If using a custom facilitator, ensure it supports the v,r,s variant for PYUSD

#### Token Info Must Be Passed to Facilitator

When using non-USDC tokens, your backend **must** pass the token info (including EIP-712 domain) to the facilitator. This is done via the `extra` field in `paymentRequirements`:

```python
# When building payment requirements for the facilitator
payment_requirements = {
    "asset": token_address,  # Use actual token address, NOT hardcoded USDC
    "extra": {
        "name": token_config.name,     # EIP-712 domain name
        "version": token_config.version,  # EIP-712 domain version
    }
}
```

Without this, the facilitator will use wrong EIP-712 domain and signature verification will fail with "invalid signature" error.

---

## Settle Overrides, Retry & Non-Raising Settle

### Asset / EIP-712 domain overrides (non-USDC settles)

`settle_payment()`, `verify_payment()` and `process_payment()` accept `asset` and
`eip712_domain` overrides. By default they send the network's USDC address and the SDK
registry's domain — the overrides let YOUR token registry decide instead (required when
the token is not in the SDK registry, or when registries drift on domain names):

```python
result = client.process_payment(
    header,
    Decimal("0.10"),
    asset="0x01bFF41798a0BcF287b996046Ca68b395DbC1071",   # the token you actually settle
    eip712_domain={"name": "USD₮0", "version": "1"},        # the domain the token contract uses
)
```

`create_authorization()` accepts the same `eip712_domain` override — there it changes the
**signed digest** (and the non-USDC `token.eip712` block), so the signature verifies
against the domain the verifier resolves. A partial domain (missing `name` or `version`)
raises `ValueError` before anything is signed or sent.

`maxTimeoutSeconds` of the requirements the client sends is `X402Config.max_timeout_seconds`
(default `60`; `X402Client(..., max_timeout_seconds=300)` passes it through). Native Hedera
keeps its 180. The USD amount is converted in `Decimal` (`Decimal("2.01")` is `2010000` base
units of USDC); pass `token_decimals` with an `asset` whose decimals are not the network's
USDC's.

### Extra requirements and the proof of payment

```python
from uvd_x402_sdk import ERC8004_EXTENSION_ID

response = client.settle_payment(
    payload,
    Decimal("0.10"),
    extra={ERC8004_EXTENSION_ID: {"includeProof": True}},   # "8004-reputation"
)
proof = response.proof_of_payment          # ProofOfPayment, or None
if proof is not None:
    wire_proof = proof.model_dump(by_alias=True)   # the facilitator's own object
```

`extra` (on `settle_payment()` and `try_settle_payment()`) is merged into
`paymentRequirements.extra`, values of any JSON type, on every attempt and in both envelopes.
An entry the SDK already set (the EIP-712 `name` / `version`, Hedera's `feePayer`) may be
repeated with the same value; another value raises `ValueError` before anything is sent (use
`eip712_domain`). With the `8004-reputation` extension, x402-rs returns `proofOfPayment` on a
network with ERC-8004, and `SettleResponse.proof_of_payment` carries it. It is `None` without
one, and `None` when the one sent does not parse: the settle still succeeds.

### Seeing the facilitator's raw answers (`http_client`)

```python
import httpx

def keep(response: httpx.Response) -> None:
    response.read()
    audit_log.write(response.request.url.path, response.status_code, response.text)

client = X402Client(
    recipient_address="0xYourWallet...",
    http_client=httpx.Client(event_hooks={"response": [keep]}),
)
```

Every facilitator call of the client (`/verify`, `/settle` and its timeout fallback,
`/supported`, ...) goes through the `httpx.Client` passed as `http_client`, and so do the
requests of the buyer's `fetch()`, the paid one included, unless `fetch()` gets an
`http_client` of its own. It stays the caller's: `client.close()` does not close it.

The SDK sets its own timeout on `/verify`, `/settle` and its timeout fallback, `/accepts`
and the `/supported` of route validation. `get_version()`, `get_supported()`,
`get_blacklist()`, `health_check()`, the other GETs and `fetch()` use the timeout of the
client passed in.

### Opt-in settle retry (anti-double-settle guard)

```python
response = client.settle_payment(payload, Decimal("0.10"), retry=True)
```

Default `False` — a single attempt, exactly as before. With `retry=True`: up to 3 attempts
with exponential backoff (1s, 2s), retrying **only** transient transport errors and 5xx.
Never retried:

- **4xx** — deterministic (bad request, auth, idempotency conflict); retrying amplifies it
- **`success=false` inside a 200** — a business error, not a transient one
- **A 5xx whose body already carries a transaction hash** — the facilitator broadcast the
  tx (e.g. a non-fatal post-settle hook failed); retrying would settle TWICE
- **A 5xx whose body states `"retryable": false`** — the facilitator saying so outright

### Idempotency-Key: one purchase binding per payment (on by default since 0.89.0)

```python
from uvd_x402_sdk import new_idempotency_key

# Nothing to do for the common case: every process_payment() call carries one
# fresh random key on its /verify, its /settle and the settle's timeout fallback.
result = client.process_payment(x_payment_header, Decimal("0.10"))
result.idempotent_replayed   # True: the facilitator's replay of THIS purchase's settle

# To resume a payment after a restart, create the key first and store it with the order.
order.idempotency_key = new_idempotency_key()   # "x402-<64 hex>", merchant-private
save(order)
result = client.process_payment(x_payment_header, Decimal("0.10"),
                                idempotency_key=order.idempotency_key)
```

`verify_payment()`, `settle_payment()`, `try_settle_payment()` and `process_payment()` send an
`Idempotency-Key` on every call. One handling of a payment (a `process_payment()` call, or a
`settle_payment()` call with its retries and timeout fallback) carries **one** key on every request
it makes. The key is random unless the call brings its own: `idempotency_key` (a key the seller
created with `new_idempotency_key()` and stored with the order) or `idempotency_scope` (a key
derived from the payment and a secret order id, see below). `VerifyResponse`, `SettleResponse` and
`PaymentResult` report the key in `idempotency_key`; it stays out of `model_dump()`, so it never
reaches the buyer in `PAYMENT-RESPONSE`.

- **Why random.** A facilitator with durable receipts (x402-rs 2.39.0, Arc and native Hedera today)
  hands an admitted payment's answer back only to the binding that admitted it: the same
  `Idempotency-Key` or the same `X-UVD-Purchase`. Possession of the signed payment alone is not a
  binding. A key derived from the `X-PAYMENT` is recomputed by whoever holds the payment, so a buyer
  resending their own `X-PAYMENT` in a new request would make the seller send the same key and get
  the original settle back. A random key per handling cannot be recomputed.
- **Why the same key on verify and settle.** The rail binds only the key that admitted the payment.
  0.83.0 to 0.88.0 sent `x402-verify-…` on `/verify`, so the `/verify` of a retried purchase read
  `authorization_already_settled` for a payment that had settled.
- **A replay nobody on this request admitted is refused.** A handling with no binding of its own (a
  fresh key, no `X-UVD-Purchase`) that receives `Idempotent-Replayed: true` before any of its own
  attempts could have admitted the payment raises `PaymentSettlementError` with reason
  `authorization_already_settled` (or `authorization_in_flight` for a `202`), carrying the receipt.
  Facilitators before 2.39.0 did not tie the replay to the binding; 2.39.0 answers `409` itself. The replay the handling's own fallback or retry receives is its own, and is
  returned with `idempotent_replayed=True`.
- **`idempotency_scope`** is kept: `derive_idempotency_key(payload, "settle", scope=...)` is
  `x402-settle-<sha256>` over `["x402-idempotency-scope/1", <signed block>, <scope>]`, the value
  0.83.1 to 0.88.0 sent, now on `/verify` too. **It is a binding only while the scope is a secret
  of the seller** (an order id the seller generates, which the buyer does not know and cannot
  guess). A scope taken from the request, or a sequential one, gives the key to whoever holds the
  payment. `idempotency_key` and `idempotency_scope` at once raise `ValueError`; a malformed key
  (not 1-255 visible ASCII characters, or starting with `receipt:`) raises before anything is sent.
- **Off switch: `send_idempotency_key=False`** sends no key at all, as 0.83.1 to 0.88.0 did by
  default. Then a settle that timed out after being admitted gets `409 authorization_already_settled`
  on its fallback: probably the seller's own payment, but nothing proves it. The SDK raises the
  facilitator's `FacilitatorError` with the receipt; reconcile `receipt.settlement` with your own
  records before delivering anything.

What the facilitator does with the key:

| Request | Without receipts (x402-rs 2.28.0 `post_settle`) | With receipts (x402-rs 2.39.0) |
|---|---|---|
| same key, same request, payment settled | cached `200`, `Idempotent-Replayed: true` | original `200`, `Idempotent-Replayed: true` |
| same key, payment in flight | executes again (no lock on the key) | `202 settlement_in_progress`: transient, same request later |
| no key or another key, payment settled | executes again; EVM answers an opaque `400 contract_call_failed` | `409 authorization_already_settled`; `/verify`: `isValid: false` |
| no key or another key, payment in flight | executes again | `409 authorization_in_flight`; `/verify`: `isValid: false` |
| same authorization, other terms or another purchase context | `409 idempotency_key_conflict` (same key) | `409 receipt_request_conflict` |
| the facilitator cannot read its store | `503 idempotency_store_unavailable`, **no settle** | `503 receipt_store_unavailable`, no verdict |
| `/verify` | header ignored | stored verdict for the binding |

- **With the key on, the idempotency store is a dependency on networks without receipts.** A keyed
  settle the facilitator cannot check is `503 idempotency_store_unavailable` and does not execute
  (without a key it used to settle): `is_transient_error()` reads it as transient, so answer 503 +
  `Retry-After` and let the buyer present the same credential again.
- **A settle that outlives its timeout is awaited.** The fallback's resend under the handling's own
  key can get `202 settlement_in_progress`: the payment was admitted and is moving. The fallback asks
  again for up to `SETTLE_IN_FLIGHT_POLL_SECONDS` (30), and the same request ends in its settle.
  Past that it raises the `202` itself (transient, with the pending receipt), never a timeout.
- **What it does not catch:** a buyer who signs a *new* authorization for the same purchase. That is
  another payment.

`admitted_authorization_code(exc)` names the receipt rail's three refusals, and
`payment_conflict_response(exc)` builds the answer. The SDK's middlewares and decorators (FastAPI,
Flask, Django, Lambda, `require_payment`) use it, never deliver on these refusals, and never answer
them with 402:

| Code | Meaning | Answer |
|---|---|---|
| `authorization_already_settled` | this `X-PAYMENT` was already used, and the payment is confirmed | `409` |
| `receipt_request_conflict` | admitted for another purchase context, or under other terms | `409` |
| `authorization_in_flight` | admitted for another request, outcome not final | `503` + `Retry-After`, `retryable: true` |

The same integrations answer every failure without a verdict with `503` + `Retry-After` and the
facilitator's `reason`: a timeout, a settle still in flight (`settlement_in_progress`), `503
idempotency_store_unavailable` or `receipt_store_unavailable`, another retryable `5xx`, a `429`. The
buyer presents the same `X-PAYMENT` later and never signs another one.

Two more answers are never a `402` either, because the payment may have moved:

| Facilitator answer | Answer | Body |
|---|---|---|
| `502 settlement_unconfirmed`, or any other failure whose body names a `transaction` | `500` | `transaction`, `paymentId`, `reason`, `retryable: false` |
| another `5xx` with `retryable: false` | `500` | `reason`, `retryable: false` |
| a `4xx` from `/settle` after `/verify` accepted the same payload (`400 contract_call_failed (ref: …)`, `400 internal_error (ref: …)`), unless it refused the request before running anything | `500` | `reason`, `retryable: false` |
| `/settle` `200 success: false` that names a `transaction` (mined and reverted) | `500` | `transaction`, `reason`, `retryable: false` |
| an authorization already used (`is_spent_nonce_error`), transient or not | `409` | `spentNonceEvidence`, the code as `reason` when there is one, `retryable: false` |

`500` is the TypeScript SDK's answer to `settlement_unconfirmed`: the transaction was broadcast and
may be mined, so the buyer must not sign again, and a `503` + `Retry-After` would invite a resend.
The body tells the buyer not to sign another payment and to check the transaction first. The
receipt, when there is one, travels in `PAYMENT-RESPONSE`. The SDK still re-sends none of these.
A `202 settlement_in_progress` stays `503`: re-sending it under its binding is the recovery.

A settle runs only after `/verify` accepted the same payload and signature, so an opaque `4xx` from
the settle is not a bad signature: something changed between the two calls, most likely the
authorization being used. The TypeScript SDK answers every settle failure it may not retry with
`500`. The settle `4xx`s that stay a rejection are the ones the facilitator sends before it runs
anything: `403`, `Invalid request` and the other parse failures, `invalid_address`, `clock_error`,
`reserved_idempotency_key`, `invalid_receipt_context` and `receipt_*`.

What still reaches `402` (`400` in `require_payment`):

- **The opaque `400` tokens on `/verify`.** x402-rs reports a used authorization without naming it:
  on EVM as `contract_call_failed (ref: …)`, the same answer as an invalid signature, and on
  Stellar, Algorand, NEAR and Sui as `internal_error (ref: …)`, the same answer as their invalid
  signatures and other internal errors. On `/verify` nothing tells them apart. On networks with
  receipts the facilitator names it (`authorization_already_settled`, `409`).
- **The facilitator's verdicts.** On `/verify` or on the settle's re-validation (`200 {"isValid":
  false, "invalidReason"}`), and a `/settle` `200 success: false` without a transaction. A settle
  re-validation that finds `insufficient_funds` right after a valid verify may mean the balance
  moved in between. It stays a rejection.
- **The settle-request refusals listed above.**

The receipt travels in `PAYMENT-RESPONSE` when the facilitator sent one. Only the FastAPI
integration forwards the buyer's `X-UVD-Purchase`; with it, a resumed purchase gets its original
answer and is delivered.

### Persisting the binding across instances (`BindingStore`)

A fresh key per request dies with the process that minted it. If a Lambda dies after the
facilitator settled and before it delivers, the buyer's resend of the same `X-PAYMENT` reaches
another instance with another key, and the receipt rail answers it `409
authorization_already_settled`: paid, not delivered. A `BindingStore` writes one row per payment
**before** the facilitator is called: the resource the payment belongs to and a random key. The
resend, in any instance, carries that key and gets the original settle back: delivered once,
charged once.

```python
import boto3
from botocore.config import Config
from uvd_x402_sdk import DynamoDBBindingStore, PostgresBindingStore
from uvd_x402_sdk.integrations import FastAPIX402, LambdaX402

dynamodb = boto3.client("dynamodb", config=Config(connect_timeout=1, read_timeout=1,
                                                  retries={"max_attempts": 2}))
x402 = LambdaX402(config=config, binding_store=DynamoDBBindingStore(dynamodb))

# or, with the app's psycopg 3 pool:
x402 = FastAPIX402(app, config=config, binding_store=PostgresBindingStore(pool))
```

`X402Depends`, `fastapi_require_payment`, `X402Middleware` and `lambda_handler` take the same
`binding_store=`. Without it, nothing changes.

- **Stores.** `InMemoryBindingStore` (one process only), `PostgresBindingStore(pool)` (a pool not
  in autocommit; the table is `uvd_x402_sdk.bindings.POSTGRES_BINDINGS_SCHEMA`: apply it in your
  migrations before deploying the code, or every paid request answers 503),
  `DynamoDBBindingStore(client)` (hash key `payment_key`, a string:
  `DYNAMODB_BINDINGS_KEY_SCHEMA`; no TTL on `expires_at`).
- **What is bought.** The request's method, path, query and a sha256 of its body, read from what
  the app routes on (FastAPI: the ASGI scope, never `request.url`). The same `X-PAYMENT` for
  another resource or another body is `409 payment_already_used`, and the facilitator is not
  called. Headers are not part of it: see the window below.
- **Fail closed.** A store that cannot answer is `503 payment_store_unavailable` + `Retry-After`,
  and the facilitator is not called: never a charge whose key was not stored.
- **Never a 402 over a payment seen before.** A payment this seller had already seen that the
  facilitator then refuses is `409 payment_presented_before`: the earlier attempt may have moved
  it. That is what the resend gets on a network without receipts whose `/verify` simulates the
  transfer (EVM), where it cannot be recovered.
- **The window.** For `binding_window_seconds(config)` (300 s with the defaults, at most 1800 s) the
  same `X-PAYMENT` for the same resource is the same purchase: delivered again from the
  facilitator's replay, not charged again. **Your route runs again**, with
  `payment.idempotent_replayed` true: check it if the route has side effects, or if its answer
  depends on the caller (`Authorization`, cookies), because whoever resends the same request with
  the same `X-PAYMENT` gets it. After the window the key is renewed and the facilitator answers
  `409` with the receipt.
- **`X402Middleware` needs Starlette 0.28 or later with a store** (it reads the body for the
  resource, and on 0.27 the route cannot read it again). It raises `ValueError` otherwise; the
  dependency and the decorator work on 0.27.
- **Your own handler.** `process_payment_bound(client, store, x_payment_header, amount, resource)`
  runs the same rule and raises `PaymentBindingError`, whose `reason` is one of the three codes
  above (`503` for the first, `409` for the other two).

### Spent nonce: never answer 402 over a payment that may have moved

`is_spent_nonce_error(exc)` says whether a failure means the authorization was **already
used**; `spent_nonce_evidence(exc)` also says how it knows: `"structured"` for a code
(`nonce_already_used`, `alreadySettled`, `idempotency_key_conflict`, …, normalised, anywhere in
the details or the facilitator's JSON body) or `"wording"` for free text. The wording match is
tarotof's substring match (it reads `NonceAlreadyUsed` and `NonceReused { .. }` inside prose and
structs) minus two measured words that contain "used" without meaning it: `refused` and `unused`.
It leans to the false positive on purpose: "check, you may have paid already" costs a lookup.
A 402 tells the buyer to sign again, so check in this order (the SDK's middlewares and
decorators do exactly this):

```python
from uvd_x402_sdk import (is_spent_nonce_error, is_transient_error,
                          payment_conflict_response, transient_503_response)

def answer(exc):
    if (conflict := payment_conflict_response(exc)) is not None:
        return conflict                       # 409, or 503 in flight: used by another request
    transient = is_transient_error(exc)
    if (getattr(exc, "transaction", None) or getattr(exc, "tx_hash", None)) and not transient:
        return may_have_settled(exc)          # 500, broadcast: check the chain
    if is_spent_nonce_error(exc):
        return already_used(exc)              # 409, already used: do NOT sign again
    if transient:
        return transient_503_response(exc)    # 503, no verdict: same credential, later
    status = getattr(exc, "status_code", None) or 0
    if status >= 500:
        return may_have_settled(exc)          # 500, the facilitator said not to retry
    if getattr(exc, "operation", None) == "settle" and 400 <= status < 500 \
            and not refused_before_running(exc):
        return may_have_settled(exc)          # 500, the settle failed after a valid verify
    return payment_rejected(exc)              # 402
```

`exc.operation` is `"verify"` or `"settle"` on a `FacilitatorError` the client raised from that
call. `refused_before_running` is the list above (`403`, the parse failures, `invalid_address`,
`clock_error`, `reserved_idempotency_key`, `invalid_receipt_context`, `receipt_*`).

### When the facilitator refuses a retry, it says where to look

```python
try:
    client.settle_payment(payload, Decimal("0.10"), retry=True)
except FacilitatorError as exc:
    if not exc.retryable:
        # 502 {"error":"settlement_unconfirmed","transaction":"0x…","paymentId":"0x…"}
        # The tx MAY be mined. Check the chain — never re-send.
        log.error("settle unconfirmed: tx=%s payment=%s code=%s",
                  exc.transaction, exc.payment_id, exc.error_code)
```

`FacilitatorError` carries `transaction`, `payment_id` and `error_code` (all `None` when
the facilitator sent none), and repeats them in `to_dict()["details"]` as `transaction` /
`paymentId` / `errorCode` — so they reach the buyer through `transient_503_response()`
without a paywall having to know about them. The hash is passed through **verbatim**:
Algorand prints base32 and Solana base58, and pasting it into an explorer is the whole
remedy on offer.

`exc.retryable` is the verdict: **the status is the ceiling and the body can only lower
it**, never raise it. A body claiming `retryable: true` on a `400` will not make the SDK
re-send a credential the facilitator genuinely rejected.

`exc.safe_to_retry` answers the question x402-rs answers per failure in its
`docs/settle-errors.md`: was anything sent?

| `safe_to_retry` | When | What to do |
|---|---|---|
| `True` | a `5xx` with `safeToRetry: true` (the receipt rail), or a writer-lease `reason` in `WRITE_NOT_ATTEMPTED_REASONS` | resend the same request, same `Idempotency-Key` |
| `False` | `retryable: false`, a `transaction`, a receipt `pending` / `unknown`, an `error` in `SETTLE_MAY_HAVE_SENT_ERRORS` (`settlement_unconfirmed`, `broadcast_uncertain`, `receipt_pending`, `receipt_response_unreadable`, `idempotency_cache_corrupt`), a `reason` in `WRITE_AMBIGUOUS_REASONS` (`forward_unconfirmed`, `forward_failed`), `202 settlement_in_progress`, an admitted authorization's `409` | the payment may be on chain: look it up, never sign again |
| `None` | anything else: a refusal, no answer at all, `upstream_rpc_unavailable`, `upstream_nonce_or_mempool`, `upstream_rate_limited`, `facilitator_signer_unfunded` | the facilitator did not say; `retryable` still says whether it is transient |

`forward_failed` and the four tokens of the last row mean "nothing was sent" from x402-rs
2.39.6 on. Up to 2.39.5 the same answers, with the same status and `Retry-After`, also covered
a transaction whose send answer was lost, and nothing in the answer says which version sent
it. `safe_to_retry` never licenses signing a new authorization: resending the same one cannot
move the money twice, because the token's own nonce stops it.

### What a failed settle or verify carries

```python
try:
    client.settle_payment(payload, Decimal("0.10"))
except PaymentSettlementError as exc:
    exc.status_code     # 200 for success: false or a failed re-validation
    exc.error_reason    # the facilitator's errorReason (invalidReason on a re-validation)
    exc.response_body   # its body, at most MAX_ERROR_BODY_BYTES (4096 bytes)
```

`PaymentVerificationError` carries the same three (`error_reason` is `/verify`'s
`invalidReason`). The message, `reason` and `to_dict()` are what they were, so nothing new
reaches the buyer.

### Non-raising settle

```python
result = client.try_settle_payment(payload, Decimal("0.10"), retry=True)
# {"success": True, "tx_hash": "0x...", "payment_id": None, "error_code": None, "error": None,
#  "proof_of_payment": None, "safe_to_retry": None}
```

Same arguments as `settle_payment()`, but payment-flow errors come back as data instead of
exceptions. **`success=False` with `tx_hash` set is the double-settle warning shape**: the
facilitator returned an error status AFTER broadcasting — verify on-chain, do not re-send.
`payment_id`, `error_code` and `safe_to_retry` (`FacilitatorError.safe_to_retry`) come back
alongside it. On success, `proof_of_payment` is the facilitator's proof as its own camelCase
dict when `extra` asked for one. Every key is always present (`None` when it does not apply),
so reading one never depends on whether the settle worked.

---

---

## Purchase policy — what this buyer may sign (`PurchasePolicy`)

A catalog listing is a claim somebody else made about their own price. The `402`
that comes back from the actual request is the **offer**. They can differ,
legitimately: the seller may have repriced. So the buying decision is made
against **the offer in hand**, every time, **before anything is signed** —
`X402Client.fetch()` evaluates the policy between reading the 402 and producing
the `X-PAYMENT` header.

This is the same contract the facilitator fixed in its P3 phase (`x402-rs`
2.25.0, `crates/x402-reqwest/src/policy.rs`) and the TypeScript SDK implements,
so a refusal code means the same thing in all three.

```python
from uvd_x402_sdk import PurchasePolicy, TokenAsset, X402Client, PolicyRefusedError

USDC_BASE = TokenAsset("base", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")

policy = PurchasePolicy(
    per_payment={USDC_BASE: 50_000},      # 0.05 USDC in any ONE payment
    cumulative={USDC_BASE: 5_000_000},    # 5 USDC total while this policy lives
    only_pay=["0xe4dc963c56979E0260fc146b87eE24F18220e545"],
)

client = X402Client(recipient_address="0xMerchant...", policy=policy)
client.connect_with_private_key(key, chain_name="base")

try:
    resp = client.fetch("https://api.example.com/data")
except PolicyRefusedError as e:
    print(e.refusal_code)   # one of the six codes below
    print(e.details)        # the numbers that caused it

# Evaluating did NOT spend. Record it once the settlement resolved:
policy.record_spend(USDC_BASE, 50_000)
```

### Fields

| field | type | meaning |
|---|---|---|
| `per_payment[asset]` | int, atomic units | most this policy will pay in ONE payment of that asset |
| `cumulative[asset]` | int, atomic units | most it will pay in that asset in total, while the policy lives |
| `spent[asset]` | int | what `record_spend()` has registered; **only `record_spend` moves it** |
| `only_pay[]` | addresses | permitted recipients, canonicalised **by family** (see rule 4c) |
| `allow_unlisted_assets` | bool, **false by default** | whether an asset with no declared ceiling may be paid at all |

`asset` is a `TokenAsset(network, address)` — the network is part of the key,
because USDC on Base and USDC on Polygon are different money to a spending
limit. A `(network, address)` tuple or a `{"network", "asset"}` dict works too.
Amounts are integers in the asset's own base units; nothing is ever compared in
decimals, because decimals come from a field the seller supplied.

**One chain, one key.** `base` and `eip155:8453` are the same chain under two
dialects — v1 uses the name, v2 the CAIP-2 id, and the same seller can answer
either — so both resolve to the SDK's canonical name (aliases like `skale` too).
A policy written in one dialect covers an offer priced in the other; without
that, a v2 challenge would be refused with `asset-not-budgeted`, a cause that is
not true and one the Rust and TypeScript buyers do not produce. Different
*chains* stay different keys, and a dialect the registry cannot resolve falls
back to the literal — which no budget holds, so the answer is a refusal.

### Order of evaluation (fixed — the FIRST failing check is the one reported)

```
no-readable-offer -> offer-expired -> recipient-not-permitted
                  -> asset-not-budgeted -> per-payment-limit -> cumulative-limit
```

`asset-not-budgeted` runs **before** the ceilings on purpose: the ceilings are a
map, and a map has no opinion about a key it does not hold — which is precisely
how an unlisted token would sail past a budget that looks complete. The caller
needs to hear "budget that asset", not "raise a ceiling that does not exist".

### Codes

Closed vocabulary, in kebab, so a caller can branch without parsing English.
Every one carries the numbers that caused it (`requested`, `allowed`, `spent`,
`wouldTotal`, `asset`, `payTo`, `validUntil`, `now`, `offered[]`) on
`PolicyRefusal.to_dict()` and on `PolicyRefusedError.details`:

| code | meaning |
|---|---|
| `no-readable-offer` | the challenge carried offers and none is one this build can pay; names the schemes offered |
| `offer-expired` | the seller's own `validUntil` has passed |
| `recipient-not-permitted` | `payTo` is not on `only_pay` |
| `asset-not-budgeted` | no ceiling was ever declared for that asset |
| `per-payment-limit` | one payment is over the per-payment ceiling |
| `cumulative-limit` | it would take total spend past the cumulative ceiling |

### Comparison against a listing — reported, never decisive

`fetch(..., quote=AdvertisedQuote(asset=USDC_BASE, amount=10_000))` compares the
offer against what a catalog advertised and reports one of `not-compared` |
`matches` | `amount-differs` | `different-asset`. **It never refuses anything.**
An offer that costs more than the listing but sits inside a policy the operator
already authorised is paid: stopping to ask would turn every ordinary reprice
into a halt, and an agent that halts on ordinary commerce is an agent nobody can
leave running. There is no human-confirmation hook on this path.

### The rules, numbered as the contract numbers them

1. **Evaluating does not spend.** Signing can fail and a settlement can be
   refused; a limit that counted attempts would lock a caller out of money it
   never spent. `record_spend()` is a separate call, after the settlement
   resolved.
2. **A policy is never widened from inside an evaluation.** There is no setter,
   no builder that raises a limit, and the mappings handed out are read-only
   views. Widening means constructing a new policy — a visible act in your code.
3. **No human confirmation when the policy already covers the operation.**
4. **A different asset is not the same price.** Numbers are never compared
   across assets.
   - **4b. An asset with no ceiling is denied by default.** A budget in USDC is
     not a budget in any other token, and the signer takes its EIP-712 domain
     from the seller's own `extra` — it will sign for a token it has never heard
     of. The permissive mode is asked for by name: `PurchasePolicy.permissive()`.
   - **4c. Addresses are canonicalised by family, not with `lower()`.** Hex is
     folded; base58 (Solana, XRPL) is compared exactly. Folding base58 refuses
     legitimate payments and, worse, can admit an address nobody put on the list.
5. **`validUntil` comes from the seller**, read from
   `extensions["offer-receipt/1"].info.validUntil`, in Unix seconds. Absent = no
   declared validity. Unreadable = absent, **never zero** — "the seller said
   something we could not read" must not become "this offer expired in 1970",
   which would refuse every payment to that seller.
6. **`validUntil == now` still stands.** It is the last instant the offer is in
   force.
7. **One unreadable offer does not take the list with it.** A seller advertising
   `exact` beside a scheme this build does not implement stays payable; the
   unreadable ones are counted by scheme name, so a refusal can say what the
   seller actually offered (`no-readable-offer`, with `offered[]`). **`scheme`
   is required and its vocabulary is closed** (`exact`, `upto`, `escrow`,
   `commerce`, `fhe-transfer`) — a payment we cannot name is a payment we cannot
   make, and an entry without one is unreadable, exactly as in the facilitator.

### Copies share the purse

A client is copied per request. `copy.copy()` and `copy.deepcopy()` of a policy
both spend from the **same** running total — if each copy carried its own, a
cumulative limit would mean nothing. And if that total cannot be read (a held
lock, a corrupt value), `spent()` reports the **ceiling**, not zero: for money
the safe direction is to refuse, never to permit.

### Without a policy, nothing changes

`X402Client` holds `PurchasePolicy.permissive()` when the caller supplied none,
so code written before 0.82.0 pays exactly what it paid before. The asymmetry is
deliberate: whoever sits down to WRITE a policy gets the safe default.

## Error Handling

```python
from uvd_x402_sdk.exceptions import (
    X402Error,
    PaymentRequiredError,
    PaymentVerificationError,
    PaymentSettlementError,
    UnsupportedNetworkError,
    InvalidPayloadError,
    FacilitatorError,
    X402TimeoutError,
)

try:
    result = client.process_payment(header, amount)
except PaymentVerificationError as e:
    # Signature invalid, amount mismatch, expired, etc.
    print(f"Verification failed: {e.reason}")
    print(f"Errors: {e.errors}")
except PaymentSettlementError as e:
    # On-chain settlement failed (insufficient balance, nonce used, etc.)
    print(f"Settlement failed on {e.network}: {e.message}")
except UnsupportedNetworkError as e:
    # Network not recognized or disabled
    print(f"Network {e.network} not supported")
    print(f"Supported: {e.supported_networks}")
except InvalidPayloadError as e:
    # Malformed X-PAYMENT header
    print(f"Invalid payload: {e.message}")
except FacilitatorError as e:
    # Facilitator returned error
    print(f"Facilitator error: {e.status_code} - {e.response_body}")
except X402TimeoutError as e:
    # Request timed out
    print(f"{e.operation} timed out after {e.timeout_seconds}s")
except X402Error as e:
    # Catch-all for x402 errors
    print(f"Payment error: {e.message}")
```

---

## ERC-8004 Trustless Agents

Build verifiable on-chain reputation for AI agents and services. Supports **25 networks** (23 EVM + Solana + Solana devnet).

Arc (`arc`, `arc-testnet`) since 0.90.0, with the canonical registries on both; see
[ERC-8004 on Arc](docs/networks/arc.md#erc-8004-on-arc-0900).

Robinhood Chain (`robinhood`, chain 4663, and `robinhood-testnet`, chain 46630) since
0.110.0, with the singleton identity, reputation and validation registries on both. It
needs a facilitator that serves ERC-8004 there (x402-rs 2.55.0 did not yet). Neither network
is on the relayed rail. The escrow pre-auth signs on `robinhood` since 0.111.0 (USDG; see
the escrow pre-auth section); `robinhood-testnet` has no escrow.

Every EVM network also takes its CAIP-2 name (`eip155:8453`, `eip155:4663`, ...), the form v2
payment requirements carry: `get_contracts()` / `is_available()` resolve it, and every read
and write sends the plain name, which is the only one the facilitator parses. Exact strings
only (`EIP155:8453` or `eip155:0x2105` are not Base).

> Name Base as `"base"`. The old `"base-mainnet"` spelling is rejected by the facilitator
> (`400 Invalid network`); the SDK now rewrites it for you, but new code should use `"base"`.

The writes (`submit_feedback`, the relayed and Solana `prepare_*` / `submit_*`, `revoke_feedback`, `append_response`, `register_agent`) answer an HTTP error without raising, except `register_agent(use_async_transport=True)`, which raises `httpx.HTTPStatusError` as before (and `RegistrationPendingError` when the wait times out). Otherwise they answer `success=False` with `error="Facilitator error: <status> - <body>"`, plus `status_code` (the HTTP status) and `retry_after` (the `Retry-After` in seconds, from seconds or an HTTP-date, not clamped; `None` when absent or unreadable). Both are `None` on success and when no answer came back.

On EVM networks, agent IDs are sequential `uint256` integers. On Solana, agent IDs are base58 pubkey strings (NFT asset addresses). The `AgentId` type (`Union[int, str]`) handles both.

```python
from uvd_x402_sdk import Erc8004Client, AgentId

async with Erc8004Client() as client:
    # EVM: agent_id is an integer
    identity = await client.get_identity("ethereum", 42)
    print(f"Agent URI: {identity.agent_uri}")

    # Solana: agent_id is a base58 pubkey string
    identity = await client.get_identity("solana", "8oo4dC4JvBLwy5...")
    print(f"Agent URI: {identity.agent_uri}")

    # Get agent reputation
    reputation = await client.get_reputation("ethereum", 42)
    print(f"Score: {reputation.summary.summary_value}")

    # Submit feedback after payment
    result = await client.submit_feedback(
        network="ethereum",
        agent_id=42,
        value=95,
        tag1="quality",
        proof=settle_response.proof_of_payment,
    )

    # Respond to feedback (agents only)
    # seal_hash is required for Solana, optional for EVM
    await client.append_response(
        network="ethereum",
        agent_id=42,
        feedback_index=1,
        response_text="Thank you for your feedback!",
    )
```

### Ratings the chain attributes to the rater

`submit_feedback()` above works, but the registry records `msg.sender` as the
author -- and on that route `msg.sender` is the **facilitator**. It is why 87,2%
of the reputation on Base (1.384 of 1.587 feedbacks) is attributed to one
wallet, which can also revoke it.

EIP-7702 fixes it without touching the registry: the rater delegates their own
EOA to a `FeedbackDelegate`, and the transaction is sent **to the rater's
address**, so the registry sees the rater while the facilitator still pays the
gas.

```python
from uvd_x402_sdk import (
    Erc8004Client,
    RelayAuthorizationParams,
    supports_relayed_feedback,
)

async with Erc8004Client() as client:
    if not supports_relayed_feedback("base"):
        ...  # fall back to submit_feedback(); the facilitator is the author

    prep = await client.prepare_relayed_feedback(
        network="base",
        agent_id=18896,
        rater=rater_address,     # who the chain will record as the author
        value=95,
        tag1="quality",
    )

    # 1. Sign with the RATER's key. WHICH value you sign depends on HOW you
    #    sign it -- get this wrong and you produce a well-formed signature that
    #    authorises nobody, and the only symptom is `relay_bad_signature`.
    #
    #    `prep.digest` already carries the EIP-191 envelope. A raw key signs it
    #    as a prehash; a wallet's personal_sign would add the envelope a SECOND
    #    time, so wallets sign `prep.signing_payload` instead.
    from eth_account import Account

    signature = Account.unsafe_sign_hash(prep.digest, rater_key).signature.hex()
    # ...or, from a browser/mobile wallet:
    #   signature = await wallet.personal_sign(prep.signing_payload)

    # 2. Only the first time this rater rates: point their EOA at the delegate.
    authorization = None
    if not prep.delegated:
        authorization = RelayAuthorizationParams(
            chainId=prep.chain_id,       # 0 is EIP-7702's wildcard: every chain
            address=prep.delegate,
            nonce=prep.account_nonce,
            **sign_authorization(prep.chain_id, prep.delegate, prep.account_nonce),
        )

    result = await client.submit_relayed_feedback(
        network="base",
        agent_id=18896,
        rater=rater_address,
        value=95,
        tag1="quality",
        deadline=prep.deadline,          # short by design; past it, refused
        nonce=prep.nonce,
        signature=signature,
        authorization=authorization,
    )
```

Pass the **same** feedback parameters, `deadline` and `nonce` back to
`submit_relayed_feedback()`. They are not redundant: the facilitator rebuilds
the registry calldata from them and refuses to relay anything the rater's
signature does not cover.

Available on the ten networks in `RELAYED_FEEDBACK_NETWORKS` -- the nine
mainnets with a deployed `FeedbackDelegate` (base, ethereum, polygon, arbitrum,
optimism, celo, bsc, monad, arc) plus base-sepolia. **Avalanche is not one of them
and is not waiting to become one**: its C-Chain rejects the transaction type
itself (`-32000 transaction type not supported`), so anchor the rating on a
chain that supports EIP-7702 -- the payment stays where it was made.
`arc-testnet` serves ERC-8004 reads but not this rail: no delegate is deployed
there, and `prepare` answers 400.

Requires facilitator v1.93.0+ for the mainnets (2.38.0+ for arc); base-sepolia since v1.74.0.

### The whole rail in one module: `uvd_x402_sdk.reputation` (0.101.0)

The example above signs `prep.digest` as the facilitator sent it. A program
that rates people on its own should not: a compromised or misrouted facilitator
can hand back a digest that is an EIP-7702 delegation of the rater's account to
someone else, or a typed-data Permit. `pip install "uvd-x402-sdk[reputation]"`
brings the implementation Karma Hello runs in production, extracted so every
product uses one: `validate_preparation` (rebuilds the typed data and the
digest, delegate allowlist per chain), `sign_relayed_feedback` /
`build_relay_authorization` (low-s, recovered against the rater before they
leave), `pay_and_prove` (the anchor payment and its chain-built proof), a
persisted outbox that never prepares the same rating twice, a `Governor` with
caps and a circuit breaker, and public evidence without the chat text or its
author. See
[`src/uvd_x402_sdk/reputation/README.md`](src/uvd_x402_sdk/reputation/README.md)
for a program wired in fifteen lines.

### The rated party's Solana identity, minted once: `ensure_solana_identity` (0.102.0)

A rating on Solana needs the rated party to own an 8004-solana identity. The
facilitator mints it, pays its rent (about 0.0134 SOL) and hands it to a base58
recipient; `uvd_x402_sdk.reputation.ensure_solana_identity` is the one client
of that, for every product (no extra needed):

```python
from uvd_x402_sdk.erc8004 import Erc8004Client
from uvd_x402_sdk.reputation import InMemoryMintBudget, ensure_solana_identity

BUDGET = InMemoryMintBudget()  # one long-lived process; several processes: a shared, persistent store

async with Erc8004Client() as client:
    result = await ensure_solana_identity(
        owner_base58,                                  # an address the owner PROVED they hold
        client=client,
        budget=BUDGET,
        agent_uri=f"https://my-app.example/agents/{owner_base58}",  # the same URI every time
    )
    if result.has_identity:                            # "created" or "already_exists"
        agent_id = result.agent_id
```

It reads the identity on Solana before every mint request, a retry's too
(`check_solana_identity`, the facilitator's owner lookup), and never mints over
an answer that is not a verdict; mints at most 25 identities a UTC day per network
(`SOLANA_IDENTITY_DAILY_MINT_CAP`; a caller may ask for less, never more), 3
requests per address in 24 hours, one per address at a time, and none for 30
minutes after a request whose outcome is unknown; and gives back a slot only
when the facilitator's answer proves nothing reached the chain. The budget is
the caller's and has no default: an implicit per-process counter would make the
cap per worker and forget its holds on a restart. The result is one of
`created`, `already_exists`, `pending`, `quota_exceeded`, `unavailable`,
`uncertain`, `refused`, with a stable `reason`. Details in the module README.

### The same thing on Solana, and it needs no delegate

Solana has the identical defect and a shorter fix. Account 0 of the program's
`give_feedback` instruction is already declared `[signer, writable] client
(feedback author / fee payer)`, and `POST /feedback` puts the **facilitator's**
keypair there. Since Solana takes several signers per transaction natively, the
rater can simply sign as `client` while the facilitator stays the fee payer --
no delegation, no contract in between.

Which is why this is a **sibling rail**, not one more network on
`RELAYED_FEEDBACK_NETWORKS`: that set means "a `FeedbackDelegate` is deployed
here", and `prepare_relayed_feedback()` builds the **EVM** URL
`/feedback/evm/prepare` out of it. Solana routes through `SOLANA_FEEDBACK_NETWORKS` and
`/feedback/solana/*` instead.

```bash
pip install uvd-x402-sdk[solana]   # ed25519 signing; no RPC client, no web3
```

```python
import os

from uvd_x402_sdk import (
    Ed25519Signer,
    Erc8004Client,
    sign_solana_feedback_transaction,
    supports_solana_feedback,
)

signer = Ed25519Signer(os.environ["RATER_SECRET_KEY"])  # 32/64 bytes or base58

async with Erc8004Client() as client:
    if not supports_solana_feedback("solana"):
        ...  # fall back to submit_feedback(); the facilitator is the author

    # 1. Ask for the transaction. Free, writes nothing, and the `client`
    #    account it builds is the RATER.
    prep = await client.prepare_solana_feedback(
        network="solana",
        agent_id="247Y4QLwz9ZbcuHR2nX2EQLZHCsMs1GTqvgd6fpdn85Q",  # asset pubkey
        rater=signer.pubkey,
        value=87,
        score=95,          # without it the ATOM Engine records but scores nothing
        tag1="quality",
    )

    # 2. Sign it. The message is carried through byte for byte -- the
    #    facilitator rebuilds it and refuses anything that is not identical.
    signed = sign_solana_feedback_transaction(prep.transaction, signer.pubkey, signer)

    # 3. Send it back with the SAME feedback parameters. The facilitator
    #    verifies the rater's signature, then adds its own and pays the fee.
    result = await client.submit_solana_feedback(
        network="solana",
        agent_id="247Y4QLwz9ZbcuHR2nX2EQLZHCsMs1GTqvgd6fpdn85Q",
        rater=signer.pubkey,
        value=87,
        score=95,
        tag1="quality",
        transaction=signed,
    )
```

The fee payer's signature slot is left empty on purpose: that one is the
facilitator's, and it fills it only after the rater's has verified -- so a
transaction the network would reject never costs a fee.

`prepare` pins the transaction to a recent blockhash, and Solana blockhashes
expire in about a minute of slots. Prepare when the rater is ready to sign,
not before -- and once `lastValidBlockHeight` is past, **call `prepare` again**.
The window is retryable, the signed transaction is not replayable: the
blockhash lives inside the message, so a new one has to be signed.

`Ed25519Signer` is a convenience, not a requirement: anything with a base58
`pubkey` and a `sign_message(bytes) -> bytes` satisfies `SolanaSigner`, so a
browser wallet, a custodian or an HSM plugs in unchanged.

Available on `solana` and `solana-devnet`. Requires facilitator **v1.74.0+**
(the release that first served both routes); measured live on **v2.16.0**.

## Server-Side Signing

Create signed EIP-3009 payment headers from your backend without a browser wallet. Useful for server-to-server x402 payments, automated agents, and testing.

```bash
pip install uvd-x402-sdk[signer]
```

```python
from decimal import Decimal
from uvd_x402_sdk import X402Client

client = X402Client(recipient_address="0xMerchant...")

# Connect with a private key (reads from env or direct param)
address = client.connect_with_private_key(
    private_key="YOUR_PRIVATE_KEY",  # or use os.environ
    chain_name="base",               # EVM chain to sign for
)
print(f"Connected: {address}")

# Create a signed X-PAYMENT header
x_payment = client.create_authorization(
    pay_to="0xMerchant...",
    amount_usd=Decimal("1.00"),
    chain_name="base",
    token_type="usdc",
    valid_duration=3600,  # 1 hour
)

# Use the header in requests
import requests
response = requests.get(
    "https://api.example.com/premium",
    headers={"X-PAYMENT": x_payment},
)
```

> **Note**: EVM-only. The SDK validates the chain is EVM type before signing.

---

## `/accepts` Negotiation

Discover what the facilitator can settle before constructing payment authorizations. Used by Faremeter middleware and clients.

```python
from uvd_x402_sdk import X402Client

client = X402Client(recipient_address="0xMerchant...")

# Ask facilitator what it can settle
enriched = client.negotiate_accepts([
    {
        "scheme": "exact",
        "network": "base-mainnet",
        "maxAmountRequired": "1000000",
        "resource": "https://api.example.com/data",
        "payTo": "0xMerchant...",
    }
])
# enriched[0]["extra"] now has feePayer, tokens, escrow config
```

---

## Escrow & Refunds

Hold payments in escrow with dispute resolution.

```python
from uvd_x402_sdk import EscrowClient

async with EscrowClient() as client:
    # Create escrow payment
    escrow = await client.create_escrow(
        payment_header=request.headers["X-PAYMENT"],
        requirements=payment_requirements,
        escrow_duration=86400,  # 24 hours
    )

    # Release after service delivery
    await client.release(escrow.id)

    # Or request refund if service failed
    await client.request_refund(
        escrow_id=escrow.id,
        reason="Service not delivered",
    )
```

---

## Bazaar Discovery

Register and discover paid x402 resources across the network.

```python
from uvd_x402_sdk import BazaarClient

async with BazaarClient() as bazaar:
    # List available resources
    resources = await bazaar.list_resources(category="finance", network="base-mainnet")
    for r in resources.items:
        print(f"{r.url} - {r.description}")

    # Only the ones a probe actually reached, best-curated first
    for r in (await bazaar.list_resources(limit=50, health="alive", tier="vip")).items:
        print(r.url, r.health.status, r.health.latency_ms, r.curation.label)

    # Free-text search. This runs server-side over the whole catalog, so
    # `pagination.total` is the real number of matches -- filtering one page
    # locally is not the same thing and will under-report.
    hits = await bazaar.list_resources(q="logs")
    print(hits.pagination.total)

    # Newer filters, sent only when passed. They need x402-rs 2.47.0 or later;
    # 2.46.1 and earlier answer 400 to a parameter they do not know.
    cheap = await bazaar.list_resources(max_price_usd="0.05", method="POST", has_input_schema=True)
    others = await bazaar.list_resources(exclude_host=["spam.example", "ads.example"])  # one comma-separated value

    # Register your own resource
    await bazaar.register_resource(
        url="https://api.example.com/data",
        resource_type="http",
        description="Premium data API",
        accepts=[{
            "scheme": "exact",
            "network": "eip155:8453",
            "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "amount": "10000",
            "payTo": "0xYourWallet...",
        }],
        metadata={"category": "finance", "tags": ["market-data"]},
    )
```

`q` is capped at `MAX_SEARCH_LEN` (400) characters by default; `BazaarClient(max_search_len=128)` matches x402-rs 2.46.1, `None` leaves the length to the server.

### Declaring the endpoint in the 402 (`bazaar` extension)

`bazaar_extension()` builds the `extensions.bazaar` block of an x402 v2 challenge. With a body method it emits the shape of the x402 spec (`info` + `schema`, [`specs/extensions/bazaar.md`](https://github.com/coinbase/x402/blob/dd927a26cfefc98c24b3ec38b3a8f204dad0c60d/specs/extensions/bazaar.md)), so the facilitator learns the endpoint is POST and how to call it:

```python
from uvd_x402_sdk import bazaar_extension, create_402_response_v2

extensions = bazaar_extension(
    {"type": "object", "properties": {"q": {"type": "string"}}, "required": ["q"]},
    {"results": []},
    method="POST",
    body={"q": "weather in Lima"},   # example body: info.input.body
)
# extensions["bazaar"]["info"]["input"] ==
#   {"type": "http", "method": "POST", "bodyType": "json", "body": {"q": "weather in Lima"}}
body = create_402_response_v2("0.01", config, resource={"url": "https://api.example.com/search"},
                              extensions=extensions)
```

The two historical shapes (`input_schema` alone, or `method` + `query_params`) come out unchanged; `info=True` gives them the spec shape too.

The same block declares the endpoint when you register it. `register_resource(..., extensions=extensions)` sends it as `extensions` in the body of `POST /discovery/register`; x402-rs keeps it as given, its listing carries `hasInputSchema: true`, and its health prober calls the endpoint with the declared method and example body. Without `extensions` the body is the one sent before.

```python
async with BazaarClient() as bazaar:
    await bazaar.register_resource(
        url="https://api.example.com/search",
        description="Search the web in natural language",
        accepts=[{
            "scheme": "exact",
            "network": "eip155:8453",
            "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "amount": "10000",
            "payTo": "0xYourWallet...",
            "maxTimeoutSeconds": 60,
        }],
        extensions=extensions,
    )
```

### Listing after settle (`extra.discoverable`)

The Ultravioleta facilitator lists a resource in its Bazaar after a successful settle whose requirements carry `extra.discoverable: true`. That is a different field from `extensions.bazaar` above. `X402Config(discoverable=True)` writes it in every option of `create_402_response_v2` and in the requirements sent to `/verify` and `/settle`, and `discoverable=False` writes an explicit `false`. Leaving it unset (`None`, the default) writes nothing. For a single accept, use `with_discoverable(accept)` (or `with_discoverable(accept, False)`):

```python
from uvd_x402_sdk import X402Config, with_discoverable

config = X402Config(recipient_evm="0xYourWallet...", discoverable=True)
accept = with_discoverable({"scheme": "exact", "network": "eip155:8453", "asset": USDC, "amount": "10000",
                            "payTo": "0xYourWallet...", "extra": {"name": "USD Coin", "version": "2"}})
# accept["extra"] == {"name": "USD Coin", "version": "2", "discoverable": True}
```

A Hedera settle is never listed, because the facilitator refuses any Hedera `extra` except `feePayer`. With the config option, native Hedera offers go out as they come. `with_discoverable` raises on a Hedera accept, whatever the case of its network.

---

## WalletAdapter

Abstract wallet interface for signing EIP-3009 authorizations. Use `EnvKeyAdapter` for raw private keys or `OWSWalletAdapter` for a key kept in an Open Wallet Standard vault.

```bash
pip install uvd-x402-sdk[wallet]
```

```python
from uvd_x402_sdk import EnvKeyAdapter

# Reads WALLET_PRIVATE_KEY or PRIVATE_KEY from env
wallet = EnvKeyAdapter()
print(wallet.get_address())  # 0x...

# Sign an EIP-3009 ReceiveWithAuthorization
auth = wallet.sign_eip3009({
    "to": "0xRecipient...",
    "amount_usdc": 0.10,
    "network": "base",
})
print(auth["signature"])  # Use as X-PAYMENT header

# Sign arbitrary EIP-712 typed data
result = wallet.sign_typed_data({
    "domain": {"name": "MyDapp", "version": "1", "chainId": 8453},
    "types": {"Message": [{"name": "content", "type": "string"}]},
    "message": {"content": "Hello"},
})

# Sign a personal message (EIP-191)
sig = wallet.sign_message("Hello, world!")
```

### OWSWalletAdapter (Open Wallet Standard)

The key stays in the OWS vault and is used there; this process never holds it.
Written against `open-wallet-standard` 1.4.2 (`pip install open-wallet-standard`;
`sign_transaction` also needs the `signer` extra).

```python
from uvd_x402_sdk import OWSWalletAdapter

wallet = OWSWalletAdapter(
    wallet_name="agent-treasury",  # name or id in the vault
    network="base",                # the chain OWS is told (its policies decide on it)
    # passphrase=...  (default: OWS_PASSPHRASE), vault_path=...  (default: ows's own)
)
auth = wallet.sign_eip3009({"to": "0xRecipient...", "amount_usdc": "0.10", "network": "base"})
```

Typed data and transactions that name their own chain id are signed on that
chain. What the adapter returns is what `EnvKeyAdapter` signs with the same key
(`tests/test_ows_wallet_adapter.py`), or it raises:

- Typed data is sent normalised by its declared types. A value out of its
  type's range (ows would sign `2**256` as a `uint256`), a `string` or
  `address` that is not a str, or a `bool` that is not a bool raises
  `ValueError` before anything is signed. With eth-account installed, each
  typed-data signature is recovered against the digest eth-account computes
  and raises `ValueError` instead of being returned when it is not the
  wallet's, e.g. for an `EIP712Domain` declared in a non-canonical order,
  which eth-account ignores.
- A transaction's `from` (web3's `build_transaction` keeps it) must be the
  wallet, compared without case; otherwise `TypeError`, and nothing is signed.
  eth-account compares the checksummed form exactly.

A `vault_path` that does not exist is created by ows, even by a read.

### Custom WalletAdapter

Any class implementing the `WalletAdapter` protocol can be used:

```python
from uvd_x402_sdk import WalletAdapter

class MyWallet:
    def get_address(self) -> str: ...
    def sign_message(self, message: str) -> str: ...
    def sign_typed_data(self, typed_data: dict) -> "SignedTypedData": ...
    def sign_eip3009(self, params: "EIP3009Params") -> "EIP3009Authorization": ...

assert isinstance(MyWallet(), WalletAdapter)  # True (runtime_checkable)
```

---

## ERC-8128 Signed HTTP Requests (`sign_request` / `fetch_nonce`)

Sign HTTP requests per [ERC-8128](https://eip.tools/eip/8128) (Signed HTTP
Requests with Ethereum, RFC 9421) with any `WalletAdapter`. This is how agents
authenticate against wallet-signed APIs — most notably Execution Market, where
API keys are rejected in production and only wallet signing is accepted. The
private key never leaves the adapter; only `get_address()` and
`sign_message()` (EIP-191 personal_sign) are used.

```python
from uvd_x402_sdk import EnvKeyAdapter, fetch_nonce, sign_request

wallet = EnvKeyAdapter()  # reads WALLET_PRIVATE_KEY from env

# 1. Fresh single-use nonce (5-minute TTL) — one per signed request,
#    including retries: the server consumes it before verification.
nonce = await fetch_nonce("https://api.execution.market")

# 2. Sign the request. Body must be byte-identical to what goes on the wire.
headers = sign_request(
    wallet,
    method="POST",
    url="https://api.execution.market/api/v1/tasks",
    body='{"title": "test"}',
    nonce=nonce,
)
# {"Signature": "eth=:...:", "Signature-Input": "eth=(...)", "Content-Digest": "sha-256=:...:"}

# 3. Merge into the request headers and send.
```

The wire format is **pinned** and byte-tested against golden vectors
(`tests/fixtures/erc8128.json`): `alg="eip191"` always emitted, keyid always
lowercase (`erc8128:{chain_id}:{address}`), signature params in the order
`created;expires;nonce;keyid;alg`. Covered components: `@method`,
`@authority`, `@path`, plus `@query` when the URL has a query string and
`content-digest` (SHA-256, RFC 9530) when the request has a body.

---

## Escrow Pre-Auth Builder (`build_escrow_pre_auth` / `compute_escrow_nonce`)

Sign the escrow lock authorization for sign-on-assignment marketplaces
(Execution Market ADR-002) with any `WalletAdapter`. The EIP-3009 nonce is
`AuthCaptureEscrow.getHash(paymentInfo)` which **includes the receiver** — the
signature commits to the chosen worker, so it can only be created AT
ASSIGNMENT. Returns the raw JSON `X-Payment-Auth` header value the backend
relays verbatim to the Facilitator `POST /settle`.

```python
import httpx
from uvd_x402_sdk import EnvKeyAdapter, build_escrow_pre_auth

# Full response of GET /api/v1/h2a/payment-config (never hardcode the domain)
config = httpx.get(
    "https://api.execution.market/api/v1/h2a/payment-config"
).json()

payment_auth = build_escrow_pre_auth(
    payment_config=config,
    network="base",
    payer="0xPublisher...",          # must match the signing wallet
    receiver="0xWorker...",          # committed by the nonce
    amount_usd=0.10,
    deadline=task_deadline_epoch,    # release window outlasts it
    wallet=EnvKeyAdapter(),
)
# Send as the X-Payment-Auth header on the assignment request.
```

Fail-loud: an unknown network or incomplete network config raises
`ValueError` — a silent domain fallback would sign a mismatched,
wallet-draining authorization. Before signing, the config's `chain_id` must
be the chain the SDK registers for `network`, and its USDC domain, escrow,
token collector, USDC and operator are checked against the SDK's own tables
(`VERIFIED_USDC_DOMAINS`, `uvd_x402_sdk.escrow_contracts`), and `maxFeeBps`
against the chain's ceiling (`ESCROW_MAX_FEE_BPS`, 1800 bps; the SDK's policy,
not an on-chain limit): a value that
differs from (or exceeds) the chain's row raises `ValueError`. Since 0.97.0 a
chain without a row in each of those tables raises `ValueError` too, and so does
a `network` that is neither a name of the SDK's network registry nor
`eip155:<chain id>` (until 0.96.0 both were signed with a logged warning): the
chains with every row are Base, Ethereum, Polygon, Arbitrum, Celo, Monad,
Avalanche, Optimism, SKALE Base, Arc, Arc Testnet and Robinhood Chain.
On Robinhood Chain (`robinhood` / `eip155:4663`, since 0.111.0) the row is Arc's
canonical x402r set and Execution Market's operator with Paxos USDG
(`0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168`, 6 decimals) as the token: the
config's `usdc` must be that address and its domain `Global Dollar` / `1`.
Execution Market's payment config serves `usdc: null` there and the token under
`tokens.USDG`; a caller fills `usdc` from it, or the pre-auth refuses the block
as incomplete. `robinhood-testnet` has no row. The tier windows are
bounded as well: each of `pre` / `auth` / `refund` is a whole number of seconds
within `ESCROW_MAX_TIER_WINDOWS` (1 day / 7 days / 30 days), and the signed
`authorizationExpiry` is at most `ESCROW_MAX_AUTHORIZATION_SEC` (37 days: a
30-day deadline plus the 7-day review window) after signing; `deadline` is
whole epoch seconds. `chain_id`, the fee bounds and the windows are read as the
TypeScript SDK reads them: a number without a fraction or a string of ASCII
digits, anything else is `ValueError`. On-chain
limits enforced client-side: bounty <= $100 (AuthCaptureEscrow deposit
condition), the signed `maxFeeBps` must
cover the operator's 1300 bps static fee, and `minFeeBps` must not exceed it. `compute_escrow_nonce()` is the
standalone, dict-based equivalent of `AdvancedEscrowClient._compute_nonce`
(no web3 needed — only `eth-abi`/`eth-utils`, pulled in by `eth-account`).
The wrapper is byte-tested against golden vectors
(`tests/fixtures/escrow-preauth.json`, shared with the Execution Market web,
mobile and plugin-SDK suites).

---

## Signed escrow lifecycle orders (`build_lifecycle_auth`)

`release` and `refundInEscrow` move money that is **already** escrowed, so
neither carries an ERC-3009 signature — there is no transfer left to authorize.
That left the other half of the question open: *who is entitled to ask for the
move*. Until now, whoever called. On 2026-08-30 a third party probed exactly
that: five calls with a fabricated `paymentInfo`, two of them mined.

The facilitator (`x402-rs`, PR #21) now verifies an **EIP-712 order** signed by
the party the action belongs to. This is the other end of that cable — the part
that signs it.

| action | accepted signers |
|---|---|
| `release` | the payer; the operator owner (`FEE_RECIPIENT()`, read on-chain) |
| `refundInEscrow` | the receiver; the operator owner; the payer, but only once `authorizationExpiry` has passed |

The receiver may never `release` (paying yourself out of an escrow is what
escrow exists to stop) and the payer may never `refundInEscrow` before expiry
(that is the chargeback).

```python
from uvd_x402_sdk import AdvancedEscrowClient, EnvKeyAdapter

client = AdvancedEscrowClient(...)

# The signer is INJECTED — the SDK never reads a key from the environment on
# its own. Any WalletAdapter works (EnvKeyAdapter, a KMS, a browser wallet).
tx = client.release_via_facilitator(
    payment_info,
    lifecycle_signer=EnvKeyAdapter(private_key),   # must be the payer or the operator owner
)
```

Or build the block yourself and attach it to any request:

```python
from uvd_x402_sdk import build_lifecycle_auth

auth = build_lifecycle_auth(
    action="release",              # or "refundInEscrow"
    payment_info=payment_info,     # the wire dict, camelCase, salt as hex
    payer=payer_address,           # payload.payer, NOT inside payment_info
    amount=1_000_000,              # the SAME amount as payload.amount
    chain_id=8453,
    wallet=adapter,
)
# -> {"signer", "deadline", "nonce", "signature"}, goes at payload.lifecycleAuth
```

**Rollout is by facilitator mode** (`ESCROW_LIFECYCLE_AUTH`): `off` (the order
is not looked at), `log` (verify when present, log the verdict, never reject)
and `enforce`. `lifecycle_signer` is optional at every layer, so a caller that
passes nothing sends the byte-identical request it sent before.

Things worth knowing, each of which is a rejection the facilitator names and the
caller cannot see:

- **`paymentInfo.salt` is `bytes32` on the wire and `uint256` in the signature.**
  The facilitator converts it (`U256::from_be_bytes`); signing it as a string
  produces a different digest and a silent `bad_signature`. The SDK converts it
  for you.
- **`amount` is signed.** Signing `max_amount` and submitting a partial release
  is an order that does not verify — and a partial is the normal case for a
  stream.
- **`deadline` has a 900 s ceiling** (`deadline_too_far`). The default signs
  `now + 600`, which is what keeps a facilitator clock a few seconds behind
  yours from deciding the verdict.
- **`nonce` is consumed on acceptance** (`replayed`). It defaults to a fresh
  random 32 bytes; a stream emitting one order per delta needs one each.
- **The order is signed over the paymentInfo that is submitted**, so neither
  side recomputes `getHash` and there is nothing to drift — and an intermediary
  cannot change the receiver after the fact.

`build_lifecycle_typed_data()` exposes the EIP-712 document itself, which is
the seam the TypeScript twin mirrors — and the seam a browser signs through.

### When someone else signs (`lifecycle_auth`)

The party entitled to the move is often not the process asking for it. The
payer signs `release` in their browser; a backend transports it. That backend
does not have — and must not have — the payer's key, so `lifecycle_signer` is
the wrong seam: it signs with a key in the process.

`lifecycle_auth` is the other one. It takes an order **already signed** and
attaches it verbatim:

```python
from uvd_x402_sdk import (
    build_lifecycle_typed_data,
    lifecycle_auth_from_signature,
)

# 1. The backend builds the document. Nothing secret here — ship it to the
#    browser as JSON and let the wallet sign it (eth_signTypedData_v4).
typed = build_lifecycle_typed_data(
    action="release",
    payment_info=payment_info,   # the wire dict, camelCase, salt as hex
    payer=payer_address,
    amount=1_000_000,
    chain_id=8453,
    deadline=int(time.time()) + 600,   # 900 s ceiling; leave yourself slack
    nonce="0x" + secrets.token_hex(32),
)

# 2. The browser returns 65 bytes and nothing else.
auth = lifecycle_auth_from_signature(
    typed_data=typed,
    signature=signature_from_browser,
    signer=payer_address,
)

# 3. Transported as-is. Not re-signed, and the nonce and deadline are the
#    ones that entered the digest.
tx = client.release_via_facilitator(payment_info, lifecycle_auth=auth)
```

- **`deadline` and `nonce` are not passed separately.** They are read out of
  the `typed_data` that was signed. Declaring them alongside would let the
  wire announce one window while the signature covers another — a
  `bad_signature` neither side can name.
- **The signature is verified against `signer` before it is returned.** The
  real failure of the browser path is that the page signs with whichever
  account is connected while the backend believes it was another one. The
  facilitator answers `bad_signature` to that and does not say which of the
  two was wrong; `lifecycle_auth_from_signature` does. (It needs
  `eth-account` for the recovery — `pip install uvd-x402-sdk[signer]`.)
- **`lifecycle_signer` and `lifecycle_auth` are mutually exclusive.** One
  signs a new order with its own nonce and deadline, the other carries a
  foreign one; picking silently would submit an order the caller did not
  intend, and on `release` that is money moving. Passing both raises.
- Both paths produce the **same wire block**, pinned by a test: the browser
  route is not a second dialect.
---

## x402 v2 requests (`build_verify_request_v2` / `build_settle_request_v2`)

If the 402 you received advertises CAIP-2 networks (`eip155:8453`), you are
speaking v2 and must send the **v2 envelope**.

**Since v0.74.0 the client does this for you.** `X402Client.verify_payment` and
`settle_payment` pick the envelope from the wire: a CAIP-2 network gets v2, a
plain name stays on v1, and `X402Config(x402_version=1|2)` pins it either way.
Nothing to call, nothing to pass — see
[Choosing the envelope](#choosing-the-envelope-x402_version) below.

Reach for the builders directly when you are assembling a body outside the
client — echoing a vendor's `accept` verbatim, or driving the facilitator
without a `PaymentPayload` in hand:

```python
from uvd_x402_sdk import (
    AcceptedRequirementsV2, ResourceInfoV2, build_verify_request_v2,
)

body = build_verify_request_v2(
    payload={"signature": "0x...", "authorization": {...}},
    resource=ResourceInfoV2(
        url="https://api.example.com/thing",
        description="Thing",
        mime_type="application/json",
    ),
    accepted=AcceptedRequirementsV2(
        scheme="exact",
        network="eip155:8453",
        asset="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
        amount="100000",
        pay_to="0xabc...",
        max_timeout_seconds=300,
    ),
)
httpx.post(f"{facilitator_url}/verify", json=body)
```

Plain dicts work too, which matters because the spec makes you echo the vendor's
accept **verbatim** — you will usually have a dict, not a model.

| | v1 envelope | v2 envelope |
|---|---|---|
| top level | `{x402Version, paymentPayload, paymentRequirements}` | `{x402Version, paymentPayload, resource, accepted}` |
| network | plain name — `base` | CAIP-2 — `eip155:8453` |
| amount field | `maxAmountRequired` | `amount` |
| `resource` | URL **string** | **object** `{url, description, mimeType}` |

> **Do not mix levels.** Each version demands its own network format *and* its
> own envelope. A v2 payload inside a v1 envelope — or a plain network name
> inside a v2 request — matches no variant at the facilitator and fails with
> `data did not match any variant of untagged enum VerifyRequestEnvelope`, an
> error that names no field. If you see it, check the **envelope shape** first,
> not the fields inside it.

### Choosing the envelope (`x402_version`)

`X402Config.x402_version` decides which envelope `verify_payment()` and
`settle_payment()` send. It defaults to `"auto"`:

```python
# auto (default): CAIP-2 on the wire -> v2, plain name -> v1
client = X402Client(recipient_address="0x...")
client.verify_payment(payload, Decimal("0.01"))   # payload.network == "base"
                                                  #   -> v1 envelope
client.verify_payment(payload_caip2, Decimal("0.01"))  # "eip155:8453"
                                                  #   -> v2 envelope

# pin, when you know better than the wire
client = X402Client(config=X402Config(recipient_evm="0x...", x402_version=1))
```

**Auto reads the network, not the version marker**, and that is measured against
production rather than assumed. The facilitator's envelope enum is *untagged* —
it matches on shape and ignores `x402Version` — so a header that merely declares
version 2 while carrying plain network names is served correctly today and is a
**400** in the v2 envelope. Upgrading it on the strength of the marker would
break a call that works.

Both envelopes answer 200 for a CAIP-2 pair against facilitator 2.10.0 and
reduce to the same payment, but only v2-with-CAIP-2 is accepted by builds older
than 2026-09-04, where v1-with-CAIP-2 is a hard 400 (`unknown variant
`eip155:8453``). Choosing v2 there is what makes one client work against both.

XRPL has no CAIP-2 form — its v1 string *is* its identifier — so it stays on v1
under `auto`. An explicit `x402_version=2` on it raises rather than sending a v1
network name inside a v2 body.

`resolve_envelope_version()` (and therefore the `"auto"` default) reads a **v2
payload** as well as a flat v1 one. A v2 payload has no top-level `network` at
all — v2 moved the chain id into `accepted` — so `auto` reads it from there, and
a payload carrying neither resolves to v1 instead of raising. Before **0.75.0**
it read only the top level and blew up on exactly that shape
(`AttributeError: 'dict' object has no attribute 'network'`, or
`TypeError: argument of type 'NoneType' is not iterable`), which is why
integrators were pinning `x402_version` instead of using the default.

```python
from uvd_x402_sdk.envelope import resolve_envelope_version

v2_payload = {                        # what a buyer following a v2 402 sends
    "x402Version": 2,
    "resource": {"url": ..., "description": ..., "mimeType": ...},
    "accepted": {"scheme": "exact", "network": "eip155:8453", ...},
    "payload": {"signature": "0x...", "authorization": {...}},
}
resolve_envelope_version(v2_payload, requirements)   # -> 2
```

The same choice is exposed as functions for callers driving the facilitator
themselves: `resolve_envelope_version()`, `build_verify_request_for_version()`,
`build_settle_request_for_version()`, and the conversion
`to_resource_info_v2()` / `to_accepted_requirements_v2()`.

## Metrics and history (`get_stats` / `get_transactions`)

```python
stats = client.get_stats()
for row in stats["byNetworkAndAsset"]:
    # Use the row's OWN decimals. USDC is 6 nearly everywhere and 18 on BSC —
    # scaling by a constant 6 overstates BSC volume by 10^12.
    print(row["network"], row["settlesOk"], row["volumeAtomic"], row["decimals"])

recent = client.get_transactions(limit=20, network="base")
```

> **An index, not a ledger.** Records are written best-effort *after* settlement,
> so an outage loses rows while payments proceed — verify anything that matters
> against the transaction hash. Counting starts when the operator enabled the
> store, so earlier operations are **unknown, not zero**. And unless failure
> publishing is on, operations that error are not recorded at all, so a 100%
> success rate means "no failures were recorded".
>
> `get_transactions` has **no pagination**: it returns the newest N (capped at
> 200), walking back at most 30 days.

## Live Traffic Stream (`GET /events`)

The facilitator emits one Server-Sent Event per operation it handles, so you can
render or react to live traffic without polling.

```python
from uvd_x402_sdk import TrafficEventStream

with TrafficEventStream() as stream:
    for event in stream:
        print(event.kind, event.network, event.ok, event.tx)

# Only settlements on the chains you care about. The facilitator has NO
# server-side filter by network, so this runs client-side.
with TrafficEventStream(networks=["base", "polygon"], kinds=["settle"]) as stream:
    for event in stream:
        print(event.tx, event.timestamp)

# Async, for an event loop
async with TrafficEventStream() as stream:
    async for event in stream:
        print(event.network)
```

Three properties decide how you should use this:

**It is lossy by design.** The facilitator will never slow down or fail a payment
to keep an observer in sync, so an event you were not connected for is gone.
Treat it as a live hint and use the chain as the source of truth — and note that
*absence of events is not evidence that nothing happened*. On a quiet rail the
only thing on the wire for minutes is a keepalive.

**Failed operations are not published.** Only operations that resolved emit an
event, so `ok=False` means "resolved and came back negative", never "blew up". A
stream that looks healthy is not proof that the rail is.

**Admission is bounded.** `/events` is public and unauthenticated, so it sheds
with HTTP 503 + `Retry-After` at subscriber capacity, and returns 404 when the
operator disabled it. Both raise `FacilitatorError` with `status_code` intact.

> **Match the canonical network slug.** `network` is the name `/supported` uses,
> which is not always the alias you may *send*. `skale` is accepted inbound, but
> events always say `skale-base`. Keying on the alias silently drops every event
> for that chain.

| Field | Notes |
|-------|-------|
| `ts` | Unix epoch **milliseconds** (not seconds); `event.timestamp` gives a UTC `datetime` |
| `kind` | `"verify"` or `"settle"` |
| `network` | Canonical slug, same as `/supported` |
| `ok` | Resolved successfully? |
| `payer` / `amount` / `asset` | Omitted in `minimal` detail mode |
| `tx` | Present on `settle`, absent on `verify` — nothing settled yet |

## Facilitator Info

Query the facilitator for version, supported networks, blacklist, and health.

```python
from uvd_x402_sdk import X402Client

client = X402Client(recipient_address="0xYourWallet...")

# Check version
version = client.get_version()
print(f"Facilitator: v{version['version']}")

# List supported networks
supported = client.get_supported()
for kind in supported["kinds"]:
    print(f"  {kind['network']} - {kind['scheme']}")

# Check blacklist
bl = client.get_blacklist()
print(f"Blocked addresses: {bl['totalBlocked']}")

# Health check
is_healthy = client.health_check()
```

---

## Escrow State Queries

Query on-chain escrow state without performing settlement.

```python
from uvd_x402_sdk import EscrowClient

async with EscrowClient() as escrow:
    state = await escrow.get_escrow_state(
        network="base-mainnet",
        payer="0xPayer...",
        recipient="0xRecipient...",
        nonce="0x1234...",
    )
    print(f"Status: {state['status']}, Balance: {state.get('balance')}")
```

---

## How x402 Works

The x402 protocol enables gasless stablecoin payments (USDC, EURC, AUSD, PYUSD):

```
1. User Request     -->  Client sends request without payment
2. 402 Response     <--  Server returns payment requirements
3. User Signs       -->  Wallet signs authorization (NO GAS!)
4. Frontend Sends   -->  X-PAYMENT header with signed payload
5. SDK Verifies     -->  Validates signature with facilitator
6. SDK Settles      -->  Facilitator executes on-chain transfer
7. Success          <--  Payment confirmed, request processed
```

The facilitator (https://facilitator.ultravioletadao.xyz) handles all on-chain interactions and pays gas fees on behalf of users.

### Payment Flow by Network Type

| Network Type | User Signs | Facilitator Does |
|--------------|-----------|------------------|
| EVM | EIP-712 message | Calls `transferWithAuthorization()` |
| SVM | Partial transaction | Co-signs + submits transaction |
| NEAR | DelegateAction (Borsh) | Wraps in `Action::Delegate` |
| Stellar | Auth entry (XDR) | Wraps in fee-bump transaction |
| Algorand | ASA transfer tx | Signs fee tx + submits atomic group |
| Sui | Programmable tx block | Sponsors gas + submits transaction |
| XRPL | Payment tx (signed blob) | Submits tx + pays network fee |

---

## Error Codes

| Exception | Description |
|-----------|-------------|
| `PaymentRequiredError` | No payment header provided |
| `PaymentVerificationError` | Signature invalid, amount mismatch, expired |
| `PaymentSettlementError` | On-chain settlement failed |
| `UnsupportedNetworkError` | Network not recognized or disabled |
| `InvalidPayloadError` | Malformed X-PAYMENT header |
| `FacilitatorError` | Facilitator service error |
| `ConfigurationError` | Invalid SDK configuration |
| `X402TimeoutError` | Request timed out |

---

## Security

- Users **NEVER** pay gas or submit transactions directly
- **EVM**: Users sign EIP-712 structured messages for any supported stablecoin (USDC, EURC, AUSD, PYUSD)
- **Solana/Fogo**: Users sign partial transactions (facilitator co-signs and submits)
- **Stellar**: Users sign Soroban authorization entries only
- **NEAR**: Users sign NEP-366 meta-transactions (DelegateAction)
- **Sui**: Users sign programmable transaction blocks (facilitator sponsors gas)
- **XRPL**: Users sign a native-XRP Payment transaction (facilitator submits it and pays the ledger fee)
- The facilitator submits and pays for all on-chain transactions
- All signatures include expiration timestamps (`validBefore`) for replay protection
- Nonces prevent double-spending of authorizations
- Each token has verified contract addresses and EIP-712 domain parameters

---

## Troubleshooting

### Common Issues

**"Unsupported network"**
- Check that the network is in `supported_networks`
- Verify the network is enabled
- For v2, ensure CAIP-2 format is correct

**"Payment verification failed"**
- Amount mismatch between expected and signed
- Recipient address mismatch
- Authorization expired (`validBefore` in the past)
- Nonce already used (replay attack protection)

**"Settlement timed out"**
- Network congestion - increase `settle_timeout`
- Facilitator under load - retry after delay

**"Invalid payload"**
- Check base64 encoding of X-PAYMENT header
- Verify JSON structure matches expected format
- Ensure `x402Version` is 1 or 2

### Debug Logging

```python
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("uvd_x402_sdk").setLevel(logging.DEBUG)
```

---

## Development

```bash
# Clone and install
git clone https://github.com/UltravioletaDAO/uvd-x402-sdk-python
cd uvd-x402-sdk-python
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black src tests
ruff check src tests

# Type checking
mypy src
```

---

## Links

- [x402 Protocol](https://x402.org)
- [Ultravioleta DAO](https://ultravioletadao.xyz)
- [402milly](https://402milly.xyz)
- [GitHub](https://github.com/UltravioletaDAO/uvd-x402-sdk-python)
- [PyPI](https://pypi.org/project/uvd-x402-sdk/)
- [TypeScript SDK](https://github.com/UltravioletaDAO/uvd-x402-sdk-typescript)

---

## License

MIT License - see LICENSE file.

---

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for release history.

## DX402 — evidence that outlives the session

x402 settles payment on-chain forever but delivers the resource **once** and
keeps nothing. DX402 seals a copy of the response to the payer's own public key
— recovered from the payment signature itself — and anchors it. No registration,
no extra round trip: paying *is* publishing your encryption key.

```bash
pip install 'uvd-x402-sdk[dx402]'
```

### Seller: one call

```python
from uvd_x402_sdk import anchor_evidence, evidence_header

result = anchor_evidence(
    body,                                   # the bytes you are about to deliver
    payment_id_value=payment_id, network="base", tx_hash=tx,
    payer=payer_addr, payee=my_addr, payer_key=payer_pubkey,
    signer=lambda digest: my_custodian.sign(digest),   # a callable, not a key
)
response.headers["X-Durable-Evidence"] = evidence_header(result)
```

**It never raises.** Every failure comes back as `result["skipped"]`, because
evidence is an addition to the payment path and must never be a gate in front of
it. An unreachable facilitator costs the receipt, never the sale.

`signer` takes a **callable rather than a private key** so a custodian can sign:
it receives the 32-byte digest and returns a signature without the seed ever
leaving it.

### Buyer: come back months later

```python
from uvd_x402_sdk import recover_evidence, evidence_from_headers

evidence = evidence_from_headers(response.headers)
body = recover_evidence(evidence, my_private_key)
```

This needs permission from nobody. The ciphertext was sealed to the wallet that
paid, so recovery is arithmetic rather than an access-control decision anyone
could refuse. The `contentHash` check runs automatically and raises on
mismatch — it is what catches a seller who anchored something other than what it
served.

### `verified` vs `signed` — read this before you branch on either

Since facilitator **1.87.0** a signature alone does not make an anchor final:

| field | means | supersedable by |
|---|---|---|
| `verified: true` | the **chain** confirmed this address is the payee | nothing — final |
| `signed: true` | the claimant controls the address it *declared* | a verified anchor |
| neither | anyone could have written it | either of the above |

To reach `verified` you must send `proof_of_payment`. Without it the facilitator
has checked no chain and answers `notVerifiedReason: "dx402_proof_missing"` —
your signature was still accepted (`signed: true`), authorship simply was not
certified.

Why the split: `verified` was previously decided against the `payee` field *in
the request*, which the caller supplies. Proving "I control the address I typed
into my own request" was enough to own a stranger's evidence permanently.

### Choosing where evidence is stored

```python
from uvd_x402_sdk import available_backends

for b in available_backends("https://facilitator.ultravioletadao.xyz"):
    print(b["id"], b["retention"], "deletable" if b["revocable"] else "IRREVERSIBLE")

anchor_evidence(body, ..., storage="ipfs-private")
```

Ask rather than assume: what exists depends on the deployment, and you may be
pointed at a facilitator that is not ours. `revocable: False` means the
`retentionUntil` in the **signed** receipt cannot be honoured — on public IPFS,
unpinning removes the facilitator's copy, not the network's.

### Runnable examples

Not snippets — files, and CI runs them:

| file | shows |
|---|---|
| [`examples/dx402/seller_anchor.py`](examples/dx402/seller_anchor.py) | the whole seller side in one call |
| [`examples/dx402/buyer_recover.py`](examples/dx402/buyer_recover.py) | recovery, tamper detection, and that another wallet cannot open it |
| [`examples/dx402/verified_anchor.py`](examples/dx402/verified_anchor.py) | reaching `verified: true` with `proof_of_payment` |
| [`examples/dx402/choose_storage.py`](examples/dx402/choose_storage.py) | discovering backends and what each one promises |

### Limits

- Inline anchors cap at **64 KiB of request** (~47 KB of plaintext); the SDK
  returns `skipped: "too_large"` before touching the network.
- Anchoring with `retention: permanent` is **irrevocable**.
- On Solana, `verified` is not reachable yet — the on-chain gate cannot read
  that payment, so `signed: true` is the honest maximum.

Full guide: [DX402.md](https://github.com/UltravioletaDAO/x402-rs/blob/main/docs/DX402.md)

## Portable facilitator receipts

Arc mainnet/testnet exact USDC/EURC and native Hedera USDC v2 support additive
facilitator receipts: network, asset, atomic amount, payTo, request hash,
settlement ID, status and refusal reason. Persist purchase context before sending
the authorization and reuse it after uncertainty. Payment confirmation does not
prove merchant delivery. See [the receipt guide](docs/facilitator-receipts.md).
Funded EURC payments settled on Arc mainnet (x402 v1/v2, 2026-09-22); Arc testnet funded acceptance is pending.
