venice_ai.resources.x402
Venice x402 API resources.
Wraps the three /x402/* endpoints documented at
api-reference/endpoint/x402/. These endpoints use wallet-based
Sign-In-With-X (SIWE / EIP-4361) authentication rather than Bearer tokens,
so calls go through a per-request X-Sign-In-With-X header built by
:class:~venice_ai.auth.x402.X402Auth.
top_up uses Bearer auth (the standard VENICE_API_KEY) and may
optionally carry an X-402-Payment header containing a signed payment
payload.
This module is intentionally import-time dependency-free; the X402Auth
helper lives under :mod:venice_ai.auth.x402 which is only imported lazily
by the caller. That keeps the core SDK installable without the
eth-account / siwe dependencies when x402 is not used.
X402 Objects
class X402(APIResource["VeniceClient"])
Provides access to Venice's x402 wallet-based billing endpoints.
X402.balance
async def balance(*, auth: X402Auth | SolanaX402Auth) -> X402BalanceResponse
Get the current x402 prepaid USDC balance for a wallet.
Wraps GET /api/v1/x402/balance/{wallet}. Authentication uses
the SIWE (EIP-4361) flow via the X-Sign-In-With-X header
derived from auth; standard Bearer auth is not used here.
Arguments:
auth- An :class:~venice_ai.auth.x402.X402Authinstance built from the wallet's private key. The wallet address is derived automatically.
Returns:
:class:X402BalanceResponse with success and data
(containing balanceUsd among other fields).
Raises:
AuthenticationError- If the SIWE signature is rejected or expired.PermissionDeniedError- If the wallet is not authorized for x402.NotFoundError- If the wallet has no x402 ledger entry.APIError- For other HTTP-level failures.
Example:
.. code-block:: python
import os from venice_ai import VeniceClient from venice_ai.auth.x402 import X402Auth
async with VeniceClient() as client: auth = X402Auth(private_key=os.environ["WALLET_PRIVATE_KEY"]) bal = await client.x402.balance(auth=auth) print(bal.data.balanceUsd)
X402.transactions
async def transactions(*,
auth: X402Auth | SolanaX402Auth,
limit: int | None = None,
offset: int | None = None) -> X402TransactionsResponse
List x402 ledger entries (usage + top-ups) for the wallet.
Wraps GET /api/v1/x402/transactions/{wallet}. SIWE-signed via
auth (no Bearer auth).
Arguments:
auth- :class:~venice_ai.auth.x402.X402Authfor the wallet to query.limit- Optional maximum number of transactions to return (server allows 1-100; defaults to 50 when omitted).offset- Optional number of transactions to skip for pagination (server default 0).
Returns:
:class:X402TransactionsResponse with data.transactions
and data.pagination (carries hasMore for paging).
Raises:
AuthenticationError- If the SIWE signature is rejected.PermissionDeniedError- If the wallet is not authorized for x402.InvalidRequestError- Iflimit/offsetare out of range server-side.APIError- For other HTTP-level failures.
X402.iter_transactions
def iter_transactions(
*,
auth: X402Auth | SolanaX402Auth,
page_size: int = DEFAULT_PAGE_SIZE,
max_items: int | None = None) -> Paginator[X402Transaction]
Lazily iterate every x402 transaction for the wallet.
Wraps :meth:transactions for unbounded enumeration. Termination
uses the response's data.pagination.hasMore flag, so iteration
stops when the server signals no more pages. Each page hits
GET /api/v1/x402/transactions/{wallet}.
Arguments:
auth- :class:X402Authfor the wallet to query.page_size- Server page size (default 100, max 100).max_items- Optional cap on total items yielded.
Returns:
A :class:~venice_ai._pagination.Paginator over
:class:X402Transaction. Iteration is async; HTTP errors
from underlying :meth:transactions calls propagate when the
paginator is consumed.
Example:
async for tx in client.x402.iter_transactions(auth=auth):
print(tx.id, tx.amount)
X402.top_up
async def top_up(*, payment_header: str | None = None) -> X402TopUpResponse
Top up the wallet balance via the x402 payment channel.
Wraps POST /api/v1/x402/top-up. Uses the standard Bearer auth
(VENICE_API_KEY). Optionally accepts a pre-built
X-402-Payment header containing the signed payment payload -
when omitted, an empty POST triggers a 402 response containing
structured payment-requirement details.
Arguments:
payment_header- Optional signed x402 payment payload sent in theX-402-Paymentheader.
Returns:
:class:X402TopUpResponse on success.
Raises:
PaymentRequiredError- When the server returns 402 with payment instructions (the structured payment requirements are attached to the error body).AuthenticationError- If the API key is missing or invalid.InvalidRequestError- If the supplied payment header is malformed.APIError- For other HTTP-level failures.
X402.top_up_with
async def top_up_with(
*,
auth: X402Auth,
amount_usdc: float,
max_amount_usdc: float | None = None) -> X402TopUpResponse
Top up the prepaid ledger from auth's wallet in one call.
Implements the full x402 v2 probe-sign-submit flow so callers don't have to handle the 402 challenge cycle manually:
- POST
/x402/top-upwith no payment header → catches :class:~venice_ai.exceptions.PaymentRequiredError. - Picks the first
"exact"requirement on Base mainnet (eip155:8453). - Validates
amount_usdcagainst the server's required amount and the optionalmax_amount_usdccap. - Builds the EIP-3009
X-402-Paymentheader via :meth:venice_ai.auth.x402.X402Auth.build_payment_header. - Re-POSTs
/x402/top-upwith the signed header; returns the settlement response.
Currently supports only USDC on Base mainnet. Other tokens /
chains require manual signing via
:meth:X402Auth.build_payment_header with explicit overrides.
Arguments:
auth- An :class:~venice_ai.auth.x402.X402Authwhose private key signs the EIP-3009 transfer authorization. The wallet must hold enough USDC on-chain to cover the payment.amount_usdc- The intended top-up amount in USD (Venice's x402 pricing is in USD; USDC is the settlement asset). Must meet or exceed the server's minimum (currently $5).max_amount_usdc- Optional safety cap. Defaults toamount_usdc. Raises :class:ValueErrorbefore signing if the server's required amount exceeds this cap.
Returns:
:class:~venice_ai.types.api.x402.X402TopUpResponse from the
settled top-up. Inspect .data.amountCredited for the USD
amount credited to the prepaid ledger and
.data.paymentId for the settlement record.
Raises:
ValueError- Ifamount_usdcis below the server's minimum, or if the server's required amount exceedsmax_amount_usdc, or if the 402 body is malformed.ImportError- If the[x402]extra is not installed.RuntimeError- If the initial probe call (no payment header) unexpectedly succeeds, or the 402 body lacks any acceptable"exact"requirement on Base mainnet.PaymentRequiredError- If the signed payment is rejected server-side (e.g., insufficient on-chain balance, expired signature, replayed nonce).APIError- For other HTTP-level failures.
Example:
.. code-block:: python
import os from venice_ai import VeniceClient from venice_ai.auth.x402 import X402Auth
async with VeniceClient() as client: auth = X402Auth(private_key=os.environ["WALLET_PRIVATE_KEY"]) result = await client.x402.top_up_with( auth=auth, amount_usdc=5.0, ) print(f"Credited ${result.data.amountCredited}; " f"new balance ${result.data.newBalance}")
X402.top_up_with_solana
async def top_up_with_solana(*,
auth: SolanaX402Auth,
amount_usdc: float,
max_amount_usdc: float | None = None,
rpc_url: str | None = None) -> X402TopUpResponse
Top up the prepaid ledger from a Solana wallet in one call.
Implements the full x402 v2 probe-sign-submit flow for the Solana
("exact" SVM settlement) path, mirroring :meth:top_up_with for EVM:
- POST
/x402/top-upwith no payment header → catches :class:~venice_ai.exceptions.PaymentRequiredError. - Picks the
acceptsentry whosenetworkis the bare string"solana". - Validates
amount_usdcagainst the server's required amount and the optionalmax_amount_usdccap. - Fetches the live transaction context (recent blockhash, mint
decimals, token program) from a Solana RPC via
:func:
venice_ai.auth.x402_solana.fetch_solana_tx_context. - Builds the base64
X-402-Paymentenvelope (a partially-signedVersionedTransaction) via :meth:venice_ai.auth.x402_solana.SolanaX402Auth.build_payment_header. - Re-POSTs
/x402/top-upwith the signed header; returns the settlement response.
Arguments:
auth- A :class:~venice_ai.auth.x402_solana.SolanaX402Authwhose base58 secret signs the SPL transfer authorization. The wallet must hold enough USDC on-chain to cover the payment (the facilitator pays the gas / network fees).amount_usdc- The intended top-up amount in USD. Must meet or exceed the server's minimum (currently $5).max_amount_usdc- Optional safety cap. Defaults toamount_usdc. Raises :class:ValueErrorbefore signing if the server's required amount exceeds this cap.rpc_url- Optional Solana JSON-RPC endpoint. Defaults to theVENICE_X402_SOLANA_RPC_URLenvironment variable, then tohttps://api.mainnet-beta.solana.com.
Returns:
:class:~venice_ai.types.api.x402.X402TopUpResponse from the
settled top-up.
Raises:
ValueError- Ifamount_usdcis below the server's minimum, or if the server's required amount exceedsmax_amount_usdc, or if the 402 body is malformed.ImportError- If the[x402-solana]extra is not installed.RuntimeError- If the initial probe call succeeds unexpectedly, the 402 body lacks a"solana"requirement, or RPC fails.PaymentRequiredError- If the signed payment is rejected server-side.APIError- For other HTTP-level failures.
Example:
.. code-block:: python
import os from venice_ai import VeniceClient from venice_ai.auth.x402_solana import SolanaX402Auth
async with VeniceClient() as client: auth = SolanaX402Auth(private_key=os.environ["SOLANA_SECRET"]) result = await client.x402.top_up_with_solana( auth=auth, amount_usdc=5.0, ) print(f"Credited ${result.data.amountCredited}")