• Reading the docs…
Start trading

API reference

Overview

The Privium API serves the Pool’s public state, relays sealed Intents to the Coprocessor, builds deposit transactions, submits Escape requests and claims, paying their fees itself, and relays chain reads. It holds no account, session or plaintext balance: every private result travels as an encrypted envelope that only the account’s own keys open.

Base URL and versions#

The API’s base URL is https://api.privium.io. Routes sit under /v1, except /health, /openapi.json and the RPC relay at /rpc. Every response carries X-Contract-Version, the contract version the server validates with, and X-Request-Id, the request’s id. The id also appears in the error envelope as requestId on INTERNAL_ERROR, and on a VALIDATION_ERROR the server raised on data other than the request’s own input, such as a provider’s answer; every other envelope leaves it out.

The contract, imported from the SDK as @privium/sdk/contract, is the API’s single definition: the zod schemas the server validates every request and response with, a typed client, and the OpenAPI 3.1 document the server also serves at GET /openapi.json. Its client parses each response with the server’s own schema, so a response that drifts from the contract fails at the call.

TypeScript
import { createClient } from '@privium/sdk/contract'

const api = createClient('https://api.privium.io')
const pool = await api.pool()

Routes#

Route Client method Returns
GET /health health Service health
GET /v1/config config Public Pool parameters and enclave transport key
GET /v1/home home Network totals and next Crossing
GET /v1/markets markets Search routable tokens paired with SOL and USDC
GET /v1/markets/{pair} market Market mid, admission state and countdown
GET /v1/markets/{pair}/candles candles Cached GeckoTerminal OHLCV from the deepest pool
POST /v1/markets/{pair}/admit admit Request protocol-paid on-demand admission
GET /v1/pool pool Vault assets, Crossing feed, fees, buybacks and burns
GET /v1/crossings crossings Committed public Crossing feed
GET /v1/crossings/{index} crossing One public Crossing
GET /v1/trust trust Enclave registration, Council and liveness
GET /v1/roots/{root} root Verify a committed root from public chain facts
GET /v1/enclaves/{key} enclave Historical enclave registration for Receipt verification
GET /v1/ledger/diffs ledgerDiffs Scan the same public encrypted diffs as every reader
POST /v1/ledger/leaves ledgerLeaves Current encrypted leaves and verified paths for public positions
POST /v1/intake intake Relay an opaque HPKE sealed Intent
POST /v1/deposits/build buildDeposit Build a wallet deposit using an opaque sealed note
GET /v1/deposits/{signature} depositStatus Public deposit landing and credit status
GET /v1/exits/{crossing}/{index} exit Public denomination release progress
GET /v1/escape/requests/{address} escapeRequest Public Council share and Escape claim progress
POST /v1/escape/relay relayEscape Relay a destination-bound Escape proof with keeper fee payment
POST /v1/escape/build buildEscape Build Escape request or claim from client proof bytes
GET /v1/events eventsUrl SSE stream of Crossings, mids, diffs and opaque private envelopes
GET /v1/rings/{address} ring Classify a destination using the configured Ring integration
POST /rpc rpc Allowlisted Solana JSON-RPC relay

Encoding#

Value On the wire
Token amounts Decimal strings of raw base units, U64 (at most 2^64 − 1). Keep arithmetic in BigInt.
Prices Decimal strings. A market’s priceExponent, fixed when the pair is admitted, sets wire prices as unsigned 64-bit counts of 10priceExponent10^{\text{priceExponent}} quote whole tokens per base whole token.
USD values Decimal strings.
Slots, Crossing indices, key epochs Decimal strings.
Cursors Strings, sent back exactly as a page gives them (Pages).
Hashes, roots, ciphertexts Base64. A Hash is 32 bytes.
Addresses and transaction signatures Base58.
Times ISO 8601 in UTC.
Pairs A PairId: the base mint and the quote mint joined by _, as So11111111111111111111111111111111111111112_EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v for SOL against USDC. Every response writes it this way, and a route reads - between the mints as _. Take it from the market list; a displayed symbol never names a pair.

What the API never takes#

No route accepts an owner id or an account, and there are no accounts, sessions or cookies. A reader of balances sends tree positions and a root, both public, and receives the encrypted leaves at them with their Merkle paths (Ledger leaves and proofs); a reader of history names Crossings by their public index and receives the same diffs as any other reader of them. Each decrypts its own leaves and entries locally. A sealed Intent carries only the enclave key epoch and the ciphertext (Intake). Private results, such as an order’s fill or a signed Receipt, return as encrypted envelopes in the intake response and on the shared event stream (Events).

Pages#

Every list is read a page at a time, and no request returns a whole list. A list route takes limit, the most rows a page holds (1 to 100, default 24), and cursor, where the page starts. Omit cursor for the first page, then send the page’s nextCursor back exactly as given while hasMore is true.

Route Order Cursor
GET /v1/markets Base mint The number of markets before the page.
GET /v1/crossings Newest first before: and a Crossing index: the page holds Crossings below it, so Crossings committed meanwhile never shift a page.
GET /v1/ledger/diffs Oldest first The index of the last Crossing read: the page holds the diffs after it, within fromCrossing and toCrossing and among crossings when sent.

The market list and the Crossing list answer:

Field Type Meaning
items array The page’s rows.
page.nextCursor string or null The cursor of the next page; null on the last.
page.hasMore boolean Whether another page follows.
asOf Timestamp When the server read the rows.

The Ledger diff scan answers nextCursor and hasMore at the top level, and its pages also stop at 2 MiB of diffs: a page holds fewer than limit diffs when the next would pass that size, and one larger diff fills a page alone (Ledger leaves and proofs). The event stream’s catch-up is one such page (Events).

Errors#

Every failed response is one envelope, whatever its status. GET /v1/crossings?limit=0 answers:

Response
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Check the highlighted fields.",
    "retryable": false,
    "stage": "validation",
    "fieldErrors": {
      "limit": [
        "Too small: expected number to be >=1"
      ]
    }
  }
}
Field Type Meaning
error object The failure.
error.code "VALIDATION_ERROR", "UNAUTHORIZED", "ORIGIN_NOT_ALLOWED", "NOT_FOUND", "PROGRAM_UNAVAILABLE", "CONFIGURATION_REQUIRED", "IDEMPOTENCY_CONFLICT", "TRANSACTION_EXPIRED", "PAYLOAD_TOO_LARGE", "UNSUPPORTED_MEDIA_TYPE", "SIMULATION_FAILED", "CHAIN_REFUSED", "RATE_LIMITED", "INTERNAL_ERROR", "UPSTREAM_UNAVAILABLE", "NOT_IMPLEMENTED", "WALLET_REQUIRED", "ACCOUNT_REQUIRED", "INSUFFICIENT_BALANCE", "INTAKE_UNAVAILABLE", "INDEXER_UNAVAILABLE", "PRICE_STALE", "BAD_LIMIT", "ESCAPE_ACTIVE", "ASSET_NOT_ADMITTED", "ASSET_UNSUPPORTED", "ORDER_EXPIRED", "ORDER_NOT_CANCELLABLE", "NONCE_USED", "UNKNOWN_ENCLAVE_KEY", "SIGNATURE_INVALID", "ROOT_NOT_ON_CHAIN", "MALFORMED_RECEIPT", "RECEIPT_CLAIM_FALSE", "MALFORMED_BUNDLE", "OUT_OF_SCOPE", "MERKLE_PROOF_INVALID", "DECRYPTION_FAILED", "CURSOR_EXPIRED", "ESCAPE_NOT_READY", "SHARES_PENDING", "ALREADY_CLAIMED" The stable code to branch on, from the table below.
error.message string A sentence fit to show the reader.
error.retryable boolean true when the same request can succeed later.
error.stage "validation", "auth", "read", "upload", "build", "wallet", "co_sign", "simulation", "send", "confirmation" Where the flow failed.
error.fieldErrors Record<string, …> of string[] (optional) Messages per invalid input, keyed by its path; form when the input as a whole is refused.
error.programError object (optional) The program that refused a transaction, on SIMULATION_FAILED or CHAIN_REFUSED.
error.programError.programId Address The refusing program's address.
error.programError.name string The error's name in that program's catalog; UnknownProgramError when the catalog has no entry for it.
error.programError.number integer (optional) The program's custom error number.
error.retryAfterSeconds integer (optional) Seconds to wait before retrying; the same value arrives as the Retry-After header.
error.requestId string (optional) The request's id, equal to its X-Request-Id header, on INTERNAL_ERROR and on a VALIDATION_ERROR raised on data other than the request's own input.

Branch on code, show message, keep the last state you verified, and retry only when retryable is true, after retryAfterSeconds when it is present (the same value arrives as the Retry-After header). fieldErrors keys each invalid input by its path. programError names the program that refused a transaction by address, so custom error numbers of different programs never collide.

The stage is where the flow failed: validation, auth, read, upload, build, wallet, co_sign, simulation, send or confirmation.

The API serves the Pool’s state from its indexer, which verifies each Commit against the chain before that state is served. A route that reads indexed state answers INDEXER_UNAVAILABLE while the indexer has not yet verified the latest Commit, which passes within moments, and while its verified root disagrees with the chain; it answers PROGRAM_UNAVAILABLE before the Pool is indexed at all. Both are retryable, and each route’s list names them where they apply.

Any route can also answer ORIGIN_NOT_ALLOWED to a browser on an origin the API does not serve (Browsers and origins), PAYLOAD_TOO_LARGE to a body over 1 MiB, and INTERNAL_ERROR with its requestId on an unexpected failure. An unknown path answers NOT_FOUND.

Code HTTP Meaning
VALIDATION_ERROR 400 A path, query or body value fails the contract's schema, a query carries an unknown key, or the JSON body does not parse; fieldErrors names each input. Intake also answers it, at stage send, when the enclave refuses a sealed Intent for a reason no other code names.
UNAUTHORIZED 401 A route that needs credentials, called without them. No Privium route takes credentials.
ORIGIN_NOT_ALLOWED 403 A browser request from an Origin the API does not serve, on any route.
NOT_FOUND 404 No route matches the path, or the market, Crossing, Exit piece, Escape request or program account it names does not exist.
PROGRAM_UNAVAILABLE 409 The API has not indexed the Pool yet, no enclave registration is active, or a deposit build finds no Pool LedgerRoot on chain.
CONFIGURATION_REQUIRED 409 A setting the call needs is unset: the pair's price exponent, the Jupiter key a mainnet market search uses, the Ring lookup's Helius endpoint, the fee payer the Escape relay pays with, or the fee rate an order's fee estimate needs.
IDEMPOTENCY_CONFLICT 409 A repeated write whose idempotency key names a different request.
TRANSACTION_EXPIRED 409 A transaction whose blockhash expired before it landed. Build it again.
PAYLOAD_TOO_LARGE 413 A request body over 1 MiB.
UNSUPPORTED_MEDIA_TYPE 415 A POST whose body is not application/json.
SIMULATION_FAILED 422 A built transaction that fails simulation; programError names the program and its error when the logs do.
CHAIN_REFUSED 422 The chain refused the transaction, the build could not form it within one packet with room for wallet guards, or an Escape relay names a request account that belongs to another leaf, owner or mint; programError, when present, names the refusing program and its error.
RATE_LIMITED 429 More than 60 POST requests to /v1 in a minute from one client, or more than 600 leaf reads. Retry after retryAfterSeconds.
INTERNAL_ERROR 500 An unexpected failure on the server, with its requestId; the client also reports a non-envelope answer below HTTP 500 this way.
UPSTREAM_UNAVAILABLE 502 A provider the route reads is unreachable or answered invalidly: the price oracle, Jupiter's price, token search or route quote, GeckoTerminal, or the Ring registry. The client also reports a non-envelope HTTP 5xx answer this way.
NOT_IMPLEMENTED 501 An operation the API does not serve: the Escape build route, or an Escape Intent at intake.
WALLET_REQUIRED 401 A flow that needs a connected wallet, started without one.
ACCOUNT_REQUIRED 409 A flow that needs an open Privium account, started before the account is opened, or an Intent from an account the enclave has not registered.
INSUFFICIENT_BALANCE 422 An order or Exit the account's unreserved balance cannot fund.
INTAKE_UNAVAILABLE 503 The Coprocessor's intake is unreachable, did not answer within 15 seconds, or could not confirm or keep the Intent. Keep the sealed Intent; sending the same bytes again is safe.
INDEXER_UNAVAILABLE 503 The indexer has not verified the latest Commit yet, or its verified root disagrees with the chain, so indexed state is not served; on a leaf read with fieldErrors.root snapshot_changed, the requested root left the recent window. Keep the last verified balances and retry.
PRICE_STALE 409 A market order without a valid mid: older than maxPriceAgeMs, a Pyth confidence interval wider than κ, or a Pyth mid more than κ from Jupiter's live price.
BAD_LIMIT 422 A limit or size that is not positive, a price off the pair's priceExponent grid, or no route bound for the order's size.
ESCAPE_ACTIVE 409 A deposit build, or any Intent but a status, a Receipt request or a registered account's registration, while the Escape is active. Trading, deposits and new Exits are closed.
ASSET_NOT_ADMITTED 409 A deposit, trade or Exit in an asset the Pool has not admitted. A trade requests admission first.
ASSET_UNSUPPORTED 422 A deposit in a token outside the market list, or a Ring Exit in an asset the Ring does not accept.
ORDER_EXPIRED 409 An Intent past its expiry slot.
ORDER_NOT_CANCELLABLE 409 A cancel for an order that is no longer resting.
NONCE_USED 409 An Intent whose nonce the account has consumed: at or below its watermark, held by an open order, or accepted with other bytes.
UNKNOWN_ENCLAVE_KEY 422 An enclave key the Registry never admitted, or an Intent sealed to a key epoch that is neither active nor within four slots after its validUntilSlot.
SIGNATURE_INVALID 422 A wallet signature that fails at connect, or a sealed Intent or enclave reply whose signature does not verify.
ROOT_NOT_ON_CHAIN 422 A root no Commit stored, a diff whose root does not match its Commit, or a leaf read whose root, Crossing or slot differs from the on-chain LedgerRoot.
MALFORMED_RECEIPT 400 Receipt bytes that do not decode.
RECEIPT_CLAIM_FALSE 422 A Receipt request's at-least claim whose figure over the span falls short of its threshold; fieldErrors.claims names the claim.
MALFORMED_BUNDLE 400 Viewing bundle bytes that do not decode.
OUT_OF_SCOPE 403 An entry outside the viewing bundle's scope.
MERKLE_PROOF_INVALID 422 A diff whose chunks do not fold to its Commit's accumulator, a diff header that disagrees with its Commit, a served leaf that differs from the committed diff, a leaf read whose paths, positions or asset entries fail their check, or an Escape request whose leaf and path do not reach the frozen root.
DECRYPTION_FAILED 422 Sealed bytes that open under no registered enclave key and its info string.
CURSOR_EXPIRED 409 A scan cursor the server no longer serves. Restart from a snapshot.
ESCAPE_NOT_READY 409 An Escape request or claim relayed while the Ledger records no active Escape.
SHARES_PENDING 409 An Escape claim before threshold Council shares are in.
ALREADY_CLAIMED 409 An Escape claim for a balance already paid.

The RPC relay answers in JSON-RPC’s own error shape instead, which Solana clients expect (RPC relay).

Limits#

What Limit
POST routes under /v1, except the leaf read 60 per minute per client; reads are not limited
Leaf read, POST /v1/ledger/leaves 600 per minute per client, 256 positions a request
Request body 1 MiB
Sealed Intent and deposit note 16,384 base64 characters
RPC relay 600 reads and 30 writes per minute per client, one request per call, 64 KiB body

A client over a /v1 limit receives RATE_LIMITED with retryAfterSeconds; over an RPC relay limit, JSON-RPC error -32005 with Retry-After. The client is the caller’s address, or behind a proxy the last address the proxy appended.

Browsers and origins#

Browsers call the API from https://privium.io. Servers, bots and scripts call it from anywhere.

Health and configuration#

GET /health#

Whether the API is up, which contract it speaks and whether its indexed state is current. Deploy health checks and monitors call it. It answers 200 in every state, so branch on status: ready while the indexer has verified the Pool’s latest Commit, waiting before the Pool is indexed, for the moments the indexer takes to verify each new Commit, and while its root disagrees with the chain.

Returns Health. It raises no error of its own.

TypeScript
const health = await api.health()
if (health.status === 'waiting') console.log('The indexer has not verified the latest Commit yet.')
Response
{
  "status": "ready",
  "mode": "chain",
  "contractVersion": "0.1.22"
}

GET /v1/config#

The program id, the Pool’s protocol parameters, the fee recipient and the enclave key every Intent and deposit note is sealed to. Privium.connect reads it before anything else, and the SDK reads it again before each sealed action, so every Intent and note is sealed to the activeEnclave of that moment. previousEnclaves holds up to four of the Registry’s other registrations, newest first, so a reply signed under another key still verifies. Intake takes an Intent sealed to the active key’s epoch, and to a previous key’s for four slots after its validUntilSlot; it refuses any other epoch with UNKNOWN_ENCLAVE_KEY before relaying (Intake): read the configuration again and seal to the active key.

Returns Config, with the parameters in Params.

Errors

  • PROGRAM_UNAVAILABLE: the Pool is not indexed yet, or no enclave registration covers the current slot.
  • INDEXER_UNAVAILABLE: the indexer has not verified the latest Commit yet, or its root disagrees with the chain; retryable.
  • INTAKE_UNAVAILABLE: outside an Escape, the enclave’s intake is not yet ready to receive under its key; retryable.
TypeScript
const config = await api.config()
const { keyEpoch, hpkeKey } = config.activeEnclave
const { deltaSlots, escapeWindowSlots, feeBps } = config.params
Response
{
  "mode": "chain",
  "network": "localnet",
  "programId": "BH2ggvL6MxJ96zQhiuCdJDym84kN4RPpkf4bVJgZAVYe",
  "rpcUrl": "/rpc",
  "params": {
    "deltaSlots": 4,
    "escapeWindowSlots": "9000",
    "kappaBps": 25,
    "beta0Bps": 50,
    "vaultShards": 2,
    "rewriteMinimum": 64,
    "denominationCount": 24,
    "exitDelayMeanSlots": 9000,
    "leaseSlots": 300,
    "maxPriceAgeMs": 75000,
    "treeDepth": 32,
    "feeBps": 10
  },
  "activeEnclave": {
    "signingKey": "5FYR7WaPVYwsmUCQxmJoLrwG14cwLCsxsQvSt2FMDJhL",
    "hpkeKey": "/kV4H3CpJDM4boEAapb7E3r17uE5y63yd+pNtrcPxkY=",
    "keyEpoch": "2180",
    "measurement": "ZgsEmPKnF/77hCijP1VK9Ndu92n3honQagGmISlBu6c=",
    "platform": "mainnet-beta",
    "quoteHash": "/ltey38J838VqZUrrqaRSJibMbOQ6avYOQ4OLIKl97k=",
    "verifiedAtSlot": "470880162",
    "validFromSlot": "470880000",
    "validUntilSlot": "471096000"
  },
  "previousEnclaves": [],
  "feeRecipient": "2oxQFJKkXUegJg5JbYtxbTTdByAsNuVsDTbdGyRcnAe9",
  "priviumMint": "9FSjffoh8Yk8jdpr9EEEuxTD6mphYayfboxZMKWVPRV",
  "fixture": false
}

Health#

Field Type Meaning
status "fixture", "waiting", "ready" ready while the indexer has verified the Pool's latest Commit; waiting before the Pool is indexed, while the indexer catches up with a Commit, or while its root disagrees with the chain; fixture on an API that answers from the contract's fixtures.
contractVersion string The contract version the server validates with, as in X-Contract-Version.
mode "fixture", "chain" chain when the API reads the program on chain, fixture when it answers from the contract's fixtures.

Config#

Field Type Meaning
mode "fixture", "chain" chain when the API reads the program on chain, fixture when it answers from the contract's fixtures.
network "localnet", "mainnet" The cluster the program runs on: mainnet or localnet.
programId Address The privium_pool program's address.
rpcUrl "/rpc" The API's own RPC relay, relative to its base URL.
params Params The Pool's protocol parameters.
activeEnclave Enclave The enclave registration Intents and deposit notes are sealed to now.
previousEnclaves Enclave[] (optional) Up to four of the Registry's other enclave registrations, newest epoch first, so a reply signed under another key still verifies.
feeRecipient Address or null The fee recipient each Commit pays the Crossing's fees to, the token's launch wallet; null until configured.
priviumMint Address or null The $PRV mint, 9FSjffoh8Yk8jdpr9EEEuxTD6mphYayfboxZMKWVPRV; null on an API not configured with a mint.
fixture boolean true on an API that answers from fixtures, whose transaction builds no wallet can sign.

Params#

The values the program and the Coprocessor run with, under the whitepaper’s symbols.

Field Type Meaning
deltaSlots 4 Δ, the batch interval: a Crossing's cutoff falls at least this many slots after the last Commit.
escapeWindowSlots U64 W, the liveness window: with no Commit for this many slots, the Escape can be triggered.
kappaBps 25 κ, in basis points: the widest Pyth confidence interval, and the furthest a mid may lie from Jupiter's live price, at which a pair crosses or a market order is built.
beta0Bps 50 β₀, in basis points: the least route bound a market order's protective limit uses.
vaultShards 2 S, the vault shards per asset; a deposit picks one uniformly at random.
rewriteMinimum 64 m₀: the fewest leaves of each carried asset a Crossing rewrites.
denominationCount 24 How many power-of-two multiples of an asset's denominationUnit an Exit splits into.
exitDelayMeanSlots 9000 μ, the mean of the delay sampled for each Exit piece, in slots.
leaseSlots 300 The Crossing lease: slots the opening enclave key alone may route and commit a Crossing.
maxPriceAgeMs 75000 The oldest a Pyth price may be, by its publish time, for a Crossing to clear at it and for a market order, in milliseconds.
treeDepth 32 The Ledger tree's depth: every Merkle path has this many siblings.
feeBps integer (optional) φ, the fee rate in basis points, charged in the pair's quote asset; null until the Pool's configuration sets it.