• Reading the docs…
Start trading

SDK

trade

privium.trade places a market or limit order in one call: it reads the market, sets the limit, builds the Intent, signs it with the account’s auth key, seals it to the enclave and submits it to intake. No wallet prompt, and no transaction of the account’s lands on chain.

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

const market = await privium.trade({ pair, side: 'buy', size: '0.5' })
const limit = await privium.trade({ pair, side: 'sell', size: '0.5', limit: '210.25' })
const spend = await privium.trade({ pair, side: 'buy', size: '100', sizeIn: 'quote' })

if (market.state === 'unsent') await market.retry()

Parameters#

Parameter Type Meaning
pair string The market's pair id, baseMint_quoteMint, as the market list returns it.
side 'buy' | 'sell' buy or sell the base asset.
size string A decimal amount in whole tokens of the base, or of the quote when sizeIn is quote.
sizeIn 'base' | 'quote' (optional) base, the default, or quote. A quote size becomes the largest base size it funds at the limit, with the fee for a buy.
limit string (optional) A decimal limit price, quote per base. Absent, the order is a market order.
expirySlot bigint (optional) The slot the order expires at. Absent, the market's current slot plus ⌈60,000 / slotTimeMs⌉ slots, about one minute.
maxSlippageBps number (optional) A market order's maximum slippage in basis points, a whole number from beta0Bps to 1,000; 300 when absent. The protective limit sits this far from the mid, and a route bound wider than it throws ABOVE_MAX_SLIPPAGE. A limit order ignores it.

What it does#

  1. Reads GET /v1/config for the active enclave key (The enclave key).
  2. Reads the market with GET /v1/markets/{pair}. A market whose trading is escape throws ESCAPE_ACTIVE. A market that is not open, or whose base or quote has no Registry index, gets an admission request (POST /v1/markets/{pair}/admit) and the call throws ASSET_NOT_ADMITTED.
  3. Requires the market’s feeBps to be set, as integer basis points, for a buy or a sell.
  4. Sets the limit. A limit order converts limit exactly at the pair’s priceExponent, and needs no mid: it rests while the mid is stale. A market order needs a mid that is present, not stale, no older than the config’s maxPriceAgeMs and within the confidence bound κ, takes it at the pair’s priceExponent with any finer digits dropped, reads the market again with its exact size and side, and checks that size’s route bound: it must match the size and side, be at least β₀ and stay below 10,000 bps (BAD_LIMIT), and be no wider than maxSlippageBps (ABOVE_MAX_SLIPPAGE). It then sets the protective limit from the mid and maxSlippageBps, as Market and limit gives it. maxSlippageBps defaults to DEFAULT_MAX_SLIPPAGE_BPS, 300, and must be a whole number from the config’s beta0Bps to 1,000 (BAD_LIMIT).
  5. Sets the size. A quote size (sizeIn: 'quote') becomes the largest base size whose cost at the limit, with the fee for a buy, fits it. A quote-sized market order quotes the route bound again for that base size, and a buy whose reservation at the new limit exceeds the budget throws BAD_LIMIT.
  6. Registers the account with the enclave before the instance’s first Intent (The one signature).
  7. Builds the 73-byte trade Intent with a fresh nonce and the expiry, signs it with the auth key, pads it to 160 bytes and seals it with HPKE to the active enclave key, read again from GET /v1/config just before (Intent).
  8. Submits it with POST /v1/intake and opens the replies; an envelope that does not open throws DECRYPTION_FAILED, and each order result goes through the instance’s order tracking.

Returns#

Submission#

Field Type Meaning
nonce bigint The Intent's nonce.
sealed string The sealed Intent, base64: what intake receives, and what retry sends again unchanged.
state 'unsent' | 'accepted' accepted once intake took the Intent; unsent while intake is unreachable. An Intent intake refuses throws instead.
ticket string (optional) Intake's ticket for the Intent, a 32-byte hash in base64; set once accepted.
results PrivateResult [] The enclave's replies from intake's answer, decrypted and checked against the enclave's signing key; an order result the instance already holds in that state or a later one is left out.
retry () => Promise< Submission > Sends the same sealed bytes again and resolves to this submission, updated.

An unreachable intake does not throw. When intake answers INTAKE_UNAVAILABLE, or fetch fails at the network, the submission comes back unsent with its sealed bytes, and retry() sends exactly those bytes again: identical bytes are answered once, with the same ticket and the same replies. An Intent intake refuses throws with the refusal’s own code and leaves nothing to retry (Refusals).

results holds the order’s first OrderResult, from intake’s answer, unless the instance already holds that state or a later one for the order (Order tracking). An order the enclave accepts but cannot fund is answered as rejected with its reason, not thrown.

After intake#

Intake answers with the order’s first state: waiting for Crossing k, or rejected with the reason below-minimum when its size is under one denomination unit of the base, the base asset’s denominationUnit (Asset), or unfunded when the unreserved balance does not cover its reservation. From then on each Crossing the order takes part in sends it one more state, on watchFills:

State When
filled It fills, and what remains is under one denomination unit of the base: that remainder finishes and its reservation is released.
partly-filled It fills in part and at least one unit remains, which keeps resting. It keeps this state at each later Crossing that gives it no new fill.
resting Nothing of it has filled and it takes no fill at this Crossing: its limit is not met, or the pair has no valid mid.
expired Its expiry slot is before the Crossing’s cutoff. It leaves the book and its reservation is released.
rejected unfunded: the balance no longer covers its reservation at this Crossing.
cancelled A cancel Intent took it out, answered at once.

A filled or partly filled state carries the crossed part, the routed part and the fee. A market order runs the same way under its protective limit (Market and limit). Without expirySlot, an order of either kind expires about one minute after it is placed.

Errors#

Code Stage Message
VALIDATION_ERROR validation Enter a nonnegative decimal amount.
VALIDATION_ERROR validation Amount has more precision than this asset.
VALIDATION_ERROR validation Enter a decimal price at the admitted pair precision.
BAD_LIMIT validation The price is not a multiple of the admitted pair precision.
CONFIGURATION_REQUIRED validation The fee rate must be integer basis points between 0 and 10000.
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.
ESCAPE_ACTIVE validation Trading is closed while the Escape is active.
ASSET_NOT_ADMITTED validation Admission was requested. Retry when the asset is admitted.
PRICE_STALE validation A fresh mid within the confidence bound is required for a market order.
BAD_LIMIT validation Max slippage must be {this.config.params.beta0Bps} to {MAX_SLIPPAGE_BPS} bps.
BAD_LIMIT validation The limit price must be positive.
BAD_LIMIT validation The size must be positive.
BAD_LIMIT validation A route bound for this size is required.
ABOVE_MAX_SLIPPAGE validation The route needs {bound.bps} bps, above the {maxSlippageBps} bps allowed.
BAD_LIMIT validation The route bound changed. Refresh the size estimate.
  • The API’s errors throw ApiClientError: NOT_FOUND for an unknown pair, and every intake error but INTAKE_UNAVAILABLE.
  • A size or limit above 264−12^{64} - 1 units throws a plain Error, Integer exceeds u64.

Sizing helpers#

The order ticket’s numbers, computed exactly in bigint, before placing the order:

ticket.ts
import { estimateFee, fromBaseUnits, fundingReservation, priceToUnits, toBaseUnits, unreservedBalance } from '@privium/sdk'

const { items } = await privium.api.markets({ q: 'SOL', quote: 'USDC' })
const panel = await privium.api.market(items[0].pair)
const { base, quote, priceExponent } = panel.market

const order = {
  side: 'buy',
  size: toBaseUnits('0.5', base.decimals),
  limit: priceToUnits('210.25', priceExponent),
  priceExponent,
  baseDecimals: base.decimals,
  quoteDecimals: quote.decimals,
  feeBps: panel.feeBps,
} as const

const notional = fundingReservation({ ...order, feeBps: 0 })
const fee = estimateFee(notional, panel.feeBps)

const { balances } = await privium.readBalances()
const held = balances.find((b) => b.asset.mint === quote.mint)?.balance ?? 0n
console.log(fromBaseUnits(fee, quote.decimals), fromBaseUnits(unreservedBalance(held, [order]), quote.decimals))

toBaseUnits#

A decimal string in whole tokens to base units, with no floating point: toBaseUnits('0.5', 9) is 500000000n.

Parameter Type Meaning
value string A nonnegative decimal string.
decimals number The asset's decimals, 0 to 18.
Code Stage Message
VALIDATION_ERROR validation Enter a nonnegative decimal amount.
VALIDATION_ERROR validation Amount has more precision than this asset.

fromBaseUnits#

Base units to a decimal string in whole tokens, trailing zeros dropped: fromBaseUnits(500000000n, 9) is '0.5'.

Parameter Type Meaning
amount bigint The amount in base units.
decimals number The asset's decimals.

priceToUnits#

A decimal price, quote per base, to the integer count of 10exponent10^{\text{exponent}} quote whole tokens per base whole token that Intents carry. A price written with more decimal places than the unit carries must still be a whole number of units.

Parameter Type Meaning
value string A nonnegative decimal price, quote per base.
exponent number The pair's priceExponent, −128 to 127.
Code Stage Message
VALIDATION_ERROR validation Enter a decimal price at the admitted pair precision.
BAD_LIMIT validation The price is not a multiple of the admitted pair precision.

estimateFee#

quoteAmount × feeBps / 10,000, rounded down, as each fill’s fee is charged. The order ticket shows it on the order’s notional.

Parameter Type Meaning
quoteAmount bigint The amount in quote base units.
feeBps number | null (optional) The fee rate in basis points, as MarketPanel.feeBps gives it.
Code Stage Message
CONFIGURATION_REQUIRED validation The fee rate must be integer basis points between 0 and 10000.

fundingReservation#

What an order holds of its funding balance while it is open: its base size for a sell, and for a buy its size times its limit times (1 + fee rate), in quote units rounded up. A sell reads only its size. For a buy, a fee rate of null or outside 0 to 10,000 throws a plain Error, CONFIGURATION_REQUIRED, and decimals or an exponent out of range throw Invalid asset scale.

Parameter Type Meaning
order FundingOrder The order's side, remaining size, limit and the pair's scales.

FundingOrder#

Field Type Meaning
side 'buy' | 'sell' buy or sell the base.
size bigint The order's remaining size in base units.
limit bigint The limit in price units.
priceExponent number The pair's priceExponent, −128 to 127.
baseDecimals number The base asset's decimals, 0 to 18.
quoteDecimals number The quote asset's decimals, 0 to 18.
feeBps number | null (optional) The fee rate in basis points, 0 to 10,000.

unreservedBalance#

The part of a balance no open order holds: the balance less each order’s fundingReservation. It is what a new order can draw on.

Parameter Type Meaning
balance bigint The balance in base units.
orders readonly FundingOrder [] The open orders that draw on this balance's asset (buys for a quote balance, sells for a base balance), each at its remaining size.