Metadata-Version: 2.4
Name: iteradian-rpc
Version: 1.2.0
Summary: Official Iteradian Control Plane SDK for Python
License: MIT
Project-URL: Homepage, https://iteradian.com
Keywords: iteradian,iteradian-rpc,rpc,blockchain,api,sdk,web3
Classifier: Development Status :: 4 - Beta
Classifier: Typing :: Typed
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
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: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.25.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"

<p align="center">
  <h1 align="center">Iteradian Python SDK</h1>
  <p align="center">Official Python client library for the Iteradian Control Plane API</p>
</p>

<p align="center">
  <img src="https://img.shields.io/badge/language-Python-3776AB?style=flat-square&logo=python&logoColor=white" alt="Python" />
  <img src="https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11%20%7C%203.12-blue?style=flat-square&logo=python&logoColor=white" alt="Python Versions" />
  <img src="https://img.shields.io/badge/version-1.2.0-green?style=flat-square" alt="Version" />
  <img src="https://img.shields.io/badge/license-MIT-blue?style=flat-square" alt="License" />
  <img src="https://img.shields.io/badge/pypi-iteradian--rpc-blue?style=flat-square&logo=pypi&logoColor=white" alt="PyPI" />
  <img src="https://img.shields.io/badge/deps-httpx-orange?style=flat-square" alt="httpx" />
</p>

---

## Closing the client

The client holds a pooled HTTP connection. Close it when you are done, or use it
as a context manager:

```python
from iteradian_rpc import IteradianClient

with IteradianClient(api_key="itrd_live_...") as client:
    result = client.rpc.call("tao-mainnet", {
        "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1,
    })

# or, without the context manager:
client = IteradianClient(api_key="itrd_live_...")
try:
    ...
finally:
    client.close()
```

Not closing it leaks sockets in a process that creates clients repeatedly.

## Errors and retries

Every failure raises `IteradianError`. On a gateway call it also carries the
JSON-RPC detail:

```python
from iteradian_rpc.exceptions import IteradianError

try:
    client.rpc.call("tao-mainnet", request)
except IteradianError as err:
    if err.is_rate_limited:          # -32005
        ...                          # wait err.retry_after seconds
    elif err.is_daily_limit_reached: # -32008
        ...                          # this key's daily limit; err.data["resetsAt"]
    elif err.is_quota_exhausted:     # -32006 / -32007
        ...                          # retrying will not help; see err.data
```

The SDK retries 5xx and `-32005`. It never retries `-32006` or `-32007`, which
do not recover until the billing period rolls over, nor `-32008` (per-key daily
limit), which does not recover until `error.data.resetsAt` (next 00:00 UTC), and it never retries a
request whose JSON-RPC method submits a transaction. Redirects are not
followed: a 3xx raises `IteradianError` rather than resending your API key to
another origin.

## Features

- **Modern HTTP client** — powered by a pooled, synchronous [httpx](https://www.python-httpx.org/) `Client` (the SDK has no async/await API)
- **Automatic retry** — exponential backoff on 429 / 5xx responses (configurable max retries)
- **Resource-based API** — clean `client.auth`, `client.organizations`, `client.endpoints` access pattern
- **Full API coverage** — Auth, Organizations, API Keys, Endpoints, Usage, Dashboard, Alerts, Logs, Subscriptions, Plans, Support, RPC gateway
- **Typed signatures** — methods carry type hints; responses are returned as plain `dict`s parsed from JSON
- **Configurable** — timeout, retry count, and base URL
- **Dual auth** — supports both Bearer tokens and API key authentication
- **Context manager** — use `with` statements for automatic resource cleanup

## Requirements

- **Python 3.8** or later
- **httpx** >= 0.25.0

## Installation

```bash
pip install iteradian-rpc
```

Or with a specific version:

```bash
pip install iteradian-rpc==1.2.0
```

## Quick Start

```python
from iteradian_rpc import IteradianClient

client = IteradianClient(base_url="https://api.iteradian.com/api/v1")

# Login: the access token is stored on the client automatically
tokens = client.auth.login("user@example.com", "password123")
if tokens.get("requires2FA"):
    # The account has 2FA: no tokens yet. Sign in again with a code.
    tokens = client.auth.login("user@example.com", "password123", two_factor_code="123456")
print(f"Logged in as {tokens['user']['email']}")

# List organizations
orgs = client.organizations.list()
for org in orgs:
    print(f"  {org['name']} ({org['slug']})")

if orgs:
    org_id = orgs[0]["id"]

    # List endpoints
    for ep in client.endpoints.list(org_id):
        print(f"  {ep['name']}: {ep['status']} ({ep['region']})")

    # Create an API key: the secret is shown once
    key = client.api_keys.create(org_id, name="Production Key", environment="live")
    print(f"Created key {key['prefix']}, secret {key['secret']}")

    # Query logs
    logs = client.logs.query(org_id, limit=20)
    print(f"Total logs: {logs['total']}")

# Cleanup
client.close()
```

### Using API Key Authentication

```python
client = IteradianClient(
    base_url="https://api.iteradian.com/api/v1",
    api_key="itrd_live_abc123..."
)

result = client.rpc.call("eth-mainnet", {
    "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1,
})
```

An API key authenticates gateway calls (`client.rpc`) only; control-plane
methods need a signed-in access token.

### Context Manager

```python
from iteradian_rpc import IteradianClient

with IteradianClient(base_url="https://api.iteradian.com/api/v1") as client:
    client.auth.login(email="user@example.com", password="password123")
    orgs = client.organizations.list()
    # client.close() is called automatically
```

### Configuration Options

```python
client = IteradianClient(
    base_url="https://api.iteradian.com/api/v1",
    timeout=60.0,       # Request timeout in seconds (default: 30.0)
    retry=True,         # Retry 5xx and rate limits (default: True)
    max_retries=5,      # Max attempts on 429/5xx (default: 3)
)
```

## API Reference

### Resource Accessors

| Resource               | Type                     | Description                         |
| ---------------------- | ------------------------ | ----------------------------------- |
| `client.auth`          | `_AuthResource`          | Authentication & account management |
| `client.organizations` | `_OrganizationsResource` | Organization CRUD & members         |
| `client.api_keys`      | `_ApiKeysResource`       | API key management                  |
| `client.endpoints`     | `_EndpointsResource`     | Endpoint & network management       |
| `client.usage`         | `_UsageResource`         | Usage analytics                     |
| `client.dashboard`     | `_DashboardResource`     | Dashboard data & health             |
| `client.alerts`        | `_AlertsResource`        | Alert management & rules            |
| `client.logs`          | `_LogsResource`          | Request log querying                |
| `client.subscriptions` | `_SubscriptionsResource` | Subscription & billing              |
| `client.plans`         | `_PlansResource`         | Plan catalog                        |
| `client.support`       | `_SupportResource`       | Support ticket management           |
| `client.rpc`           | `_RpcResource`           | JSON-RPC gateway calls              |

### Authentication (`client.auth`)

```python
# Login (token set automatically). With 2FA on and no code the result is
# {"requires2FA": True, "requires_2fa": True} and the stored token is untouched.
tokens = client.auth.login(email="...", password="...")
tokens = client.auth.login(email="...", password="...", two_factor_code="123456")
tokens = client.auth.login(email="...", password="...", backup_code="...")

# Register — does NOT sign in. Returns {"message", "email"} and emails a
# confirmation link; log in once the address is confirmed.
# accepted_terms is required: pass True only after the user agreed to the
# Terms of Service, Privacy Policy and DPA (https://iteradian.com/terms,
# /privacy, /dpa). The server rejects registration (400) otherwise.
result = client.auth.register(email="...", password="...", accepted_terms=True)

# Email verification and password reset
client.auth.verify_email(token="...")
client.auth.resend_verification(email="user@example.com")
client.auth.forgot_password(email="user@example.com")
client.auth.reset_password(token="...", new_password="...")

# Refresh token
tokens = client.auth.refresh(refresh_token="...")

# Logout
client.auth.logout()

# Two-Factor Authentication
setup = client.auth.enable_2fa(password="...")
print(f"Secret: {setup['secret']}")
print(f"QR Code: {setup['qrCode']}")
codes = client.auth.verify_2fa(code="123456")   # {"backupCodes": [...]}
codes = client.auth.regenerate_backup_codes(password="...")
client.auth.disable_2fa(password="...", code="123456")

# Magic link
client.auth.request_magic_link(email="user@example.com")
tokens = client.auth.login_with_magic_link(token="...")  # also takes two_factor_code / backup_code
```

### Organizations (`client.organizations`)

```python
# CRUD. plan_id and accepted_terms are required by the server;
# slug and billing_interval ("month" | "year") are optional.
orgs = client.organizations.list()
org = client.organizations.create(
    name="My Org", plan_id="plan_free", accepted_terms=True, slug="my-org"
)
org = client.organizations.get(org_id)
org = client.organizations.update(org_id, name="New name")
perms = client.organizations.get_my_permissions(org_id)  # {"role", "permissions", ...}
client.organizations.leave(org_id)
client.organizations.delete(org_id)

# Members
members = client.organizations.list_members(org_id)
client.organizations.update_member_role(org_id, member_id, "viewer")
client.organizations.remove_member(org_id, member_id)

# Invitations — inviting creates a pending invite; the invitee becomes a
# member only after accepting it (signed in, verified email).
invite = client.organizations.invite_member(org_id, email="user@example.com", role="developer")
# {"id": ..., "email": ..., "role": "developer", "status": "pending", "expiresAt": ..., ...}
open_invites = client.organizations.list_invites(org_id)
client.organizations.revoke_invite(org_id, invite["id"])

# As the invitee
mine = client.organizations.list_my_invites()  # {"emailVerified": ..., "invites": [...]}
client.organizations.accept_invite(mine["invites"][0]["id"])  # or decline_invite()
# A user who has not accepted the current terms version gets 403
# (TERMS_ACCEPTANCE_REQUIRED); once they agree, accept with:
client.organizations.accept_invite(mine["invites"][0]["id"], accepted_terms=True)
```

### API Keys (`client.api_keys`)

```python
keys = client.api_keys.list(org_id)
key = client.api_keys.create(org_id, name="Key Name", environment="live")
print(key["secret"])   # shown once; key["key"] holds the same value (deprecated alias)
key = client.api_keys.get(org_id, key["id"])
client.api_keys.update(org_id, key["id"], name="Renamed", rate_limit=100)
new_key = client.api_keys.rotate(org_id, key["id"])   # new_key["secret"]
analytics = client.api_keys.get_analytics(org_id, key["id"], time_range="30d")
client.api_keys.revoke(org_id, key["id"])
```

`create` also takes `ip_allowlist`, `allowed_networks`, `rate_limit`,
`daily_limit`, `expires_at` and `wallet_url_auth`.

### Endpoints (`client.endpoints`)

```python
# Networks
networks = client.endpoints.get_networks()
network = client.endpoints.get_network(network_id)

# Endpoint management. region: eu_central, us_east, us_central, us_west, uk,
# asia_southeast, asia_east, australia, india (eu_west and asia_south still work).
endpoints = client.endpoints.list(org_id)
endpoint = client.endpoints.create(org_id, name="...", network_id="...", region="us_east")
endpoint = client.endpoints.update(org_id, endpoint_id, name="renamed", priority=2)
endpoint = client.endpoints.pause(org_id, endpoint_id)
endpoint = client.endpoints.resume(org_id, endpoint_id)
client.endpoints.update_priorities(org_id, [{"id": endpoint_id, "priority": 1}])
client.endpoints.delete(org_id, endpoint_id)

# Health and metrics
check = client.endpoints.check_health(org_id, endpoint_id)   # runs a check now (POST)
health = client.endpoints.get_health(org_id, endpoint_id)    # last recorded (GET)
summary = client.endpoints.get_summary(org_id)
metrics = client.endpoints.get_metrics(org_id, endpoint_id)
metrics = client.endpoints.get_metrics(
    org_id, endpoint_id, from_time="2030-01-01T00:00:00Z", to_time="2030-01-01T06:00:00Z"
)
```

### Usage (`client.usage`)

```python
rows = client.usage.get(org_id, from_date="2030-01-01", to_date="2030-01-31")  # list of rows
summary = client.usage.get_summary(org_id)
```

### Dashboard (`client.dashboard`)

`time_range` is `last_hour`, `last_24_hours` (default), `last_7_days` or
`last_30_days`. The short forms `1h`, `24h`, `7d`, `30d` are translated.

```python
data = client.dashboard.get(org_id, time_range="7d")
health = client.dashboard.get_health(org_id)
stats = client.dashboard.get_quick_stats(org_id, time_range="24h")
rate = client.dashboard.get_request_rate(org_id)
errors = client.dashboard.get_error_rate(org_id)
latency = client.dashboard.get_latency(org_id)
performance = client.dashboard.get_performance(org_id)
```

### Alerts (`client.alerts`)

```python
# Fired alerts, as a plain list. Filters: status, type, severity, limit, offset.
alerts = client.alerts.list(org_id)
client.alerts.acknowledge(org_id, alert_id)
client.alerts.resolve(org_id, alert_id)
client.alerts.evaluate(org_id)

# Alert rules. type: high_error_rate, high_latency, rate_limit_exceeded,
# quota_warning, service_down, key_expiring, unusual_traffic.
# severity: info, warning, error, critical. cooldown_seconds is at least 60.
rules = client.alerts.list_rules(org_id)
rule = client.alerts.create_rule(
    org_id,
    name="High error rate",
    type="high_error_rate",
    config={"threshold": 5},
    severity="warning",
    is_enabled=True,
    cooldown_seconds=900,
)
rule = client.alerts.get_rule(org_id, rule["id"])
client.alerts.update_rule(org_id, rule["id"], name="Renamed")
client.alerts.toggle_rule(org_id, rule["id"])
client.alerts.seed_defaults(org_id)
client.alerts.delete_rule(org_id, rule["id"])

# Channels. type: email ({"recipients": [...]}), webhook ({"url": ..., "secret": ...}),
# slack ({"webhookUrl": ...}).
channels = client.alerts.list_channels(org_id)
channel = client.alerts.create_channel(
    org_id, name="Ops hook", type="webhook", config={"url": "https://example.com/hook"}
)
client.alerts.get_channel(org_id, channel["id"])
client.alerts.update_channel(org_id, channel["id"], name="Renamed", is_enabled=False)
client.alerts.test_channel(org_id, channel["id"])   # {"success", "message"}
client.alerts.delete_channel(org_id, channel["id"])
```

### Logs (`client.logs`)

```python
# Query logs with filters. status: success, error, timeout, throttled.
# sort_by: timestamp, latencyMs, statusCode. limit is 1 to 200.
result = client.logs.query(
    org_id,
    limit=50,
    offset=0,
    status="error",
    method="eth_call",
    network="ethereum",
    from_time="2030-01-01T00:00:00Z",
    sort_by="timestamp",
    sort_order="desc",
)
print(f"{len(result['logs'])} of {result['total']}")
for log in result["logs"]:
    print(f"  [{log['status']}] {log['method']} ({log['latencyMs']}ms)")
```

Also accepted: `api_key_id`, `region`, `search`, `status_code`,
`min_latency_ms`, `max_latency_ms` and `to_time`.

```python
# Get single log
log = client.logs.get(org_id, log_id)

# Available filter options
filters = client.logs.get_filter_options(org_id)

# Log stats
stats = client.logs.get_stats(org_id)
```

### Subscriptions (`client.subscriptions`)

```python
sub = client.subscriptions.get(org_id)
# accepted_terms is required: the caller confirms the user accepted the
# plan-change billing terms. The server rejects the change unless it is True.
sub = client.subscriptions.change_plan(org_id, plan_id="pro", accepted_terms=True)
sub = client.subscriptions.cancel(org_id)
sub = client.subscriptions.reactivate(org_id)
invoices = client.subscriptions.get_invoices(org_id)
```

### Plans (`client.plans`)

```python
plans = client.plans.list()
plan = client.plans.get(plan_id)
```

### Support (`client.support`)

```python
# category: general, billing, technical, api_keys, endpoints, performance,
# security, feature_request, bug_report. priority: low, medium, high, urgent.
# subject is 5 to 200 characters, body 10 to 5000.
ticket = client.support.create_ticket(
    org_id,
    subject="API returning 500 errors",
    body="Detailed description of what happens...",
    category="technical",
    priority="high",
)
tickets = client.support.list_tickets(org_id)        # plain list
stats = client.support.get_stats(org_id)
ticket = client.support.get_ticket(org_id, ticket["id"])
client.support.add_message(org_id, ticket["id"], content="Follow-up message...")
client.support.update_status(org_id, ticket["id"], "resolved")
```

### RPC gateway (`client.rpc`)

```python
gateway = IteradianClient(api_key="itrd_live_...")
networks = gateway.rpc.networks()
request = {"jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1}
result = gateway.rpc.call("eth-mainnet", request)
results = gateway.rpc.batch("eth-mainnet", [request, {**request, "id": 2}])
```

## Data Types

Responses are plain `dict`s and `list`s. The dataclasses in
`iteradian_rpc/types.py` describe them for callers who want attribute access:
`Endpoint.from_dict(payload)`. Every field is optional, unknown keys are
ignored, and numbers that arrive as strings (`avgLatencyMs`, `priceMonthly`,
`successRate`, `uptime`) are converted, so decoding a real response does not
fail.

| Type              | Key Fields |
| ----------------- | ---------- |
| `IteradianConfig` | `base_url`, `gateway_url`, `access_token?`, `api_key?`, `timeout`, `retry`, `max_retries` |
| `AuthTokens`      | `access_token?`, `refresh_token?`, `user?`, `requires_2fa` |
| `TwoFASetup`      | `secret`, `qr_code` |
| `Organization`    | `id`, `name`, `slug`, `role`, `subscription?`, `members?` |
| `OrgMember`       | `id`, `user_id`, `email`, `role`, `joined_at` |
| `OrgInvite`       | `id`, `email`, `role`, `status`, `expires_at`, `invited_by` |
| `ApiKey`          | `id`, `name`, `prefix`, `secret?` (`key` is a deprecated alias), `environment`, `status`, `ip_allowlist`, `allowed_networks`, `rate_limit`, `daily_limit`, `wallet_url_auth` |
| `Network`         | `id`, `name`, `type`, `environment`, `chain_id`, `native_currency`, `is_active`, `available_nodes` |
| `Endpoint`        | `id`, `organization_id`, `network_id`, `name`, `region`, `priority`, `status`, `is_enabled`, `timeout_ms`, `retry_count`, `avg_latency_ms`, `success_rate`, `uptime` |
| `HealthCheck`     | `status`, `latency_ms`, `checked_at` |
| `UsageRow`        | `date`, `requests`, `errors`, `throttled`, `avg_latency_ms`, `key_name`, `key_prefix` |
| `RequestLog`      | `id`, `method`, `path`, `network`, `region`, `status`, `status_code`, `latency_ms`, `error_code`, `api_key_id`, `timestamp` |
| `LogsResponse`    | `logs`, `total`, `stats` |
| `Alert`           | `id`, `rule_id`, `type`, `severity`, `status`, `title`, `message`, `fired_at`, `acknowledged_at`, `resolved_at` |
| `AlertRule`       | `id`, `name`, `type`, `severity`, `is_enabled`, `config`, `cooldown_seconds` |
| `AlertChannel`    | `id`, `name`, `type`, `is_enabled`, `config` |
| `Plan`            | `id`, `name`, `tier`, `display_name`, `price_monthly`, `price_annual`, `limits`, `features`, `is_active` |
| `Subscription`    | `id`, `status`, `billing_interval`, `current_period_start`, `current_period_end`, `cancel_at_period_end`, `plan` |
| `SupportTicket`   | `id`, `organization_id`, `subject`, `category`, `priority`, `status`, `messages?` |

## Error Handling

```python
from iteradian_rpc import IteradianClient, IteradianError

client = IteradianClient(base_url="https://api.iteradian.com/api/v1")

try:
    client.auth.login(email="user@example.com", password="wrong")
except IteradianError as e:
    print(f"Status: {e.status_code}")   # 401
    print(f"Message: {e.message}")      # "Invalid credentials"
    print(f"Error: {e.error}")          # Error detail
```

`IteradianError` is the only exception the SDK raises. That covers HTTP
errors, validation errors (a list of messages is joined with ", "), network
failures (`error == "NETWORK_ERROR"`), timeouts (`"TIMEOUT"`) and responses
that cannot be decoded (`"DECODE_ERROR"`).

### Terms acceptance (403 `TERMS_ACCEPTANCE_REQUIRED`)

After Iteradian publishes a new version of the Terms of Service, Privacy
Policy or DPA, any write (POST/PUT/PATCH/DELETE) made with a user JWT may
raise `IteradianError` with `status_code` 403 until the user accepts the new
version in the dashboard (the response body carries
`code: "TERMS_ACCEPTANCE_REQUIRED"`, `termsVersion` and `termsUrl`). API keys
and agent tokens are unaffected. `organizations.accept_invite(invite_id,
accepted_terms=True)` records the acceptance as part of joining.

### Retry Behavior

The SDK automatically retries requests on:

- **429 Too Many Requests** — with exponential backoff
- **5xx Server Errors** — with exponential backoff

Configure via `max_retries` (default: 3):

```python
client = IteradianClient(
    base_url="...",
    max_retries=5,   # Up to 5 attempts
)
```

## Project Structure

```
sdks/python/
├── pyproject.toml           # Package metadata & build config
├── README.md                # This file
└── iteradian_rpc/
    ├── __init__.py          # Package exports
    ├── client.py            # IteradianClient & all resource classes (407 lines)
    ├── http.py              # HttpClient — httpx, retry, timeouts (107 lines)
    ├── exceptions.py        # IteradianError exception class
    └── types.py             # Dataclass types (235 lines)
```

## License

MIT © [Iteradian](https://iteradian.com)

## RPC gateway, rate limits and quotas

The RPC gateway is a **different host** from the control-plane API:

| Surface | Base URL |
| --- | --- |
| Control plane | `https://api.iteradian.com/api/v1` |
| RPC gateway | `https://rpc.iteradian.com` |

This SDK takes both, and defaults the gateway to `https://rpc.iteradian.com`.

- A **batch of N calls costs N** against your per-second rate limit and your
  monthly quota. Batching saves round trips, not allowance.
- Limits are **per subscription**, aggregated over every API key your
  organization holds. Creating more keys does not raise them.
- The gateway returns HTTP 429 with a JSON-RPC error body:
  `-32005` rate limited (retry after `error.data.retryAfter`), `-32006` monthly
  quota exhausted, `-32007` overage spend cap reached, `-32008` the API key's
  own daily limit reached (`error.data = { dailyLimit, used, cost, resetsAt }`).
  None of the last three recover before `resetsAt` (the billing period roll-over,
  or the next 00:00 UTC for `-32008`), so retrying them is wasted work.

Plans (defaults; an admin can change them): Free 25 rps / 3M per month with no
overage (requests stop at the quota, no card needed), Developer 100 rps / 5M
with overage at $6 per million, Professional 500 rps / 30M at $4.50 per million,
Dedicated per contract from $4 per million. Trials are offered on Developer
only; a trial that ends unpaid falls back to Free. See `sdks/SDK_CONTRACT.md`
for the full table.

### WebSocket

The gateway also serves JSON-RPC over WebSocket at
`wss://rpc.iteradian.com/ws/v1/{network}`. This SDK does not wrap it on
purpose: connect with any WebSocket client, such as web3.py's `WebSocketProvider` (web3.py 7) or the
`websockets` package. Authenticate with the
`X-Api-Key` header, `Authorization: Bearer <key>`, or `?apiKey=<key>` on the
URL (browsers cannot set headers on a WebSocket).

```python
import asyncio
from web3 import AsyncWeb3, WebSocketProvider

URL = "wss://rpc.iteradian.com/ws/v1/eth-mainnet?apiKey=itrd_live_..."

async def main():
    async with AsyncWeb3(WebSocketProvider(URL)) as w3:
        await w3.eth.subscribe("newHeads")
        async for payload in w3.socket.process_subscriptions():
            print("new head", payload["result"]["number"])

asyncio.run(main())
```

- Each message you send is charged like an HTTP request (a batch of N costs N).
  Subscription notifications pushed to you are not charged.
- A message refused by a limit gets an ordinary JSON-RPC error under that
  call's `id`, with the same codes as above (`-32005` to `-32008`). The socket
  stays open.
- An organization can hold `max(5, floor(concurrency / 4))` streams at once;
  past that the upgrade is refused with HTTP 429. Other upgrade failures: 400
  bad path, 401/403 bad key, 404 unknown network, 503 no WebSocket-capable node.
- Close code `1012` means the upstream node restarted: reconnect and
  re-subscribe. `4003` means the key was revoked or the organization suspended
  (keys are re-checked every 60 s): do not reconnect.
- The server pings every 30 s. Messages are limited to 1 MB.
