Skip to main content

Python SDK for peaqOS, the operating system for the machine economy — on-chain identity, credit rating, and omnichain infrastructure for robots and machines.

Project description

peaq-os-sdk

Python SDK for the peaqOS protocol. Provides a typed wrapper around the peaq on-chain capabilities so integrators can onboard machines, submit events, mint NFTs, and query credit ratings without writing raw web3.py boilerplate.


Install

pip install peaq-os-sdk

Dependencies installed automatically: web3, eth-account, requests, posthog.

For OWS wallet management (optional):

pip install peaq-os-sdk[ows]

Requirements

  • Python >= 3.10
  • A peaq RPC endpoint
  • A funded wallet for the proxy operator (or for the machine itself, in self-managed mode)

Quick start

from peaq_os_sdk import PeaqosClient

client = PeaqosClient(
    rpc_url="https://peaq.api.onfinality.io/public",
    private_key="0xYOUR_PRIVATE_KEY",
    identity_registry="0x...",
    identity_staking="0x...",
    event_registry="0x...",
    machine_nft="0x...",
    did_registry="0x...",
    batch_precompile="0x...",
)

print("signer address:", client.address)

PeaqosClient is the only class consumers instantiate. All feature methods hang off it. The constructor performs synchronous validation and wires up the underlying Web3 provider + signing account — no network I/O is issued at construction time.

Read More here >>


MCR queries

Three read-only methods talk to the off-chain MCR API server at client.api_url (override via the api_url kwarg or PEAQOS_MCR_API_URL; defaults to http://127.0.0.1:8000). All three validate the DID prefix (did:peaq:0x…) locally and share a single requests.Session for connection pooling.

Method HTTP endpoint Returns
client.query_mcr(did) GET /mcr/{did} MCRResponse TypedDict
client.query_machine(did) GET /machine/{did} MachineProfileResponse (NFT metadata JSON v1.0 as dict[str, Any])
client.query_operator_machines(did) GET /operator/{did}/machines OperatorMachinesResponse

MCRResponse:

{
    "did": str,
    "machine_id": int,
    "mcr_score": int | None,    # 0–100, None if Provisioned
    "mcr": str,                 # "AAA" | "AA" | "A" | "BBB" | "BB" | "B" | "NR" | "Provisioned"
    "bond_status": str,         # "bonded" | "unbonded"
    "negative_flag": bool,      # active negative event flag
    "event_count": int,
    "revenue_event_count": int,
    "activity_event_count": int,
    "revenue_trend": str,       # "up" | "stable" | "down" | "insufficient"
    "total_revenue": float,
    "average_revenue_per_event": float,
    "last_updated": int | None,
}

OperatorMachinesResponse carries operator_did, a machines list of {did, machine_id, mcr_score, mcr, negative_flag} entries, and a pagination object. MachineProfileResponse returns structured NFT metadata with a validated peaqos sub-object. Every failure path is an ApiError with a stable .code (NOT_FOUND, SERVICE_UNAVAILABLE, SERVER_ERROR, HTTP_ERROR, BAD_RESPONSE, TIMEOUT, NETWORK_ERROR). See docs/03_QUERIES.md for the full endpoint and error reference.


Smart account deployment

ERC-4337 smart accounts are provisioned via the MachineAccountFactory contract using CREATE2 — the deployed address is deterministic from (owner, machine, daily_limit, salt), so the same tuple always resolves to the same address.

Method On-chain Returns
client.get_smart_account_address(owner, machine, daily_limit, salt) view call — no gas predicted address
client.deploy_smart_account(owner, machine, daily_limit, salt) createAccount tx deployed address

Because CREATE2 is deterministic, predicted == deployed for the same inputs — callers can preview the address, pre-fund it, or display it in a UI before paying gas. Configure the factory address via the optional machine_account_factory kwarg on PeaqosClient or the MACHINE_ACCOUNT_FACTORY_ADDRESS env var. See docs/04_SMART_ACCOUNTS.md for parameter rules and receipt-decoding error codes.


Cross-chain NFT bridging

Machine NFTs move between peaq and Base over LayerZero v2. Two chains are recognised today; direction is inferred from the source / destination arguments.

Chain SUPPORTED_CHAINS id LAYERZERO_EIDS
"peaq" 3338 30302
"base" 8453 30184
Direction Source contract Effect dstEid
peaq → base MachineNFTAdapter on peaq NFT locked on peaq, minted on Base 30184
base → peaq MachineNFTBase on Base NFT burned on Base, unlocked on peaq 30302

client.bridge_nft(...) estimates the LayerZero messaging fee via quoteSend before broadcasting and attaches that fee as msg.value on the actual send transaction so the message is correctly paid for. PeaqosClient.wait_for_bridge_arrival(...) is a static method (no client instance needed) that polls MachineNFT.ownerOf(token_id) on the destination every 10 seconds and returns True on arrival or False at timeout (default 300 s). See docs/05_BRIDGE.md for the full walkthrough including options handling, Base-source setup, and the complete error-code table.


Telemetry

The SDK collects anonymous, aggregate usage telemetry via PostHog to measure install counts, onboarding success rates, and MCR query volume. No PII is collected — GeoIP is disabled, IP addresses are nulled, and all UUIDs are randomly generated.

Telemetry is enabled by default and can be disabled via environment variables:

Env var Effect
DO_NOT_TRACK=1 Disables telemetry unconditionally (industry standard)
PEAQOS_TELEMETRY=0 Disables telemetry (project-specific toggle)

DO_NOT_TRACK=1 always takes precedence. When telemetry is disabled, no PostHog client is created and no events are sent.

Analytics events are captured automatically from existing SDK methods — no additional API calls are needed:

client = PeaqosClient(...)                         # peaqos_sdk_initialize (first install only)
addr, key = PeaqosClient.generate_keypair()        # peaqos_sdk_generate_keypair (via active instance)
machine_id = client.register_machine()             # peaqos_sdk_generate_wallet
tx = client.write_machine_did_attributes(...)      # peaqos_sdk_generate_did
tx = client.mint_nft(machine_id, addr)             # peaqos_sdk_generate_nft
mcr = client.query_mcr("did:peaq:0x...")           # peaqos_sdk_mcr_request
client.close()                                     # flush queued events

All analytics calls are fire-and-forget — they never block or raise. See docs/10_ANALYTICS.md for the full event reference and privacy details.


Documentation

Per-feature deep-dives live under docs/:

  • Quick Start — client initialization, configuration, environment variables, types, exception classes, validation, utilities, and constants.
  • Machine identity & registration — faucet 2FA enrollment, gas-station funding, self-managed and proxy-managed registration. Includes the full faucet error reference and the on-chain revert mapping.
  • MCR queriesquery_mcr, query_machine, query_operator_machines, response shapes, rating tiers, and the full HTTP error-code table.
  • Smart account deploymentdeploy_smart_account and get_smart_account_address, CREATE2 determinism, parameter rules, and receipt-decoding error codes.
  • Cross-chain NFT bridgingbridge_nft direction handling (peaq ↔ Base via LayerZero v2), supported chain IDs and LayerZero EIDs, LayerZero fee estimation, and wait_for_bridge_arrival polling semantics.
  • Event submission — single and batch event submission, pipeline details, limits, hashing, metadata mode, and rate-limiting behavior.
  • NFT minting & DID attributes — minting machine NFTs, querying token IDs, writing machine and proxy DID attributes atomically via the Batch precompile. Covers attribute key reference, data visibility options, and the atomic batch guarantee.
  • OWS wallet lifecycle — create, import, list, get, export, and delete encrypted wallets via the Open Wallet Standard. Multi-chain accounts, passphrase management, and vault storage.
  • Orchestration service (experimental)client.orchestration, policies, observability, market lifecycle, pagination, challenge-sign workflows, planned type stubs, and live integration tests.
  • Stream data signing & encryption (experimental) — local field-level privacy rules, EIP-191 data package signing, and verification (Phase 2 Step 2; no network/distribution).
  • Stream data chunking (experimental) — per-chunk XChaCha20-Poly1305 encryption, inline Ed25519 signatures, owner/operator/machine key wrapping, and separate buyer access docs; build_chunk_chain / verify_chunk_chain / decrypt_chunk / create_buyer_access_entry / build_buyer_access_files.
  • Analytics & telemetry — anonymous usage telemetry, event inventory, opt-out, privacy guarantees, and onboarding flow integration.

Development

git clone https://github.com/peaqnetwork/peaq-os-sdk-py.git
cd peaq-os-sdk-py
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

Activate .env for Testing

set -a
source .env
set +a

Quality gates

ruff check src tests       # lint — zero warnings
black --check src tests    # formatting
mypy src                   # strict type check, zero errors
pytest -q                  # all green

The unit tests are hermetic — they mock Web3 and requests.Session with handwritten stubs and never touch the network.

Optional integration tests

The repo ships an opt-in suite that talks to a real peaq devnet. It is skipped silently in normal pytest -q and only runs when the required environment variables are supplied.

Registration integration suite (tests/integration/registration/test_registration_integration.py) — three end-to-end tests for the self-managed flow, proxy-managed flow, and double-registration revert. Gated behind the integration marker plus seven environment variables:

PEAQOS_RPC_URL=https://peaq.api.onfinality.io/public
PEAQOS_PRIVATE_KEY=0xYOUR_FUNDED_TREASURY_KEY
IDENTITY_REGISTRY_ADDRESS=0xYOUR_DEPLOYED_REGISTRY_ADDRESS
IDENTITY_STAKING_ADDRESS=0xYOUR_DEPLOYED_STAKING_ADDRESS
PEAQOS_OWNER_ADDRESS=5GrwvaEF...
PEAQOS_FAUCET_URL=https://depinstation.peaq.xyz
PEAQOS_2FA_CODE=123456
pytest -m integration tests/integration/

See docs/02_REGISTRATION.md → Integration tests for the full breakdown of what each test verifies and operational warnings.

NFT & DID integration suite (tests/integration/nft_did/test_nft_and_did_integration.py) — end-to-end tests for the full NFT lifecycle, atomic DID writes, and atomicity guarantee verification (all-or-nothing batch semantics). Includes 7 tests across minting, token queries, machine DID attributes, proxy DID attributes, and atomic revert scenarios. Requires the same env vars as the registration suite plus:

EVENT_REGISTRY_ADDRESS=0x...
MACHINE_NFT_ADDRESS=0x...
DID_REGISTRY_ADDRESS=0x0000000000000000000000000000000000000800
BATCH_PRECOMPILE_ADDRESS=0x0000000000000000000000000000000000000805

See docs/04_NFT_AND_DID.md for the full breakdown.

OWS wallet integration suite (tests/integration/wallet/test_wallet_integration.py) — six end-to-end tests for wallet lifecycle (create, list, get, delete), create-export-reimport round-trip, private key import, empty vault, and error paths. Gated behind PEAQOS_INTEGRATION=1 and requires the open-wallet-standard package:

pip install peaq-os-sdk[ows]
PEAQOS_INTEGRATION=1 pytest -m integration tests/integration/wallet/

See docs/06_WALLET.md for the full wallet API reference.

Orchestration live API suite (tests/integration/orchestration/test_orchestration_integration.py) — health, readiness, machine lifecycle, market lifecycle, policy CRUD, and audit-event listing against a real orchestration deployment. Gated behind PEAQOS_ORCHESTRATION_INTEGRATION=1:

PEAQOS_ORCHESTRATION_INTEGRATION=1
PEAQOS_ORCHESTRATION_URL=https://markets.peaq.xyz
PEAQOS_API_KEY=your-platform-api-key
pytest -m integration tests/integration/orchestration/test_orchestration_integration.py

Optional overrides: PEAQOS_ORCHESTRATION_PROVIDER_KEY, PEAQOS_ORCHESTRATION_ENDPOINT_URL, PEAQOS_ORCHESTRATION_MARKET_SERVICE_TYPE, PEAQOS_ORCHESTRATION_MARKET_OPERATION, PEAQOS_ORCHESTRATION_MARKET_ORDER_INPUT (JSON object), PEAQOS_ORCHESTRATION_MARKET_PAYMENT_RAIL. See docs/07_ORCHESTRATION.md → Integration tests.

A separate mocked market lifecycle test lives in tests/integration/orchestration/test_market_lifecycle_integration.py and runs without orchestration env vars.

PEAQOS_PRIVATE_KEY must match ^0x[0-9a-fA-F]{64}$. Never commit a real key. Never run the suite against mainnet.

Build

python -m build

Produces dist/peaq_os_sdk-<version>-py3-none-any.whl and dist/peaq_os_sdk-<version>.tar.gz for downstream testing.

License

See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

peaq_os_sdk-0.3.0.tar.gz (159.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

peaq_os_sdk-0.3.0-py3-none-any.whl (233.1 kB view details)

Uploaded Python 3

File details

Details for the file peaq_os_sdk-0.3.0.tar.gz.

File metadata

  • Download URL: peaq_os_sdk-0.3.0.tar.gz
  • Upload date:
  • Size: 159.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for peaq_os_sdk-0.3.0.tar.gz
Algorithm Hash digest
SHA256 0b8826e6504625560bfc6dc287b526dc7eeeccc471315a2dd2d1e66e1c44f7ad
MD5 b890ac4e5c305b20ebbf5442cddebb0d
BLAKE2b-256 fcc0966bffb0d6171da3ebd986dc102b47eadfbd67144e4188e66b1f319a2273

See more details on using hashes here.

Provenance

The following attestation bundles were made for peaq_os_sdk-0.3.0.tar.gz:

Publisher: publish-peaq-os-sdk.yml on peaqnetwork/peaq-os-sdk-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file peaq_os_sdk-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: peaq_os_sdk-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 233.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for peaq_os_sdk-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bd4ca7f851d0e6e2502218686c3dbfe2aa52c9fee7464e375bf4bd0cfa1032e4
MD5 e9229cedede666e8c6d5231c54fe78bb
BLAKE2b-256 23e4e66ac3d3bae512b8add9de3fac1e7aa693da97235aaa0232f197e1ca6665

See more details on using hashes here.

Provenance

The following attestation bundles were made for peaq_os_sdk-0.3.0-py3-none-any.whl:

Publisher: publish-peaq-os-sdk.yml on peaqnetwork/peaq-os-sdk-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page