The distribution surface ships in
@peaqos/peaq-os-sdk and peaq-os-sdk 0.4.0+ and is flagged @experimental. It builds on the stream crypto module (0.3.0+): everything here moves chunks that buildChunkChain already signed and encrypted.stream module makes machine data sellable; this surface actually sells and ships it. It covers the whole buyer-to-seller loop: a buyer creates a purchase against a listing, pays over a transfer or rail, and the seller — notified over a control socket — re-wraps the purchased chunk keys and delivers through a pluggable delivery channel: S3 (the buyer-access files plus a pre-signed download URL, with the ciphertext staying at each chunk’s storageRef) or the peaqos-p2p transport (the encrypted chunks themselves, streamed machine-to-machine). The seller never decrypts or re-encrypts chunk data at any point; only the buyer-access documents (wrapped per-chunk keys) are generated during distribution.
The distribution lifecycle
Every step is a stateless API call — the SDK holds no purchase state. The buyer authenticates with an agent-pairing token (x-agent-pairing-token), the seller’s machine agent with x-machine-agent-id + x-machine-agent-token, and platform reads with x-api-key.
Delivery setup (before any purchase)
Both sides discover what the orchestration service supports instead of hardcoding it, and machines register what they can handle:| Function | Purpose |
|---|---|
listPaymentRails | Returns the supported rails — X402PaymentRail (chains, tokens, requiresProof) or TransferPaymentRail (chains, tokens, verification), discriminated by type. |
listDeliveryTransports | Returns the available transports, discriminated by mode: p2p (transportId, version, features, protocols, encoding), storage (provider: "walrus" | "s3"), or tunnel (provider: "cloudflare"). |
putDeliveryCapabilities | Registers what a machine can support (buyer or seller side) — after a machine is provisioned, its capability advertisement is what makes it reachable for delivery. The server populates mode and signaling; capabilities are short-lived and renewable. |
updateStreamListingPurchaseFields | Adds paymentRails and deliveryOptions to an existing stream listing. Additive — existing listing fields are untouched. |
PurchasePaymentRail ("x402" | "transfer"), PurchaseChain ("peaq" | "base" | "ethereum" | "solana"), PurchaseToken ("USDC" | "USDT" | "PEAQ"), PurchaseDeliveryMode ("p2p" | "storage" | "tunnel"), PurchaseResourceType ("stream.bundle" | "stream.live") — each with SCREAMING_SNAKE_CASE constants (PURCHASE_CHAIN_BASE, PURCHASE_TOKEN_USDC, …).
Buyer: purchases
{ rail: "x402", paymentHeader } — the signed payment header, no on-chain transfer of your own.
Purchase status progresses delivery_reserving → delivery_reserved → payment_pending → payment_verified → delivery_released → active → completed (or cancelled / failed). Payment status is pending | verified; delivery status is requested | ready | active | completed | failed.
Both sides record lifecycle progress with createPurchaseEvent — event types delivery.started, delivery.completed, delivery.failed, buyer.connected, seller.ready, seller.offline. Invalid types are rejected client-side.
Buyer: paying on-chain
Helpers for the transfer rail on peaq, Base, and Solana. Token decimals resolve from a well-known registry (USDC/USDT on peaq, USDC on Base/Solana) or an explicittokenDecimals override — no on-chain decimals() lookups.
| Function | Purpose |
|---|---|
transferToken | Native or token transfer routed by chain; returns TokenPaymentResult with the tx hash / signature. |
submitPaymentProof | POSTs the proof JSON to a confirmationUrl; expects { accepted: boolean }. (Distinct from client.orchestration.submitPaymentProof().) |
payAndSubmitProof | Chains the two. On partial failure returns { payment, proof: null, proofError } so the tx hash can be resubmitted instead of paying twice. |
| Chain | Extra params | Optional peer deps |
|---|---|---|
peaq | — | viem (required peer) |
base | rpcUrl | viem |
solana | rpcUrl, solanaSigner | @solana/web3.js, @solana/spl-token (SPL only) |
PeaqosClient.solanaSignerFromWallet() — OWS-native Solana signing also ships in 0.4.0.
Seller: getting paid and preparing access
The seller’s primary signal is the control socket — a WebSocket to the orchestration service that carries short control notifications (never bulk data):PollingConfirmationProvider is the fallback: it polls a confirmationUrl (appending ?orderId=...) every pollInterval ms (default 30 000) until status === "confirmed" or timeout seconds (default 3 600) elapse, then resolves a PaymentConfirmation (orderId, buyerId, buyerPublicKeyHex, txHash, status, confirmedAt). HTTP 5xx retries silently; 4xx throws StreamValidationError; timeout throws StreamTimeoutError; stop() aborts immediately. The polling surface (and DistributePackage) tracks the sale as orderId; in the orchestration purchases flow the same identifier is the purchaseId — peaqos stream distribute --order-id documents it as exactly that.
On confirmation the seller submits the re-wrapped chunk keys plus a short-lived connection handoff:
delivery.connect.url is a secret handoff: never log it.
distributeData and delivery channels
distributeData packages the seller side into one call — generate the buyer access files and hand them to a DeliveryChannel:
S3DeliveryChannel uploads each access file to {prefix}{buyerId}/{fileName} and needs @aws-sdk/client-s3 + @aws-sdk/s3-request-presigner (optional peer deps — missing packages throw StreamConfigError with the install hint). Custom channels implement the single-method DeliveryChannel interface: deliver(pkg: DistributePackage) => Promise<DeliveryResult>, where pkg carries buyerAccessFiles, encryptedDataRefs, buyerId, and orderId.
P2P delivery
Thepeaqos-p2p transport moves the encrypted chunks directly machine-to-machine — no storage bucket in the middle. The seller runs a long-lived channel; the buyer dials in with a transient node, receives the chunks, verifies, and decrypts. Delivery here is transport and hand-over only: what a machine is allowed to serve is still governed by its provisioning and registered capabilities.
Seller: P2PDeliveryChannel
start() discovers the peaqos-p2p transport via listDeliveryTransports, validates it against a fixed allowlist, creates the node, registers the machine’s delivery capability, schedules capability renewal, and installs a single central accept loop for inbound buyer connections.
deliver() implements DeliveryChannel, so it plugs straight into distributeData. Called after payment confirmation, it resolves and validates every chunk against the access entries, builds a short-lived delivery.connect handoff (an opaque peaqos-p2p:// URL), calls prepareBuyerAccess, waits for the buyer to connect, streams the chunks as frames, and emits delivery.started / delivery.completed / delivery.failed progress events. Inbound handshakes are routed by (purchaseId, sessionId, buyerId); sessions are single-use with tombstone replay protection.
Buyer: P2PDeliveryReceiver
receive() validates the negotiated session (mode, transport, encoding, connect expiry), dials the seller over delivery.connect.url, identifies itself with a handshake frame, and then — for each chunk — verifies the ciphertext hash, signature, and chain linking before decrypting with decryptChunk, runs verifyChunkChain as a final cross-check, and reassembles the plaintext in index order. The transient node is closed in finally, success or failure.
Wire format and dependencies
Frames usepeaqos-json-frame-v1 — newline-delimited JSON with types handshake, chunk, complete, error. The libp2p stack is wrapped entirely inside the SDK: no libp2p types, peer IDs, or multiaddrs appear in the public API, and delivery.connect URLs are redacted from all SDK-controlled logs, errors, and telemetry.
libp2p ships as optional peer dependencies — install them only when you use P2P delivery:
StreamConfigError carrying exactly that install hint.
Errors
Distribution extends the Stream error hierarchy:| Error | When | Extras |
|---|---|---|
StreamTimeoutError | Confirmation polling timed out. | .timeout (s), .orderId |
StreamPaymentError | On-chain transfer or proof submission failed. | .txHash (when available), .reason |
StreamConfigError | Optional dependency missing (AWS SDK, libp2p). | .installHint |
StreamDeliveryError | Seller-side P2P delivery failure. | .channel: "p2p", .purchaseId, .code |
StreamReceiveError | Buyer-side P2P reception failure. | .purchaseId, .code |
.code is a coarse public StreamErrorCode: "config" (missing dependency, transport/capability negotiation failure), "protocol" (wire/frame/session violation, verification failure), or "transfer" (connection, timeout, or data-transfer failure). Error messages are sanitized — no key material, no raw transport exceptions. Purchase functions throw the standard orchestration errors (OrchestrationApiError, OrchestrationValidationError, …).
Python and the CLI
The Python SDK ships the same distribution surface in snake_case. From the terminal,peaqos stream distribute (payment listener + S3 delivery), peaqos stream pay / payproof (buyer transfer + proof), and peaqos stream consume --download-url (remote release packages) wrap it — P2P delivery itself is SDK-level and has no CLI flag yet.
Related
- Stream crypto module — signing, chunking, encryption, access grants
- Stream function — what Stream is and what ships
- Data streams concept — the trust model
- Stream data marketplace API — the buyer-side HTTP surface
- peaqOS CLI: stream

