Metadata-Version: 2.4
Name: paxos-sdk
Version: 0.1.0
Summary: Paxos Python SDK — Idiomatic access to all public Paxos APIs
Author: Paxos
License-Expression: Apache-2.0
Project-URL: Homepage, https://docs.paxos.com/sdks
Project-URL: Documentation, https://docs.paxos.com
Keywords: paxos,crypto,api,sdk,stablecoin
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: typing_extensions>=4.1.0
Provides-Extra: signing
Requires-Dist: cryptography>=43.0.1; extra == "signing"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: pytest-timeout>=2.3; extra == "dev"
Requires-Dist: ruff==0.17.4; extra == "dev"
Requires-Dist: mypy==2.4.1; extra == "dev"
Requires-Dist: hypothesis>=6.100; extra == "dev"
Requires-Dist: orjson>=3.9; extra == "dev"
Requires-Dist: cryptography>=43.0.1; extra == "dev"
Dynamic: license-file

# Paxos Python SDK

> Beta: we aim to avoid breaking changes, but they may occur before 1.0. Support is provided through standard Paxos support channels; please do not open GitHub issues.

Idiomatic Python client for all public [Paxos](https://paxos.com) APIs. Supports both synchronous and asynchronous usage.

## Installation

```bash
pip install paxos-sdk
```

For [request signing](#request-signing) support, install the `signing` extra:

```bash
pip install "paxos-sdk[signing]"
```

Requires Python 3.11+ and httpx.

## Quick Start

```python
import os
import paxos
from paxos.enums import Scope

client = paxos.Client(
    client_id=os.environ["PAXOS_CLIENT_ID"],
    client_secret=os.environ["PAXOS_CLIENT_SECRET"],
    sandbox=True,
    scopes=[Scope.TRANSFER_READ_TRANSFER],
)

transfer = client.transfers.get_transfer("txn_123")
print(transfer.id, transfer.status)
```

## Import Paths

- `paxos`: `Client`, `AsyncClient`, `RequestOptions`, `ResponseMetadata`, hook types, `Decimal`, and all error classes
- `paxos.models`: request and response models
- `paxos.enums`: enums
- `paxos.services`: service classes and `*Params` TypedDicts
- `paxos.testing`: mock server and fixtures

Modules whose names start with an underscore are internal.

## Sandbox

Use `sandbox=True` to target the Paxos sandbox environment for testing:

```python
from decimal import Decimal
from paxos.enums import Scope
from paxos.models import CreateSandboxDepositRequest

client = paxos.Client(
    client_id=os.environ["PAXOS_SANDBOX_CLIENT_ID"],
    client_secret=os.environ["PAXOS_SANDBOX_CLIENT_SECRET"],
    sandbox=True,
    scopes=[Scope.FUNDING_READ_PROFILE],
)

# Sandbox-only operations
client.sandbox_deposits.create_sandbox_deposit(
    profile_id="p_123",
    body=CreateSandboxDepositRequest(
        asset="ETH",
        amount=Decimal("1.0"),
        crypto_network="ETHEREUM",
    ),
)
```

## Authentication

The SDK uses OAuth2 client credentials. Token acquisition, caching, and refresh are handled automatically. Pass your credentials to `Client()` or `AsyncClient()`, including at least one OAuth scope. Use the `Scope` constants from `paxos.enums`; each method's docstring states the scope it requires (for example `Requires scope: transfer:read_transfer`):

```python
client = paxos.Client(
    client_id="your_client_id",
    client_secret="your_client_secret",
    scopes=[Scope.TRANSFER_READ_TRANSFER],
)
```

## Error Handling

Every SDK error is a subclass of `paxos.PaxosError`. HTTP error responses are `paxos.PaxosApiError` subclasses carrying `status` and a `request_id` for debugging with Paxos support; `NetworkError` and `PaxosTimeoutError` are siblings with no status:

```python
try:
    client.transfers.get_transfer("bad-id")
except paxos.NotFoundError as e:
    print(f"Not found (request_id={e.request_id}): {e.detail}")
except paxos.RateLimitError as e:
    print(f"Rate limited (request_id={e.request_id})")
except paxos.PaxosApiError as e:
    print(f"API error {e.status}: {e.request_id}")
except paxos.PaxosError as e:
    print(f"Transport failure: {e}")
```

Error classes: `ValidationError` (400), `UnauthorizedError` (401), `ForbiddenError` (403), `NotFoundError` (404), `ConflictError` (409), `UnprocessableError` (422), `RateLimitError` (429), `ServerError` (5xx); and directly under `PaxosError`, with no status: `PaxosTimeoutError` (a request or a paginated iteration exceeded its allotted time) and `NetworkError` (transport failure with no HTTP response; `__cause__` preserved); both expose `request_id`, the most recent attempt built's `Paxos-Request-Id` (`None` if none), since the request may still have reached Paxos.

OAuth and token-endpoint failures are API errors (`AuthenticationError`, a `PaxosApiError`) carrying the real HTTP status.

Every `PaxosError` exposes `status` (`None` unless it is a `PaxosApiError`), `title`, `detail` and `request_id` (`None` when absent, as are `type`, `instance` and `AuthenticationError.code` on the errors that carry them, and `ResponseMetadata.request_id` and `ResponseMetadata.status_code` when no response was received; `status` is always an `int` on `PaxosApiError`), so they are safe to read on any SDK error. Go keeps `""`/`0`.

`paxos.is_api_error(err)` is a `TypeGuard[PaxosApiError]`: true for any API error, false for `NetworkError`, `PaxosTimeoutError` and non-SDK errors, so it guards `err.status` and `err.request_id`.

Errors follow the [RFC 7807](https://datatracker.ietf.org/doc/html/rfc7807) Problem Details standard. The SDK automatically retries on 429, 500, 502, 503 and 504 with exponential backoff (max 3 retries). HTTP 500, 502, 503 and 504 responses are retried for GET, HEAD, OPTIONS and DELETE, and for POST, PUT and PATCH requests on operations whose ref_id the SDK manages (create operations with a ref_id). Other POST, PUT and PATCH requests, including UpdateIdentity and UpdateAccount, are returned to the caller without a retry because the request may already have taken effect; check the resource's state before retrying such a call yourself.

## Pagination

Paginated `list_*` methods return iterators that automatically fetch pages. A few `list_*` methods return the whole response in one call instead (for example `profiles.list_profile_balances`, `limits.list_transfer_limits`, `pricing.list_prices` and `quotes.list_quotes`); check the method's return type. Query parameters use typed keyword arguments with IDE autocompletion:

```python
from datetime import datetime, timezone

for transfer in client.transfers.list_transfers(limit=10, profile_ids=["p_123"]):
    print(transfer.id, transfer.status)

# Dotted API params use underscores in Python (auto-remapped on the wire)
# created_at.lt -> created_at_lt in Python kwargs
for transfer in client.transfers.list_transfers(
    created_at_lt=datetime(2024, 1, 1, tzinfo=timezone.utc),
    limit=5,
):
    print(transfer.id, transfer.created_at)
```

Timestamp fields and query parameters are timezone-aware `datetime` values in UTC. A naive `datetime` raises `ValueError`.

Cursor management is automatic, and iteration always terminates — even if the server
returns a non-advancing cursor, or an empty page alongside a cursor.

`limit` controls page size, not the total number of results — it's re-sent unchanged on
every page. To bound the whole iteration instead, pass `max_items` and/or `max_duration`
via `request_options`:

```python
for transfer in client.transfers.list_transfers(
    request_options=paxos.RequestOptions(
        max_items=250, max_duration=10
    ),  # ~3 pages, or 10s
    limit=100,
    profile_ids=["p_123"],
):
    print(transfer.id)
```

A `max_duration` that elapses raises `PaxosTimeoutError` rather than silently returning a
partial result.

### Async Pagination

```python
async with paxos.AsyncClient(
    "your_client_id",
    "your_client_secret",
    sandbox=True,
    scopes=[Scope.TRANSFER_READ_TRANSFER],
) as client:
    async for transfer in client.transfers.list_transfers(limit=10):
        print(transfer.id, transfer.status)
```

### Pages

Every `list_*` result also exposes `pages()`, which yields one `Page` per fetched page with `items`, `next_cursor` (`None` on the last page) and that page's own `metadata` (`request_id`, `status_code`, `raw_body`). Pages are fetched lazily, with the same termination rules and `max_items`/`max_duration` limits as item iteration. A page trimmed by `max_items` reports `next_cursor=None`. Breaking out of `pages()` leaves the iterator open and resumable; call `close()` (`aclose()` in async code) to stop it. Nothing is held open between pages. An empty page is yielded once. A fetch error (after the client's normal retries) finishes the iterator; later calls make no requests.

Calling `pages()`, even without iterating it, locks that result to page mode, so mixing item iteration and `pages()` on one result raises `ValueError` (a closed iterator just ends instead). To resume later, stop after the pages you want and keep the last `next_cursor`; do not rely on `max_items` for that, because a page trimmed by it has no cursor.

```python
for page in client.transfers.list_transfers(limit=100, profile_ids=["p_123"]).pages():
    print(page.metadata.request_id, len(page.items), page.next_cursor)
    if page.next_cursor:
        saved_cursor = page.next_cursor
        break

resumed = client.transfers.list_transfers(
    limit=100, profile_ids=["p_123"], page_cursor=saved_cursor
)
```

Async clients use `async for page in client.transfers.list_transfers().pages()`.

## Raw JSON

Every typed response object returned or yielded by the SDK (each list item and each get/create/update result) has a `raw_json` property: its own JSON value from the response (a parsed `dict`), for passthrough or for fields the SDK does not model.

```python
transfer = client.transfers.get_transfer("txn_123")
payload = transfer.raw_json
for order in client.orders.list_orders():
    forward(order.raw_json)
```

`raw_json` is a deep copy, independent of the typed fields: mutating one never changes the other. It is parsed JSON, not wire bytes (numbers are re-parsed, duplicate keys are last-wins, whitespace is not preserved), and it is `None` on objects you construct yourself, on copies made with `copy`, `dataclasses.replace` or pickle. It never takes part in equality, `repr`, hashing or request bodies. `_raw_json` is a plain instance attribute, so it appears in `vars(obj)` and `typing.get_type_hints`; serialise with `dataclasses.asdict`, not `__dict__`. Only types the SDK returns or yields as a result or list item have `raw_json`; nested sub-objects never carry raw JSON (`raw_json` is `None`, or absent on types that are never returned at top level), and request bodies have none. The copy is made eagerly when the response is decoded, so later mutation of the typed object cannot leak into `raw_json`. Go returns each item's original bytes and Java returns compact JSON text.

## Decimal Handling

All monetary amounts in API responses are automatically converted to `decimal.Decimal`. Use `Decimal` for request bodies too -- the SDK serializes them to strings on the wire:

```python
from decimal import Decimal

# Decimal values in responses are already Decimal objects
transfer = client.transfers.get_transfer("txn_123")
print(type(transfer.amount))  # <class 'decimal.Decimal'>

# Use Decimal for safe arithmetic
fee = Decimal("0.001")
total = transfer.amount + fee
```

## Per-Request Options

Override client defaults for a single request. `call_timeout` defaults to 30 seconds
and shares one budget across authentication, token lock waits, HTTP attempts,
retry backoff, and complete response bodies. Optional `call_attempt_timeout`
limits each API or OAuth HTTP attempt; it defaults to no additional cap. Token
lock waits use the call budget. Omitting either setting inherits the client value;
`None` explicitly disables that cap. Overrides may increase or decrease defaults.
Pagination `max_duration` adds a separate budget across page fetches and consumer
pauses; the tighter budget wins.

Both sync and async clients cancel active HTTP I/O when the deadline expires,
including continuously trickling API success, error, and OAuth response bodies,
and raise `PaxosTimeoutError`. Sync clients own a lazy I/O thread and join it on
`close()`; use a context manager or close clients explicitly. Custom async
transports and async hooks must cooperate with cancellation. Sync hooks run on the
calling thread and cannot be forcibly interrupted; a late hook result cannot
extend the network budget.

```python
from paxos import RequestOptions

opts = RequestOptions(
    call_timeout=60,
    extra_headers={"X-Trace-Id": "trace-abc"},
)
transfer = client.transfers.get_transfer("txn_123", request_options=opts)
```

`RequestOptions`, `ResponseMetadata`, `Page` and `paxos.testing.RecordedRequest` take keyword arguments only.

## Request/Response Hooks

Register hooks for logging or metrics. Sync hooks are used with `Client`, async hooks with `AsyncClient`:

```python
def before(req):
    req.headers["X-Trace-Id"] = "trace-abc"


def after(req, resp):
    print(f"{req.method} {req.url} -> {resp.status_code}")


client = paxos.Client(
    client_id="your_client_id",
    client_secret="your_client_secret",
    before_request=before,
    after_response=after,
    scopes=[Scope.TRANSFER_READ_TRANSFER],
)

async_client = paxos.AsyncClient(
    client_id="your_client_id",
    client_secret="your_client_secret",
    before_request=async_before_hook,
    after_response=async_after_hook,
    scopes=[Scope.TRANSFER_READ_TRANSFER],
)
```

- Each hook runs once per HTTP attempt, including retries and the 401 token-refresh retry. The before hook runs before request signing; neither runs for the OAuth token request.
- The `before_request` hook may add headers, may override `Paxos-Request-Id`, and may return a replacement `httpx.Request` or `None`. It must not change the method, URL, body or the SDK-owned headers (`Authorization`, `Content-Type`, `Accept`, `Paxos-SDK-Language`, `Paxos-SDK-Version`, `Paxos-Signature`); if it does, or adds `Paxos-Signature`, the call raises `ValueError` and nothing is sent.
- The `after_response` hook runs for every attempt that received a response, before 401, retry and status handling, and not on network errors. The response body is already read, so `resp.text` and `resp.json()` are safe.
- An exception from either hook fails the call without retry.
- Each client has one hook of each kind.

## Request Signing

Request signing is configured per OAuth client. Setup follows the guide (https://docs.paxos.com/guides/developer/request-signing), which says request signing "must be activated by Paxos" and to contact Support (https://support.paxos.com). Credentials with the crypto-withdrawal scope also need Paxos Support to register the public key before signing works.

1. Generate a private key with OpenSSL 3 or later (check with `openssl version`; the macOS system `openssl` is LibreSSL and does not support Ed25519). For Ed25519 (EdDSA): `openssl genpkey -algorithm ed25519 -out private.pem`. For P-256 (ES256): `openssl ecparam -name prime256v1 -genkey -noout -out private.pem`
2. Derive the public key. For Ed25519: `openssl pkey -in private.pem -pubout -out public.pem`. For P-256: `openssl ec -in private.pem -pubout -out public.pem`
3. In the Dashboard, go to Developer > API, open the credential and choose Edit. Click "Add Public Key", enter a nickname, select the algorithm that matches your key (EdDSA or ES256), paste the contents of `public.pem`, click "Save Key", then save the credential with "Save API Credential".
4. Copy the Key ID (a UUID) shown on the saved public key.
5. Activate signing. For credentials without the crypto-withdrawal scope, turn on "Enable Request Signing" (available once the credential has a public key), save the credential, then contact Support to complete activation. For credentials with the crypto-withdrawal scope, contact Support to register the key with the signing stack, and turn on "Enable Request Signing" only after they confirm.
6. Configure the SDK with the private key and the Key ID (requires the optional `signing` extra: `pip install "paxos-sdk[signing]"`):

```python
import os
from pathlib import Path

client = paxos.Client(
    client_id=os.environ["PAXOS_CLIENT_ID"],
    client_secret=os.environ["PAXOS_CLIENT_SECRET"],
    signing_key=Path("private.pem").read_text(),
    key_id=os.environ["PAXOS_KEY_ID"],
    scopes=[Scope.TRANSFER_READ_TRANSFER],
)
```

The options are `signing_key` and `key_id`; pass both together. `paxos.AsyncClient` takes the same options. The private key can be the PEM file contents as written by step 1 (an unencrypted PKCS#8 `-----BEGIN PRIVATE KEY-----` block for either key type, or an unencrypted SEC1 `-----BEGIN EC PRIVATE KEY-----` block for P-256) or, for Ed25519 only, 128 hex characters (the 32-byte seed followed by the matching 32-byte public key). Pass the PEM exactly as openssl writes it (multi-line, with the BEGIN and END lines); reformatted PEM, such as a single line with spaces, may be rejected. Load it from a file or a secret store (keep its newlines if it comes from an environment variable); do not put key literals in source. Encrypted PEM is rejected: decrypt it first. Whatever the format, an invalid key raises `ValueError`.

The SDK supports Ed25519 (EdDSA) and P-256 (ES256) keys and picks the algorithm from the key; other key types and curves are rejected.

Only API requests are signed; OAuth token requests are not. Each signed request carries a JWS in the `Paxos-Signature` header covering the method, the full transmitted path (including the `/v2` prefix), the exact serialized query string and the body bytes. For example, a boolean query is signed as `include_deactivated=true`, exactly as HTTPX sends it. Signing runs after `before_request`, so it covers the final request.

Once signing is enforced for the credential, unsigned or mis-signed requests are rejected with HTTP 401, surfaced as `paxos.UnauthorizedError` with `request_id`. Quote the request ID when contacting Support.

## Debug Logging

Enable debug output with the `PAXOS_LOG_LEVEL` environment variable:

```bash
PAXOS_LOG_LEVEL=debug python my_app.py
```

Or provide a custom `logging.Logger`:

```python
import logging

logger = logging.getLogger("paxos")
logger.setLevel(logging.DEBUG)

client = paxos.Client(
    client_id="your_client_id",
    client_secret="your_client_secret",
    logger=logger,
    scopes=[Scope.TRANSFER_READ_TRANSFER],
)
```

The explicit logger takes precedence over `PAXOS_LOG_LEVEL`.

Debug logging records the method, path, status, request ID, timing and retry attempt, never request or response bodies.

## Async Client

Use `AsyncClient` for async/await support. Its services expose asynchronous methods
with the same names as the synchronous methods on `Client`. Await requests and
use `async for` for paginated lists. The client supports the async context manager
protocol:

```python
import paxos

async with paxos.AsyncClient(
    client_id="your_client_id",
    client_secret="your_client_secret",
    sandbox=True,
    scopes=[Scope.TRANSFER_READ_TRANSFER],
) as client:
    transfer = await client.transfers.get_transfer("txn_123")
    print(transfer.id, transfer.status)

    async for t in client.transfers.list_transfers(limit=10):
        print(t.id)
```

The clients expose separate service classes: `Client` uses synchronous services
and `AsyncClient` uses asynchronous services. Neither exposes the other mode.
For example, `client.profiles` is a `ProfilesService` on `Client` and an
`AsyncProfilesService` on `AsyncClient`.

## Thread Safety

`Client` can be shared across threads. Share an `AsyncClient` only among tasks
on the same event loop; create a separate client for each loop/thread. Do not
reuse an async client across successive `asyncio.run()` calls. Close clients with
`with Client(...)` or `async with AsyncClient(...)` when their application lifetime ends.

## Using with fork / gunicorn / Celery prefork

- The default `Client` is safe across `fork()`: its I/O loop, thread and connection pool are rebuilt lazily in the child.
- A `Client` built with a custom `transport=` cannot be used in a forked child: it raises `PaxosError`. Create a new `Client` in the child.
- Creating the `Client` after the fork (for example in a post-fork hook) is always safe.
- In a forked child with no proxy settings cached from the parent, the client uses environment-variable proxies only (`HTTPS_PROXY`, `NO_PROXY` and so on) and skips the macOS system proxy lookup, which can crash after `fork()`.

## Response Metadata

Capture metadata from typed service methods using a fresh holder for each call:

```python
metadata = paxos.ResponseMetadata()
try:
    transfer = client.transfers.get_transfer(
        "txn_123",
        request_options=paxos.RequestOptions(response_metadata=metadata),
    )
finally:
    print(metadata.request_id, metadata.status_code)
```

Metadata records the terminal HTTP response, including API errors. It is empty
when no terminal API response exists. Do not share holders across concurrent
calls; pagination overwrites the holder per page, so after an auto-paginated call it reflects the final page only; a hook captures every page. See the
[developer guide](https://docs.paxos.com/sdks).

## Request Bodies

Empty lists and empty map fields are omitted from request bodies; empty objects for nested model fields are sent as given.

## Reference IDs

For operations that take a `ref_id`, the SDK fills an omitted `ref_id` with a UUID once per method call and reuses it across internal retries. Set it yourself to persist it before submission.

For a passthrough or BFF, forward the unmodified JSON of a call from
`metadata.raw_body` (`bytes`, set for every received response, `b""` for an empty body) instead of re-serializing the typed model:

```python
metadata = paxos.ResponseMetadata()
client.transfers.get_transfer(
    "txn_123",
    request_options=paxos.RequestOptions(response_metadata=metadata),
)
body = metadata.raw_body
```

## Requirements

- Python 3.11 or later
- httpx

## License

[Apache 2.0](LICENSE)
