• Reading the docs…
Start trading

SDK

Events and account state

A connected account follows the Pool live with watchEvents, follows its own orders with watchFills and its Exit pieces with watchExits, opens any reply of its own with decodeEnvelope, recovers its open orders and Exit pieces from the enclave with openOrders, reads its current balances with readBalances and reads its history from the public Crossing diffs a page at a time. Every read is checked against the chain and decrypted in the caller’s process; no request carries the account in the clear. An Escape request is followed with watchEscape.

watchEvents#

Streams the API’s live events as typed values.

watch-events.ts
const controller = new AbortController()

try {
  for await (const event of privium.watchEvents(controller.signal)) {
    if (event.type === 'crossing') console.log('Crossing', event.data.index, 'committed')
    if (event.type === 'resync') console.log('Refetch snapshots, then scan diffs from', event.data.cursor)
  }
} catch (error) {
  if (!controller.signal.aborted) throw error
}
Parameter Type Meaning
signal AbortSignal (optional) Aborts the stream.
cursor string (optional) The public cursor to resume from.

It opens GET /v1/events with Accept: text/event-stream, without a pair, and yields each event’s data parsed as a LiveEvent: ready, crossing, mid, ledger, encrypted and resync. Before it opens the stream, and again after each crossing event, it reads GET /v1/config, so replies sealed under a newly registered enclave key keep opening (The enclave key). The generator ends when the server closes the stream. Aborting the signal stops it: the pending read rejects with the platform’s abort error, and the stream is released either way. To resume, call again with the last cursor the stream gave; ready, ledger and resync events carry one.

Code Stage Message
PROGRAM_UNAVAILABLE read The enclave quote has not been indexed yet. Retry when its attestation is available.
CONFIGURATION_REQUIRED read The API changed its Pool program. Reconnect explicitly.
UPSTREAM_UNAVAILABLE read The event stream is unavailable.

An event that does not parse as a LiveEvent throws zod’s ZodError.

watchFills#

Streams this account’s order results: every encrypted event whose envelope opens under the account’s reply key and moves its order forward.

watch-fills.ts
const controller = new AbortController()

for await (const result of privium.watchFills(controller.signal)) {
  if (result.kind === 'order' && result.state === 'filled') console.log(result.nonce, result.crossed, result.routed, result.fee)
}
Parameter Type Meaning
signal AbortSignal (optional) Aborts the stream.
cursor string (optional) The public cursor to resume from.

Each envelope is opened as decodeEnvelope opens it. One that does not open, another account’s reply among them, is passed over: the stream carries every account’s replies, and each reader keeps only its own. Replies of other kinds are passed over too. Each OrderResult then goes through the instance’s order tracking, and the generator yields it only when it moves its order forward, so the states of one order arrive in the order the enclave reached them (After intake).

Code Stage Message
PROGRAM_UNAVAILABLE read The enclave quote has not been indexed yet. Retry when its attestation is available.
CONFIGURATION_REQUIRED read The API changed its Pool program. Reconnect explicitly.
DECRYPTION_FAILED read This envelope cannot be opened by this account.
UPSTREAM_UNAVAILABLE read The event stream is unavailable.

DECRYPTION_FAILED stays inside the generator: it is how an envelope that does not open is passed over. A reply that opens but does not parse as a PrivateEvent throws zod’s ZodError, and one that opens under an enclave key whose EnclaveKey record does not check throws a plain Error, UNKNOWN_ENCLAVE_KEY (verifyEnclaveRegistration).

Order tracking#

An instance keeps the latest state it has taken for each order nonce, from intake’s answers (a Submission’s results), from watchFills and from decodeEnvelope. A result for an order it already holds is passed over when:

  • the state held is final: filled, expired, cancelled or rejected;
  • it names no Crossing and the state held names one, or it names an earlier Crossing than the state held;
  • it is the state held, unchanged;
  • it names the same Crossing as the state held, or neither names one, and comes earlier in the order sealed, waiting, resting, partly-filled, then any final state.

Any other result replaces the state held. A reply the stream delivers twice, or late, therefore never moves an order back: watchFills does not yield it, and a submission’s results leave it out. decodeEnvelope returns every reply it opens and records only a result that moves its order forward.

decodeEnvelope#

Opens one sealed reply, such as an encrypted event’s envelope, and returns it as a PrivateResult of any kind. watchFills opens envelopes the same way and keeps only order results; decodeEnvelope serves a client that reads the stream itself.

decode-envelope.ts
import { SdkError } from '@privium/sdk'

for await (const event of privium.watchEvents()) {
  if (event.type !== 'encrypted') continue
  try {
    const reply = await privium.decodeEnvelope(event.data.envelope)
    if (reply.kind === 'exit') console.log(reply.nonce, reply.state)
  } catch (error) {
    if (!(error instanceof SdkError && error.code === 'DECRYPTION_FAILED')) throw error
  }
}
Parameter Type Meaning
envelope string A sealed reply in base64, such as an encrypted event's envelope.

It decodes the base64 and opens the bytes with the account’s note key under every enclave key the instance holds, newest first, checking the reply’s signature against that key’s enclave signing key. The first key that opens it is checked on chain with verifyEnclaveRegistration, once per key, and the plaintext parses as a PrivateEvent. An order result enters the instance’s order tracking; the call returns it either way.

Code Stage Message
PROGRAM_UNAVAILABLE read The enclave quote has not been indexed yet. Retry when its attestation is available.
DECRYPTION_FAILED read This envelope cannot be opened by this account.

DECRYPTION_FAILED, at stage read, is the answer for an envelope that is not base64 or that no key opens with a valid enclave signature, as for every reply sealed to another account. A reply that does not parse throws zod’s ZodError, and a key whose EnclaveKey record does not check throws a plain Error, UNKNOWN_ENCLAVE_KEY.

openOrders#

Recovers the account’s open orders and pending Exit pieces from the enclave, on any device, from the wallet alone, with the Crossings of a history range that hold the account’s entries.

open-orders.ts
const status = await privium.openOrders()
for (const order of status.openOrders) console.log(order.pair, order.side, order.remainingSize, order.state)

const span = await privium.openOrders({ from: 1000n, to: 2000n })
console.log(span.history.entryCrossings, span.history.hasMore)

Neither the orders nor the pieces are in the Ledger diff: the enclave holds them in its working state, checkpointed at each committed root (What stays off the diff), and only a status Intent reads them.

The range is optional:

Parameter Type Meaning
from bigint The first Crossing of the history range the status lists entry Crossings for. The whole range is optional: without it, Crossing 0 through the last committed.
to bigint The range's last Crossing, at or after from. The enclave caps it at the last committed Crossing.
asset string (optional) A mint: list only Crossings holding the account's entries of that asset. Every asset when absent.

It sends a status Intent: signed by the auth key and sealed like every Intent, under a fresh nonce of its own, through POST /v1/intake, with the range inside the signed body when one is given (ExtendedIntent). The enclave answers with the account’s status sealed to the account alone; no route returns it in the clear. The reply opens under the account’s reply key, and its signature is checked against the enclave signing key it came under, as for every reply. The call then raises the instance’s nonce floor to the status’s watermark and the highest nonce of its open orders (Nonces).

Returns the AccountStatus: the watermark, the OpenOrder list, the PendingExit list, the ledger positions readBalances reads, and history, an AccountHistory: up to 256 Crossings of the range, through the last committed one, that hold the account’s entries, of the named asset when there is one. Without a range, history covers Crossing 0 through the last committed, every asset. disclose and readHistory read it to fetch only those Crossings. An open order reads resting until part of it fills and partly-filled from then on, through every Crossing that gives it no new fill, until it finishes.

Code Stage Message
PROGRAM_UNAVAILABLE read The enclave quote has not been indexed yet. Retry when its attestation is available.
CONFIGURATION_REQUIRED read The API changed its Pool program. Reconnect explicitly.
DECRYPTION_FAILED read This envelope cannot be opened by this account.
INTAKE_UNAVAILABLE send The account registration is sealed and the intake is unreachable.
INTAKE_UNAVAILABLE read The account status intake is unreachable.
UPSTREAM_UNAVAILABLE read The enclave returned no account status.

Intake’s other errors throw ApiClientError. A range whose to is before its from throws a plain Error, Invalid status history range, before the Intent is sealed.

pendingExits#

The pendingExits of a fresh openOrders() read: the account’s Exit pieces, released ones included, each with its nonce, amount, destination and release slot. A piece the enclave holds reads scheduled: its release slot is the one the enclave sampled, shown to the owner alone, and its amount stays in the balance, reserved against new orders and Exits. Once the first Crossing opened at or after that slot commits, the piece reads committed, with that Crossing and its index in the Crossing’s exits root, and is releasable. Once paid it reads released, with the release transaction. The release is read from the chain’s public record by watchExits. It raises what openOrders raises.

pending-exits.ts
for (const piece of await privium.pendingExits()) console.log(piece.amount, piece.state, piece.crossing, piece.index)

watchExits#

Follows the account’s Exit pieces from scheduled through committed to released: it recovers the signed pieces from the enclave, then reads each committed piece’s public record.

watch-exits.ts
const controller = new AbortController()

for await (const update of privium.watchExits({ signal: controller.signal })) {
  console.log(update.nonce, update.state, update.amount)
  if (update.state === 'released') console.log('Paid to', update.destination, 'in', update.transaction)
}
Parameter Type Meaning
options WatchExitsOptions (optional) The abort signal and the poll interval, both optional.

WatchExitsOptions#

Field Type Meaning
signal AbortSignal (optional) Ends the generator when aborted.
pollIntervalMs number (optional) Milliseconds between rounds of public reads, at least 100; 3,000 when absent.

Each round, it:

  1. Reads the account’s status as pendingExits does, at most once every 3 seconds, and follows every piece the status lists. An answer of RATE_LIMITED holds the next status read for its retryAfterSeconds (60 when absent, and at least 3); the public reads go on meanwhile.
  2. Reads GET /v1/exits/{crossing}/{index} for each followed piece that has a Crossing and an index and is not released. A scheduled piece has neither, and nothing public exists for it until its Commit. The public record must name the piece’s mint, recipient and amount, or the generator throws CHAIN_REFUSED; its state and transaction then stand for the piece’s. A record the API answers NOT_FOUND for leaves the piece as the enclave gave it.
  3. Yields an ExitUpdate for each piece that is new or has changed since it was last yielded, with its asset as the Registry index the first page of GET /v1/markets gives the mint. A released piece is yielded once as released. An update carries no release slot: pendingExits has it.
  4. Waits pollIntervalMs.

It runs until the signal aborts, then returns at its next check, or throws the platform’s abort error from a public read in flight. Every status read is a signed status Intent with a fresh nonce of its own, so it raises the instance’s nonce floor as openOrders does.

Code Stage Message
PROGRAM_UNAVAILABLE read The enclave quote has not been indexed yet. Retry when its attestation is available.
CONFIGURATION_REQUIRED read The API changed its Pool program. Reconnect explicitly.
DECRYPTION_FAILED read This envelope cannot be opened by this account.
INTAKE_UNAVAILABLE send The account registration is sealed and the intake is unreachable.
INTAKE_UNAVAILABLE read The account status intake is unreachable.
UPSTREAM_UNAVAILABLE read The enclave returned no account status.
VALIDATION_ERROR validation Exit polling interval must be at least 100 ms.
CHAIN_REFUSED read The public exit differs from its signed private piece.
ASSET_UNSUPPORTED read The exit asset is missing from the market catalogue.

The API’s other errors throw ApiClientError.

readBalances#

Reads the account’s current balances. The enclave’s signed status names the positions of the account’s leaves, the API serves those leaves with their Merkle paths, and each leaf is checked against the LedgerRoot account on chain before it is decrypted. No diff is scanned and no past transaction is read.

balances.ts
import { fromBaseUnits } from '@privium/sdk'

const snapshot = await privium.readBalances()
for (const { asset, balance } of snapshot.balances) console.log(asset.symbol, fromBaseUnits(balance, asset.decimals))
console.log('Checked against the root of Crossing', snapshot.crossing)

It holds the account’s queue in the process (Nonces), then:

  1. Reads the account’s status as openOrders does. Besides the orders and Exit pieces, the status carries ledger: the root and Crossing the enclave last committed, and the positions of the account’s balance leaves under that root.
  2. Reads the program’s LedgerRoot account through the API’s RPC relay with readLedgerRoot. The status must name the same root and Crossing; when the Ledger moved between the two reads, the call waits 100 ms and starts again from step 1.
  3. Requests the positions, up to 256 at a time, with POST /v1/ledger/leaves, pinned to that root. Each answer must name the root, Crossing and slot the LedgerRoot account holds, and return exactly the positions requested, each with its path. An answer of INDEXER_UNAVAILABLE for a snapshot that changed also starts the call again from step 1 after 100 ms. The call makes four attempts at most: on the fourth, a Ledger that moved throws INDEXER_UNAVAILABLE, and a snapshot that changed throws the leaf route’s answer.
  4. For each leaf, finds its asset by Registry index among the answer’s assets, which must list it as admitted, verifies its 32-sibling Merkle path against the root, decrypts its owner ciphertext under the account’s balance key for that mint, and checks the commitment against the decrypted balance and opening (Reading your own balances).

A fresh connection reading up to 256 balances makes nine requests: three configuration reads, two intake calls (the registration and the status), three account reads through the relay (the enclave key’s EnclaveKey record, the Registry and LedgerRoot) and one leaf request, with no diff page and no historical transaction. The count follows the account’s leaves, not the Ledger’s history. The leaf request carries positions and a root; no account id, key, balance or order leaves the process in the clear.

It returns a Balances with stale false: one Balance per leaf, with the root, Crossing and slot they were checked against. The snapshot replaces the instance’s own once every leaf verifies, so a call that throws leaves the instance holding the snapshot it had, which lastKnownBalances returns.

A balance is the committed one: a scheduled Exit piece stays in it until the Commit that lists the piece debits it, and pendingExits gives what such pieces reserve.

While the Escape is active the root is frozen and the call fetches no leaves. It returns the instance’s snapshot when that snapshot was taken at the frozen root and Crossing, and otherwise throws ESCAPE_ACTIVE at stage read; recoverBalancesFromHistory then builds that snapshot. A status read that intake cannot serve while the Ledger is live throws as openOrders does.

Code Stage Message
PROGRAM_UNAVAILABLE read The enclave quote has not been indexed yet. Retry when its attestation is available.
CONFIGURATION_REQUIRED read The API changed its Pool program. Reconnect explicitly.
DECRYPTION_FAILED read This envelope cannot be opened by this account.
INTAKE_UNAVAILABLE send The account registration is sealed and the intake is unreachable.
INTAKE_UNAVAILABLE read The account status intake is unreachable.
UPSTREAM_UNAVAILABLE read The enclave returned no account status.
INDEXER_UNAVAILABLE read No verified balance snapshot is available.
ESCAPE_ACTIVE read Recover the frozen snapshot from public history before reading this account.
INDEXER_UNAVAILABLE read The ledger moved while reading account status. Retry this snapshot.
ROOT_NOT_ON_CHAIN read The leaf snapshot does not match the on-chain ledger.
MERKLE_PROOF_INVALID read A committed account leaf is missing.
MERKLE_PROOF_INVALID read The leaf proof has an unexpected position.
ASSET_NOT_ADMITTED read The committed leaf asset is unavailable.
  • A leaf whose path does not reach the root throws a plain Error, MERKLE_PROOF_INVALID; one whose commitment does not match its decrypted balance throws COMMITMENT_INVALID. A LedgerRoot account the program does not own, or without its discriminator, throws ROOT_NOT_ON_CHAIN.
  • The API’s refusals throw ApiClientError: INDEXER_UNAVAILABLE from the leaf route when it holds no verified snapshot at the root, which the app answers with the last balances marked by their Crossing, and the RPC relay’s own refusals.

lastKnownBalances#

privium.lastKnownBalances() returns the last snapshot the instance verified, with stale set to true, or undefined before the first. It makes no request, so a screen keeps showing balances marked by their Crossing while it retries a failed read.

last-known.ts
try {
  await privium.readBalances()
} catch (error) {
  const last = privium.lastKnownBalances()
  if (!last) throw error
  console.log('As of Crossing', last.crossing, last.balances.length, 'balances')
}

recoverBalancesFromHistory#

Rebuilds the account’s balances from the public diffs, for an Escape on a device that holds no snapshot at the frozen root. requestEscape and claimEscape call it when readBalances throws ESCAPE_ACTIVE; a normal balance read never does.

  1. Reads the LedgerRoot account with readLedgerRoot, and the Pool’s assets from GET /v1/pool.
  2. Reads GET /v1/ledger/diffs page by page up to that account’s Crossing. Each diff must name its own Crossing, come after the one before it and start from the root that one ended at, the empty tree’s root for the first. The call applies each diff’s writes, and empties each position a write clears.
  3. Requires the last diff to end at the root and Crossing the LedgerRoot account holds, then rebuilds the tree’s root from every leaf and checks that it equals that root.
  4. Keeps each balance leaf whose owner tag is the account’s own for its mint and version, computes its path from the rebuilt tree, and decrypts and checks it as readBalances does.

One check of the rebuilt tree against the root on chain authenticates every leaf in it, so no Commit transaction is read. The snapshot replaces the instance’s own, anchored at that root, and returns as a Balances.

Code Stage Message
INDEXER_UNAVAILABLE read No verified balance snapshot is available.
MERKLE_PROOF_INVALID read The public ledger history is not contiguous.
CURSOR_EXPIRED read The history cursor did not advance.
INDEXER_UNAVAILABLE read Public history has not reached the frozen ledger.
MERKLE_PROOF_INVALID read The reconstructed ledger does not match the on-chain root.
ASSET_NOT_ADMITTED read A committed asset is unavailable.

The plain errors are those of readBalances, and the API’s refusals throw ApiClientError.

readHistory#

Reads the account’s own history a page at a time: only the Crossings the enclave lists as holding the account’s entries, within the filter’s Crossing span, decrypted and filtered. History is the entries the diffs carry, one per deposit credit, fill, fee and Exit; open orders and Exit pieces still scheduled come from openOrders.

history.ts
import { historyCsv, type HistoryEntry, type HistoryFilter } from '@privium/sdk'

const filter: HistoryFilter = { kinds: ['fill', 'fee'], fromCrossing: 1000n, toCrossing: 2000n }
const entries: HistoryEntry[] = []
let cursor: string | undefined
for (;;) {
  const page = await privium.readHistory(filter, cursor)
  entries.push(...page.entries)
  cursor = page.cursor
  if (!page.hasMore) break
}
const csv = historyCsv(entries)
Parameter Type Meaning
filter HistoryFilter (optional) Which entries to keep, all of them when absent. Its fromCrossing and toCrossing bound the Crossings read, and its asset narrows the enclave's list to that asset.
cursor string (optional) A cursor a previous page returned: the read continues after that Crossing. Absent, it starts at the filter's fromCrossing, or at Crossing 0.

Each call:

  1. Sets the span: from the filter’s fromCrossing (0 when absent), or from one past cursor when that is later, to the filter’s toCrossing (264−12^{64} - 1 when absent). A span with no Crossing in it returns an empty page with no request.
  2. Asks the enclave for the span’s entry Crossings with a status Intent, as openOrders sends it with a range, naming the filter’s asset when it has one. The enclave answers with up to 256 Crossings of the span, through the last committed one, that hold the account’s entries.
  3. Builds a version 2 bundle over those Crossings, for the whole account or for the filter’s asset (disclose), and reads one page of it with readBundle over the span: up to 24 of the listed Crossings through GET /v1/ledger/diffs, each diff pinned to its Commit and decrypted in the process.
  4. Parses each entry as a HistoryEntry and keeps those the whole filter selects.

A page therefore fetches only the diffs that carry the account’s entries.

Field Type Meaning
entries HistoryEntry [] The entries on this page the filter keeps.
cursor string Where the page ended: the last Crossing it read, or the end of the span the enclave reported when it listed none. Pass it for the next page, and once hasMore is false, for the Crossings committed since.
hasMore boolean true while listed Crossings remain, on this page's list or the enclave's next one: call again with cursor.

While hasMore is true, call again with the cursor it returned: the next call goes on after the last Crossing read, through the rest of the enclave’s list and then its next one. Once hasMore is false, the same cursor later reads only the Crossings committed since. A page raises what openOrders and readBundle raise, and an entry that is not a valid HistoryEntry throws zod’s ZodError.

readHistory for a bundle#

A reader holding a bundle calls the exported readHistory(bundle, api, cursor, filter), with no account. It reads one page with readBundle, passing the filter’s fromCrossing and toCrossing as its range, and keeps the entries the whole filter selects. A version 2 bundle’s page holds only the Crossings the bundle lists.

Parameter Type Meaning
bundle ViewingBundle The viewing bundle to read with.
api PriviumApi | string A contract client, or the API's base URL.
cursor string (optional) A cursor a previous page returned: the read continues after it. Absent, it starts at the first diff in range.
filter HistoryFilter (optional) Which entries to keep, all of them when absent. Its fromCrossing and toCrossing also bound the diffs read.
Field Type Meaning
entries HistoryEntry [] The entries on this page the filter keeps.
cursor string Where the page ended, at its last diff: pass it to read the next page.
hasMore boolean true while the bundle's listed Crossings in range remain after this page (for version 1, any diffs in range): call again with cursor.

HistoryFilter#

Field Type Meaning
asset string (optional) Keeps entries of this mint. privium.readHistory also asks the enclave only for this asset's entry Crossings.
kinds ( HistoryEntry ['kind'])[] (optional) Keeps entries of these kinds.
fromCrossing bigint (optional) Keeps entries at or after this Crossing; readHistory reads diffs from it on.
toCrossing bigint (optional) Keeps entries at or before this Crossing; readHistory reads diffs up to it.
fromDate string (optional) Keeps entries at or after this time, in any form Date.parse reads.
toDate string (optional) Keeps entries at or before this time.

historyCsv#

historyCsv(entries) is the history as CSV: a header row, then one row per entry, in these columns:

Column Holds
kind deposit, fill, exit or fee.
id The entry's id.
asset The entry's mint.
crossing The Crossing that wrote the entry.
time When that Crossing committed, ISO 8601 in UTC.
amount Base units moved by a deposit, an Exit or a fee.
pair A fill's pair id, baseMint_quoteMint.
size A fill's size in base units.
crossedSize Base units crossed inside the Pool.
crossedPrice The crossed part's price.
routedSize Base units routed through the Residual swap.
routedPrice The routed part's price.
feeMint A fill's fee asset.
feeAmount A fill's fee in base units.
destination An Exit's destination.
transaction A deposit's or Exit's transaction, or a fill's Residual swap.

Every cell is quoted, with quotes inside doubled, and a cell that starts with =, +, @, a tab or a carriage return gets a leading ', so a spreadsheet reads it as text. CRLF separates the rows, and the last row ends without one.