• Reading the docs…
Start trading

SDK

exit

privium.exit withdraws an amount from the account’s balance to any Solana address, or to a Helius Ring deposit. It splits the amount into denominations in the caller’s process and seals one exit Intent per piece, each signed by the auth key with no wallet prompt; the enclave schedules each piece at a release slot of its own, and each is paid from a vault once a Commit lists it.

exit.ts
declare const destination: string // any address, such as a fresh wallet's

const { items } = await privium.api.markets({ q: 'SOL', quote: 'USDC' })
const usdc = items[0].quote

const exit = await privium.exit({ asset: usdc.mint, amount: '120.5', destination })
if (exit.state === 'unsent') await exit.retry()
console.log(exit.pieces.length, exit.scheduledAmount, exit.remainder)

To a Ring deposit, check the destination first and pass kind: 'ring':

exit-ring.ts
declare const ringDeposit: string

const { items } = await privium.api.markets({ q: 'SOL', quote: 'USDC' })
const usdc = items[0].quote

const lookup = await privium.api.ring(ringDeposit)
if (lookup.kind === 'ring-deposit') {
  await privium.exit({ asset: usdc.mint, amount: '120.5', destination: ringDeposit, kind: 'ring' })
}

Parameters#

Parameter Type Meaning
asset string The mint to exit, base58.
amount string A decimal amount in whole tokens.
destination string The address to pay, base58.
kind 'address' | 'ring' (optional) address, the default, for any address; ring for a Helius Ring deposit.
expirySlot bigint (optional) The slot each piece's exit Intent expires at; they never expire when absent.

What it does#

  1. Reads GET /v1/config for the active enclave key (The enclave key).
  2. Checks that destination decodes as a 32-byte base58 address.
  3. For kind: 'ring', reads GET /v1/rings/{address}. The destination must be a ring-deposit with its Ring record, and the Ring must accept any asset or list asset among its accepted mints.
  4. Finds asset among the assets of the markets GET /v1/markets returns on its first page. It must have a Registry index and a denominationUnit (Asset). Converts amount to base units.
  5. Splits the amount as previewExit does, with the asset’s denominationUnit as the unit δ\delta: one piece δ⋅2j\delta \cdot 2^j for each set bit jj of ⌊amount/δ⌋\lfloor \text{amount} / \delta \rfloor below the Pool’s denominationCount. An amount that gives no piece throws VALIDATION_ERROR here.
  6. Registers the account with the enclave before the instance’s first Intent (The one signature).
  7. Checks the whole batch before any piece is sealed. It reads the account’s balances as readBalances does, with the status that read takes, and throws ESCAPE_ACTIVE when the Escape leaves it no status. It then reserves out of the balance in asset the account’s pieces already scheduled in that asset (those no Commit has listed yet) and the fundingReservation of each open order that asset funds, on its remaining size at the configured fee rate. The pieces’ total must fit in what is left, or the call throws INSUFFICIENT_BALANCE with nothing of the Exit sent.
  8. Seals every piece before sending any: an exit Intent each, carrying the asset index, the piece’s amount, the destination, the destination kind, a fresh nonce and the expiry, signed under privium/extended-intent/v2, padded to 4,096 bytes and sealed to the active enclave key.
  9. Submits the pieces in order with POST /v1/intake and opens each one’s replies, stopping at the first piece intake does not take.

The enclave checks again, for each piece, that the unreserved balance covers it, counting every device’s open orders and scheduled pieces; its answer decides. It keeps the piece as one piece of its denomination and samples its release slot. The amount stays in the balance, reserved, until the first Crossing opened at or after that slot debits it and lists the piece in its Commit’s exits root; from that Commit on the piece is releasable to the destination (From request to release).

Returns#

ExitSubmission#

Field Type Meaning
nonce bigint The first piece's nonce.
sealed string The first piece's sealed Intent, base64.
state 'unsent' | 'accepted' accepted once intake took every piece; unsent while any piece is unsent.
ticket string (optional) The first piece's intake ticket; set once that piece was accepted.
results PrivateResult [] Every piece's decrypted replies, in piece order.
pieces Submission [] One Submission per denominated piece, smallest first, each with its own nonce, sealed bytes and replies.
remainder bigint Base units that stay in the balance: the part below the smallest denomination, and any part above the largest.
scheduledAmount bigint Base units the pieces carry: the amount less remainder.
retry () => Promise< ExitSubmission > Sends the unsent pieces in order, each with its original sealed bytes, stopping again at the first intake does not take, and resolves to this submission, updated.

Each piece is a Submission of its own, whose results hold its ExitUpdate in state scheduled. An unreachable intake leaves a piece unsent without throwing, and the batch stops there, so the pieces after it stay unsent too; retry() sends the unsent pieces in order with their original sealed bytes, stopping again at the first intake does not take, and intake answers identical bytes once. A piece intake refuses throws its refusal with its own code, and the pieces after it are not sent (Refusals). The pieces intake accepted before an error are scheduled all the same: pendingExits recovers them with their release slots. Each piece’s progress through committed to released, with its release transaction, comes from watchExits.

Errors#

Code Stage Message
VALIDATION_ERROR validation Enter a nonnegative decimal amount.
VALIDATION_ERROR validation Amount has more precision than this asset.
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 target.reason ?? 'This destination is not a registered Ring recipient.'
ASSET_UNSUPPORTED validation target.reason ?? 'The Ring does not accept this asset.'
ASSET_NOT_ADMITTED validation The asset is not admitted.
CONFIGURATION_REQUIRED validation This asset needs an explicit denomination unit.
VALIDATION_ERROR validation The amount is below the smallest exit denomination.
ESCAPE_ACTIVE validation Exits are closed while Escape is active.
ASSET_NOT_ADMITTED read An open order market is unavailable.
INSUFFICIENT_BALANCE validation The unreserved balance does not cover this exit.
VALIDATION_ERROR validation The amount and denomination must be positive.
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 destination that is not base58, or not 32 bytes, throws a plain Error before any Intent is sealed.
  • An amount above 264−12^{64} - 1 base units throws a plain Error, Integer exceeds u64.
  • The API’s errors throw ApiClientError. Intake refuses a piece with INSUFFICIENT_BALANCE when the account’s other Intents reserved the balance first, ESCAPE_ACTIVE once the Escape is open, ORDER_EXPIRED past the piece’s expirySlot, and NONCE_USED for a nonce consumed under other bytes (POST /v1/intake).

previewExit#

The split and delay an Exit will take, computed locally before the trader confirms. It reads only the connected configuration and sends nothing.

preview.ts
import { fromBaseUnits, toBaseUnits } from '@privium/sdk'

const { items } = await privium.api.markets({ q: 'SOL', quote: 'USDC' })
const usdc = items[0].quote

if (usdc.denominationUnit !== null) {
  const preview = privium.previewExit(toBaseUnits('120.5', usdc.decimals), BigInt(usdc.denominationUnit))
  console.log(preview.pieces.map((piece) => fromBaseUnits(piece, usdc.decimals)), preview.meanDelaySlots)
}

For a unit δ, the amount runs as one piece δ·2^j for each set bit j of ⌊amount / δ⌋, for j below the Pool’s denominationCount (Denominations). An admitted asset’s denominationUnit in the market list is the unit exit splits with, so the preview is the split exit seals.

Parameter Type Meaning
amount bigint The amount in base units.
denominationUnit bigint The asset's denomination unit in base units, Asset.denominationUnit.
Field Type Meaning
pieces bigint[] Each piece's amount in base units, smallest first.
remainder bigint What stays in the balance: the part below the unit, and any part above the configured denominations.
meanDelaySlots number The configured mean of each piece's delay, in slots.
Code Stage Message
VALIDATION_ERROR validation The amount and denomination must be positive.

Escape#

Once the Escape is open, the account takes each asset’s last committed balance out with three calls: requestEscape opens the request, watchEscape follows the Council’s shares, and claimEscape proves the balance and has it paid (Claiming a balance). None of them seals an Intent or prompts the wallet. The SDK builds each proof locally from the account’s keys and its leaves under the frozen root, and the keeper pays each transaction through POST /v1/escape/relay.

escape.ts
declare const destination: string // any address, such as a fresh wallet's

const { items } = await privium.api.markets({ q: 'SOL', quote: 'USDC' })
const usdc = items[0].quote

const opened = await privium.requestEscape({ asset: usdc.mint })
for await (const request of privium.watchEscape(opened.request)) {
  console.log(request.state, `${request.shares.length} of ${request.threshold} shares`)
  if (request.state === 'claimable') break
}
const paid = await privium.claimEscape({ request: opened.request, destination })
console.log(paid.state, paid.transaction)

requestEscape#

Opens the Escape request for the account’s frozen balance in one asset.

Parameter Type Meaning
asset string The mint whose frozen balance to request, base58.
  1. Reads GET /v1/trust: liveness.state must be escape, with its frozen root.
  2. Takes the account’s leaves under the frozen root, with their paths: readBalances returns the instance’s snapshot when it was read at that root, and when it throws ESCAPE_ACTIVE instead, recoverBalancesFromHistory rebuilds the snapshot from the public diffs. Any other error of the read is thrown. The account must hold a balance above zero in asset.
  3. Checks that the snapshot’s root is the frozen root, and that the leaf’s owner tag is the account’s: SHA-256 of privium/owner/v1, the escape public key, the owner salt, the mint and the leaf’s version.
  4. Sends the leaf, its position and path, the escape public key and the owner salt to the relay as a request. The keeper pays escape_request (escape_request).

It returns the relay’s EscapeSubmission. Its request is the EscapeRequest account’s address, which watchEscape and claimEscape take. A second call for the same asset answers with the same request and its transaction.

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.
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.
ESCAPE_NOT_READY validation Escape is not active.
INSUFFICIENT_BALANCE validation No frozen balance is available for this asset.
MERKLE_PROOF_INVALID validation The local leaf does not match the frozen root.

The relay’s refusals throw ApiClientError (POST /v1/escape/relay lists them). The read in step 2 throws the plain errors of readBalances.

watchEscape#

Follows a request from its opening through the Council’s shares to its payment.

Parameter Type Meaning
request string The EscapeRequest account's address.
options { signal?: AbortSignal; pollIntervalMs?: number } (optional) An abort signal, and the milliseconds between reads, at least 100; 1,000 when absent.

Each round it reads GET /v1/escape/requests/{address} and yields the EscapeRequest whenever it differs from the last one yielded: requested, collecting while shares arrive, claimable once threshold shares are in, and paid with the claim’s transaction, after which the generator returns. An answer of NOT_FOUND, for a request the indexer has not recorded yet, yields nothing and the round passes. It waits pollIntervalMs between rounds and ends when the signal aborts; a read in flight then throws the platform’s abort error.

Code Stage Message
VALIDATION_ERROR validation Escape polling interval must be at least 100 ms.

The interval is checked when iteration starts. The API’s other errors throw ApiClientError.

claimEscape#

Proves a combined request’s balance and has it paid to a destination.

Parameter Type Meaning
request string The EscapeRequest account's address: request from requestEscape, or escapeRequestAddress of the leaf.
destination string The address to pay, base58: the wallet, a fresh address or a Helius Ring deposit.
  1. Checks that destination decodes as a 32-byte base58 address.
  2. Reads the account at request through the RPC relay (getAccountInfo at confirmed). It must belong to the program, decode as an EscapeClaimAccount, sit at the address of its own leaf position and mint, be unclaimed, and hold the Council’s combined shares.
  3. Takes the account’s balance at that leaf from the instance’s snapshot. When the snapshot has none there, it reads balances first as requestEscape does in its step 2. It must be a balance of the request’s mint.
  4. Makes the claim proof for that balance and destination (The claim proof).
  5. Sends the request, mint, destination, amount and proof to the relay as a claim. The keeper pays escape_claim, which pays the destination by the settlement rule (The settlement rule), and the relay creates the destination’s token accounts the payout needs.

It returns the relay’s EscapeSubmission, paid once the claim is confirmed.

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.
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.
ESCAPE_NOT_READY validation The Escape request is unavailable.
MERKLE_PROOF_INVALID validation The Escape request address is invalid.
ALREADY_CLAIMED validation This Escape balance was already claimed.
SHARES_PENDING validation Council shares are still arriving.
INSUFFICIENT_BALANCE validation The frozen balance is not available.
  • A destination that is not base58, or not 32 bytes, throws a plain Error before any read.
  • An account that is not 800 bytes with the EscapeRequest discriminator throws a plain Error, Invalid Escape request account.
  • The relay’s refusals throw ApiClientError.

The request address#

Each balance leaf has one EscapeRequest account, at the program address of the seeds escape-req, the leaf’s position as a little-endian u32 and the mint (EscapeRequest). escapeRequestAddress computes it locally, so an account finds its requests from its balances alone:

request-address.ts
import { escapeRequestAddress } from '@privium/sdk'

const { balances } = await privium.readBalances()
for (const { asset, position } of balances) console.log(asset.symbol, escapeRequestAddress(privium.config.programId, position, asset.mint))
Parameter Type Meaning
programId string The program id, base58: privium.config.programId.
index number The leaf's Ledger position: position in readBalances.
mint string The leaf's mint, base58.

The claim proof#

createEscapeClaimProof makes the proof claimEscape sends. With AA and BB the request’s combined pair, CC the leaf’s commitment, yy the escape scalar and Y=yGY = yG its public key, it sets Z=bG−(C−B)Z = bG - (C - B) for the amount bb and requires Z=yAZ = yA, which holds only for the leaf’s committed balance. It then proves that one yy gives both YY and ZZ: a nonce rr from 64 random bytes, R1=rGR_1 = rG, R2=rAR_2 = rA, the challenge ee as SHA-256 of privium/claim/v1 ‖ GG ‖ AA ‖ YY ‖ ZZ ‖ R1R_1 ‖ R2R_2 ‖ program ‖ request ‖ mint ‖ destination read little endian modulo the group order, and z=r+eyz = r + ey. escape_claim checks zG=R1+eYzG = R_1 + eY and zA=R2+eZzA = R_2 + eZ (escape_claim), so the proof pays only that destination, whoever relays it.

Parameter Type Meaning
input { programId: string; request: string; mint: string; destination: string; amount: bigint; account: EscapeClaimAccount ; keys: AccountKeys } The program id, the request address and its mint, the destination, the amount in base units, the decoded request account and the account keys.
randomness Uint8Array (optional) 64 bytes the nonce is drawn from; fresh random bytes when absent.

A request that is not combined, already claimed, of another mint or under another escape key throws a plain Error, Escape request is not claimable by this owner; an amount the pair does not open to throws Escape amount does not match the threshold ciphertext, and a zero amount Escape amount must be positive. The proof’s fields are in EscapeClaimProof.