An SDK call fails in one of four ways: an SdkError from the SDK’s own checks, an ApiClientError when the API answers with its error envelope (intake’s refusals of an Intent among them), zod’s ZodError when a request or a response does not match the contract, and a plain Error from the byte layer. An order the enclave accepts but cannot fund is none of these: it is answered, as a rejected order.
import { ApiClientError } from '@privium/sdk/contract'
import { SdkError } from '@privium/sdk'
const { items } = await privium.api.markets({ q: 'SOL', quote: 'USDC' })
try {
const submission = await privium.trade({ pair: items[0].pair, side: 'buy', size: '1' })
if (submission.state === 'unsent') await submission.retry()
} catch (error) {
if (error instanceof SdkError && error.code === 'PRICE_STALE') console.log('Place a limit order, or retry when the mid is fresh.')
else if (error instanceof ApiClientError && error.body.error.retryable) console.log('Retry:', error.message)
else throw error
}
SdkError#
| Member | Signature | Meaning |
|---|---|---|
code |
code: string |
The stable code to branch on. |
stage |
stage: 'validation' | 'read' | 'wallet' | 'send' |
Where the call failed: validation, read, wallet or send. |
constructor |
new SdkError(code: string, message: string, stage?: 'validation' | 'read' | 'wallet' | 'send') |
An error with a code and message; the stage defaults to validation. |
name is SdkError and message is a sentence a screen can show. Branch on code; stage says where the call stopped:
| Stage | Meaning |
|---|---|
validation |
The call refused its input, or the market's or account's state, before it sent its own Intent or request. |
read |
A read of public state failed or did not verify. |
wallet |
The wallet's signature did not verify. |
send |
A sealed Intent could not be delivered. |
SdkError codes#
Every code the SDK throws, with the calls that throw it. Each call’s page lists its own codes with their exact messages.
| Code | Stage | Raised by | Meaning |
|---|---|---|---|
VALIDATION_ERROR |
validation | toBaseUnits, priceToUnits, trade, exit, previewExit, deposit, watchExits, watchEscape |
An amount or price is not a nonnegative decimal within the asset's precision, an Exit amount is below the smallest denomination, an Exit preview has a zero amount or unit, the Ring lookup refused the destination, or a watchExits or watchEscape poll interval is under 100 ms. Nothing was sent: correct the input. |
BAD_LIMIT |
validation | priceToUnits, trade |
The limit or size is zero, the price is off the pair's grid, or no route bound fits a market order's size. Change the price or size, or retry the market order. |
CONFIGURATION_REQUIRED |
validation, read | estimateFee, trade, openOrders, pendingExits, cancel, exit, deposit, disclose, receipt, readBalances, watchEvents, watchFills, watchExits, requestEscape, claimEscape, readHistory |
The market's fee rate is not set as integer basis points, the Exit asset's denominationUnit is null, or the API's configuration names another Pool program than the one connected to. For the last, connect again. |
SIGNATURE_INVALID |
wallet | connect |
The wallet's signature of the account message does not verify against its public key. The adapter must return the raw 64-byte Ed25519 signature. |
PROGRAM_UNAVAILABLE |
read | decodeEnvelope, trade, openOrders, pendingExits, cancel, exit, deposit, disclose, receipt, readBalances, watchEvents, watchFills, watchExits, requestEscape, claimEscape, readHistory |
The active enclave key's attestation is not indexed yet: GET /v1/config serves its quoteHash as zeros, and the SDK seals nothing to a key it has not checked on chain. Retry once the quote is indexed. |
DECRYPTION_FAILED |
read | decodeEnvelope, trade, openOrders, pendingExits, cancel, exit, disclose, receipt, readBalances, watchFills, watchExits, requestEscape, claimEscape, readHistory |
An envelope is not base64, or opens under none of the enclave keys the instance holds with a valid enclave signature: another account's reply, or bytes altered on the way. watchFills passes over such envelopes; decodeEnvelope and intake's replies throw it. |
INTAKE_UNAVAILABLE |
send, read | trade, openOrders, pendingExits, cancel, exit, disclose, receipt, readBalances, watchExits, requestEscape, claimEscape, readHistory |
Intake was unreachable for an Intent whose answer the call needs: the account's registration before its first Intent, or a status read. Retry the call. |
ESCAPE_ACTIVE |
validation, read | trade, exit, readBalances, requestEscape, claimEscape |
The Escape is active: trading and Exits are closed. trade finds its market's trading at escape, and exit finds the Ledger frozen when it reads balances. readBalances throws it at stage read when the Ledger root is frozen and the instance holds no snapshot at that root: recover one with recoverBalancesFromHistory. |
ASSET_NOT_ADMITTED |
validation, read | trade, exit, readBalances, recoverBalancesFromHistory, requestEscape, claimEscape |
An asset of the call has no Registry index yet. trade has requested the pair's admission before throwing: retry when the market reads open. At stage read: exit finds an open order's market missing from the first page of GET /v1/markets, or a balance read finds a committed leaf whose asset the API does not list as admitted. |
PRICE_STALE |
validation | trade |
A market order needs a fresh mid within the confidence bound κ, and the mid is missing, stale or too wide. Retry, or place a limit order. |
ABOVE_MAX_SLIPPAGE |
validation | trade |
A market order's route bound for its size is wider than maxSlippageBps; the message names the bound in bps. Nothing is sent. Raise maxSlippageBps, lower the size, or place a limit order. |
UPSTREAM_UNAVAILABLE |
read | openOrders, pendingExits, exit, disclose, readBalances, watchEvents, watchFills, watchExits, requestEscape, claimEscape, readHistory |
The event stream did not open, the enclave's reply to a status read held no status, or the enclave's history list did not move its nextFrom on while disclose paged through it. Retry. |
ASSET_UNSUPPORTED |
validation, read | exit, deposit, watchExits |
The mint is not among the assets on the first page of GET /v1/markets (for watchExits, or is listed with no Registry index), or the Ring deposit does not accept it. |
INSUFFICIENT_BALANCE |
validation | exit, requestEscape, claimEscape |
exit: the balance in the asset, less the account's scheduled Exit pieces and its open orders' reservations, does not cover the pieces, and no piece was sent. requestEscape: the account holds no committed balance above zero in the asset. claimEscape: none at the request's leaf and mint. |
INDEXER_UNAVAILABLE |
read | exit, readBalances, lastKnownBalances, recoverBalancesFromHistory, requestEscape, claimEscape |
A balance read found the Ledger moving: through four attempts 100 ms apart, the enclave's status kept naming another root or Crossing than the LedgerRoot account. For an Escape rebuild, the public diffs end before the frozen Crossing. Retry. |
ROOT_NOT_ON_CHAIN |
read | exit, readBalances, requestEscape, claimEscape |
The leaf page the API served for a balance read names another root, Crossing or slot than the LedgerRoot account read on chain. |
MERKLE_PROOF_INVALID |
read, validation | exit, readBalances, recoverBalancesFromHistory, requestEscape, claimEscape |
A balance read's leaf page omits a position the status named, or returns one it did not. For an Escape: the public diffs do not chain root to root, the Ledger rebuilt from them does not reach the root on chain, the leaf is not under the frozen root with the account's owner tag, or the request account does not sit at the address of its leaf and mint. |
CURSOR_EXPIRED |
read | recoverBalancesFromHistory, requestEscape, claimEscape |
An Escape rebuild's diff page announced more diffs without moving its cursor past the one requested. Retry. |
CHAIN_REFUSED |
read | watchExits |
The public record at an Exit piece's Crossing and index names another mint, recipient or amount than the signed piece the enclave reported. |
ESCAPE_NOT_READY |
validation | requestEscape, claimEscape |
requestEscape while GET /v1/trust shows no Escape with a frozen root, or claimEscape when the request account is absent or not the program's. Request once the Escape is open; claim once the request has landed. |
ALREADY_CLAIMED |
validation | claimEscape |
The request's balance has been claimed and paid. |
SHARES_PENDING |
validation | claimEscape |
Fewer than t Council shares have combined on the request. Claim once watchEscape reads claimable. |
An Intent intake did not take#
trade, cancel, exit and receipt do not throw when intake is unreachable. When intake answers INTAKE_UNAVAILABLE, or fetch fails at the network, the call returns its Submission as unsent, holding the sealed bytes; exit returns its ExitSubmission with the piece intake did not take, and every piece after it, left unsent. retry() sends exactly those bytes again, and intake answers identical bytes once. Calls that need the enclave’s answer to go on, the registration before an instance’s first Intent and the status read of openOrders, pendingExits, watchExits, readBalances, disclose, readHistory and exit’s balance check, throw INTAKE_UNAVAILABLE instead.
Refusals#
An Intent the enclave refuses at intake is not unsent. Intake answers with the refusal’s own contract code, its HTTP status and retryable: false, at stage send, and the call throws it as an ApiClientError: INSUFFICIENT_BALANCE for an exit piece the unreserved balance does not cover, ORDER_EXPIRED for an Intent past its expiry slot, NONCE_USED for a nonce at or below the watermark or accepted under other bytes, ORDER_NOT_CANCELLABLE for a cancel whose order is no longer open, ESCAPE_ACTIVE for a trade, cancel or exit once the Escape is open, RECEIPT_CLAIM_FALSE for a Receipt request whose at-least claim does not hold, among the codes POST /v1/intake lists. The call keeps no unsent work for a refused Intent, so there is nothing to retry(): show the refusal, and once its cause is gone make a new call, which seals a new Intent under a fresh nonce.
Rejected orders#
An order the enclave accepts but cannot fund is answered, not thrown. It comes back in results and on watchFills as an OrderResult with state rejected and a reason, and its nonce is consumed:
reason |
The enclave found |
|---|---|
unfunded |
The account’s unreserved balance does not cover the order’s reservation, at intake or at a later Crossing. |
below-minimum |
The order’s size is under one denomination unit of the base, the base asset’s denominationUnit (Asset). Intake answers it at once. |
What intake checks, in order, is in What intake checks.
ApiClientError#
Every privium.api method throws ApiClientError for an answer that is the API’s error envelope, whatever its HTTP status, and the SDK’s calls pass it through unchanged.
| Member | Holds |
|---|---|
status |
The HTTP status. |
body |
The envelope, { error: { code, message, retryable, stage, fieldErrors?, programError?, retryAfterSeconds?, requestId? } } (Errors). |
code |
body.error.code. |
message |
body.error.message. |
An answer that is not JSON becomes UPSTREAM_UNAVAILABLE, retryable, for HTTP 500 and above, and INTERNAL_ERROR otherwise, both at stage read. The API’s codes:
| 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. |
Show message, keep the last state you verified, and retry only when retryable is true, after retryAfterSeconds when it is present.
Contract validation#
The contract client checks every request body against the contract before sending it (deposit builds, intake, Escape relays and builds, and the RPC relay) and parses every response with the server’s own schema. watchEvents parses each event, and every decrypted reply and history entry parses the same way. Input or an answer that does not match throws zod’s ZodError, with the failing path in its issues. A ZodError from a response means the API answered outside the client’s contract version; every response names the server’s in X-Contract-Version.
Errors from the byte layer#
The wire, crypto, viewing, Receipt and reader helpers throw a plain Error whose message names the failure:
| Message | Thrown by |
|---|---|
Noncanonical scalar |
commitment |
Truncated HPKE ciphertext |
hpkeOpen |
Merkle path must have depth 32 |
merkleRoot |
MERKLE_PROOF_INVALID |
decryptLeaf, readBundle |
COMMITMENT_INVALID |
decryptLeaf |
Unsupported note |
decodeDepositNote |
SIGNATURE_INVALID |
openReply |
Invalid PDA seeds |
programAddress |
No program address |
programAddress |
Invalid Escape request account |
decodeEscapeClaimAccount |
Escape amount must be positive |
createEscapeClaimProof |
Escape request is not claimable by this owner |
createEscapeClaimProof |
Escape amount does not match the threshold ciphertext |
createEscapeClaimProof |
CONFIGURATION_REQUIRED |
fundingReservation |
Invalid asset scale |
fundingReservation |
Invalid nonce time or counter |
nonceAt |
ROOT_NOT_ON_CHAIN |
verifyChainRootUncached, readLedgerRoot, readBundle |
UNKNOWN_ENCLAVE_KEY |
verifyEnclaveRegistration, verifyActiveEnclave |
INDEXER_UNAVAILABLE |
readBundle |
Select exact or at-least claim |
encodeClaim |
Unknown claim |
decodeClaim |
Invalid cost basis |
decodeCostBasis |
Invalid Receipt span or version |
encodeReceiptBody |
MALFORMED_RECEIPT |
decodeReceipt |
Invalid asset disclosure |
decodeRequestClaim |
Unknown request claim |
decodeRequestClaim |
Invalid Receipt span or claims |
encodeReceiptRequest |
Invalid viewing node |
deriveNode |
Invalid viewing period |
coveringNodes |
Invalid history Crossing |
compressCrossings |
MALFORMED_BUNDLE |
decodeViewingBundle |
OUT_OF_SCOPE |
keyFromBundle |
Invalid hexadecimal |
unhex |
Expected {n} bytes |
fixed |
Integer exceeds u{size * 8} |
uint |
Signed integer overflow |
int |
Truncated wire message |
Reader.take |
Wire field exceeds limit |
Reader.bytes |
Wire array exceeds limit |
Reader.array |
Invalid option tag |
Reader.opt |
Trailing wire bytes |
Reader.end |
Invalid trade intent |
encodeIntent |
Invalid side |
decodeIntent |
Invalid intent padding |
decodeSignedIntent |
Invalid status history range |
encodeExtendedIntent, decodeSignedExtendedIntent |
Extended intent too large |
encodeSignedExtendedIntent |
Invalid padding |
decodeSignedExtendedIntent |
Unknown extended intent |
decodeSignedExtendedIntent |
Invalid destination |
decodeSignedExtendedIntent |
Unknown extended kind |
decodeSignedExtendedIntent |
Not a balance leaf |
decodeLeaf |
Diff writes must be strictly sorted |
encodeDiff |
Unknown diff format |
decodeDiff |
The platform’s own errors pass through as well: Web Crypto’s OperationError for an AES-GCM tag that does not verify, the HPKE library’s OpenError for a ciphertext that does not open, the base58 and base64 decoders’ errors, and the abort error of an aborted stream.