Build

SDK reference

Every export of @una/sdk: the client and its calls, the errors, the constants, the schemas and the helpers.

@una/sdk 0.1.9 is the API as typed calls. It is an ES module with one dependency, zod, and it runs unchanged in a browser, in a server component and in a Node 22 script. Every response is parsed against the contract's schema before the call returns, so a value has the type its signature says.

The SDK quickstart places a first order with it.

It has two clients. createUna binds a wallet and does each task in one call: it builds the transaction, signs it, submits it and follows it until it settles. createUnaClient holds no wallet and returns unsigned transactions.

The bound client

createUna({ apiUrl, wallet, ...options })

Returns a client bound to one wallet. Una is the type of what it returns, and CreateUnaOptions the type of its argument.

TypeScript
import { createUna } from '@una/sdk'

const una = createUna({ apiUrl: 'https://api.una.markets', wallet })

CreateUnaOptions

apiUrlstringrequired
The API's address.
walletUnaWalletrequired
The wallet every call acts for and signs with. See below.
walletReachesClusterboolean
Set true when the wallet can send to the cluster itself. A wallet with signAndSendTransaction then sends its own transactions and the SDK reports the signature. Default false: the wallet only signs and the API sends.
pollIntervalMsnumber
How often a submitted transaction's status is read. Default 1000.
pollTimeoutMsnumber
How long a submitted transaction is followed. Default 90000.
fetch, headers, credentialssee the unbound client
The options of the unbound client, passed through.

The wallet

wallet is a UnaWallet, any of three shapes:

TypeShapeWhere it comes from
KeypairLike{ publicKey, secretKey }, where publicKey has toBase58() and toBytes() and secretKey is the 64 bytesA Keypair of @solana/web3.js, in a script or on a server. The SDK signs with WebCrypto Ed25519.
WalletStandardLike{ account, features, chain? }A connected Wallet Standard wallet in a browser: its account and its solana:signTransaction feature, and solana:signAndSendTransaction if it has one. WalletStandardAccountLike is the type of account.
UnaSigner{ address, signTransaction(bytes), signAndSendTransaction?(bytes) }Anything else that can sign the bytes of a transaction.

What a write call does

Every write call on the bound client runs the same four steps: it asks the API to build the transaction for the bound wallet, has the wallet sign it, submits it, and asks for its status every pollIntervalMs until it is confirmed or finalized. The last argument of each is call, a FollowCallOptions:

FollowCallOptions

onStatus(status: TxStatus) => void
Called with each status as the transaction moves.
pollIntervalMsnumber
Overrides the client's interval for this call.
pollTimeoutMsnumber
Overrides the client's timeout for this call.
signal, headerssee call below
The fields of CallOptions.

A write call resolves to a BoundTxResult:

BoundTxResult

buildTxBuild
The transaction as the API built it.
txTxStatus
Its final status.
signaturestring
Its signature.

It rejects with a UnaTxError when the wallet declines, the transaction fails or expires, or it has not settled within pollTimeoutMs, and with an ApiClientError when the API refuses to build it.

una.swap({ sell, buy, amount, limit, expiryBatchId? }, call?)

Places an order and follows it. After the transaction settles it reads the order and its batch once.

BoundSwapParams

selladdressrequired
The mint of the token to sell.
buyaddressrequired
The mint of the token to buy.
amountu64 string, above 0required
Atoms of the sell token.
limitu128 string, above 0required
The limit: least atoms of the buy token per atom of the sell token, as Q64.64. una.quote returns one as suggestedLimitQ64.
expiryBatchIdu64 string, above 0
The last batch the order may clear in.

BoundSwapResult, the fields it adds to BoundTxResult

orderAddressaddress
The order's address.
batchIdu64 string
The batch the order joined.
orderOrder | null
The order as read right after the transaction settled, or null if the read failed. Read it again with una.order once the batch clears.
batchBatchDetail | null
The order's batch as read at the same moment, or null.

una.cancelOrder(orderAddress, call?)

Takes back an order of the bound wallet. If the order sits in a sealed batch that has not cleared, the call waits and tries again, for up to two minutes. The build it returns carries outcome: cancelled, filled or expired. Returns a BoundTxResult whose build is a CancelOrderBuild.

una.settleOrder(orderAddress, call?)

Settles an order after its batch has cleared. Returns a BoundTxResult.

una.addLiquidity(pair, { tickLower, tickUpper, amountX, amountY, liquidityDelta? }, call?)

Adds liquidity on a pair over a tick range. The fields are those of POST /v1/pairs/{pair}/liquidity/add without wallet. Returns a BoundTxResult with positionAddress.

una.removeLiquidity(positionAddress, { liquidityDelta, minAmountX?, minAmountY? }, call?)

Removes liquidity from a position. Returns a BoundTxResult.

una.collectFees(positionAddress, call?)

Pays a position's earnings to the bound wallet. Returns a BoundTxResult.

una.settlePosition(positionAddress, call?)

Pays out a position's earnings to its owner. The position may be anyone's. Returns a BoundTxResult.

una.stake({ solver, bondMint, amount }, call?)

Stakes amount atoms of a bond mint behind a solver. Returns a BoundTxResult.

una.requestUnstake(stakeAddress, { amount }, call?)

Moves amount atoms of a stake into its cooldown. Returns a BoundTxResult.

una.withdrawStake(stakeAddress, call?)

Withdraws a stake whose cooldown has passed. Returns a BoundTxResult.

una.claimRewards(stakeAddress, call?)

Pays a stake's rewards to the bound wallet. Returns a BoundTxResult.

una.claimCommission(solverAddress, { tokenIndex? }, call?)

Pays a solver's accrued commission to the bound wallet, which has to be its operator. Without tokenIndex it claims every token with commission accrued. Returns a BoundTxResult.

una.claimCover(batchId, { participant? }, call?)

Claims a share of a slashed batch's cover for one of the bound wallet's orders or positions. participant names which; without it the API picks one that has not claimed. Returns a BoundTxResult.

Reads on the bound client

una.wallet is the bound wallet's address, and una.client is the unbound client underneath. Every read of the unbound client is also on una under the same name. Five of them fill in the bound wallet:

CallWhat it reads
una.balances(call?)The bound wallet's balances.
una.orders(query?, call?)The bound wallet's orders.
una.positions(query?, call?)The bound wallet's positions.
una.stakes(query?, call?)The bound wallet's stakes.
una.batch(id, call?)A batch, with the bound wallet's orders in it and its share of any cover.

The others are the unbound calls unchanged: health, protocol, live, tokens, quote, order, pairs, pair, candles, quoteLiquidity, solvers, solver, batches, batchInput, batchState, publishBatchState and batchesStreamUrl.

UnaTxError

What a write call rejects with when the transaction does not go through.

UnaTxError

failureTxFailure
The stage that failed, a message, whether trying again can help, and the program's error when the program refused.
txStatusTxStatus, may be absent
The last status read, when the transaction was submitted.
messagestring
The failure's message.

Limits and prices

A limit is a Q64.64 ratio of atoms. These four turn it to and from the numbers a person reads. Amounts may be bigint, string or number; results are decimal strings.

ExportWhat it returns
limitQ64(minOut, amount)The limit that accepts no less than minOut atoms of the buy token for amount atoms of the sell token: minOut * 2^64 / amount, rounded up. Throws a RangeError if either is 0 or does not fit a u64.
minOutFromLimitQ64(limit, amount)The least atoms of the buy token a limit accepts for amount: limit * amount / 2^64, rounded down.
formatLimitPrice(limit, sellDecimals, buyDecimals, precision = 6)The limit as a price in whole tokens, buy per sell, to precision decimals.
parseLimitPrice(price, sellDecimals, buyDecimals)The limit for a price typed in whole tokens, such as "162.4", rounded up. Throws a RangeError on anything but a positive decimal.

The unbound client

createUnaClient(baseUrl, options?)

Returns a client that holds no wallet: it reads, and it builds unsigned transactions for a wallet you name in each call. Use it on a server, or wherever signing happens somewhere else. baseUrl is the API's address, https://api.una.markets. createClient is the same function under a shorter name, and UnaClient is the type of what it returns. The bound client carries one as una.client.

TypeScript
import { createUnaClient } from '@una/sdk'

const client = createUnaClient('https://api.una.markets')

options

fetchtypeof fetch
The fetch to use. Defaults to the global one.
headersRecord<string, string>
Headers sent with every request.
credentialsRequestCredentials
The credentials mode passed to fetch.

Every call takes a last argument, call, of type CallOptions:

call

signalAbortSignal
Aborts the request.
headersRecord<string, string>
Headers for this request only.
queryobject
Extra query fields. The calls that take a query set it themselves.

An unbound call resolves to the parsed response or rejects with an ApiClientError.

client.swap({ wallet, sell, buy, amount, limit, expiryBatchId? }, call?)

Builds the transaction that places an order, unsigned. It is client.placeOrder with shorter names: sell and buy are the two mints and limit is the limit as a Q64.64 integer string.

SwapParams

walletaddressrequired
The wallet that signs the transaction and pays its fee.
selladdressrequired
The mint of the token to sell.
buyaddressrequired
The mint of the token to buy.
amountu64 string, above 0required
Atoms of the sell token.
limitu128 string, above 0required
The limit: least atoms of the buy token per atom of the sell token, as Q64.64. una.quote returns one as suggestedLimitQ64.
expiryBatchIdu64 string, above 0
The last batch the order may clear in.

Returns a PlaceOrderBuild: the unsigned transaction, the address the order will have and the batch it joins. Sign it and pass it to client.tx.submit.

Health and protocol: unbound calls

client.health(call?)

Whether the API is serving the program. Calls GET /health. Returns HealthResponse.

client.protocol(call?)

The protocol's settings as the program's configuration holds them, and the mints a stake can be in. Calls GET /v1/protocol. Returns ProtocolParams.

client.live(call?)

The market at this moment in one read: the open batch, the last cleared batch with its prices, the recent batches and the protocol settings. Calls GET /v1/live. Returns LiveOverview.

Tokens and quotes: unbound calls

client.tokens(call?)

Every listed token with its last proven price and the band the next batch may price it in. Calls GET /v1/tokens. Returns TokensResponse.

client.balances(wallet, call?)

A wallet's SOL and its balance of every listed token. Calls GET /v1/wallets/{wallet}/balances, where wallet is the path of the route. Returns WalletBalancesResponse.

client.quote(query, call?)

What an order between two tokens would receive at the last proven prices, and a limit to place it with. Calls GET /v1/quote, where query holds its query fields. Returns QuoteResponse.

Orders: unbound calls

client.orders(query?, call?)

Orders, newest first, filtered by any of the query fields. Calls GET /v1/orders, where query holds its query fields. Returns OrdersPage.

client.order(address, call?)

One order by its address. Calls GET /v1/orders/{address}, where address is the path of the route. Returns Order.

client.placeOrder(body, call?)

Builds the transaction that places an order in the open batch. The sell amount moves from the wallet to the token's vault when it lands. Calls POST /v1/orders/place, where body holds its body fields. Returns PlaceOrderBuild.

client.cancelOrder(address, body, call?)

Builds the transaction that takes an order back. While the order's batch is open it cancels the order and returns its sell amount. After that batch has cleared it settles the order first and cancels whatever remainder moved on into the open batch. Calls POST /v1/orders/{address}/cancel, where address is the path of the route, body holds its body fields. Returns CancelOrderBuild.

client.settleOrder(address, body, call?)

Builds the transaction that settles an order after its batch cleared: the bought tokens go to the owner, and the remainder returns or joins the open batch. Anyone may send it; the keeper does by default. Calls POST /v1/orders/{address}/settle, where address is the path of the route, body holds its body fields. Returns TxBuild.

Pairs and positions: unbound calls

client.pairs(call?)

Every pair with its fee, its price and its liquidity. Calls GET /v1/pairs. Returns PairsResponse.

client.pair(pair, call?)

One pair with its liquidity tick by tick. Calls GET /v1/pairs/{pair}, where pair is the path of the route. Returns PairDetail.

client.candles(pair, query?, call?)

Price candles for a pair, built only from proven batches. Calls GET /v1/pairs/{pair}/candles, where pair is the path of the route, query holds its query fields. Returns CandlesResponse.

client.quoteLiquidity(pair, query, call?)

The token amounts a position over a tick range takes at the pair's current price. Give one amount and it returns the other. Calls GET /v1/pairs/{pair}/quote-liquidity, where pair is the path of the route, query holds its query fields. Returns LiquidityQuote.

client.positions(query?, call?)

Liquidity positions, filtered by wallet or pair. Calls GET /v1/positions, where query holds its query fields. Returns PositionsPage.

client.addLiquidity(pair, body, call?)

Builds the transaction that places liquidity on a pair over a tick range and creates the position. Calls POST /v1/pairs/{pair}/liquidity/add, where pair is the path of the route, body holds its body fields. Returns AddLiquidityBuild.

client.removeLiquidity(address, body, call?)

Builds the transaction that removes liquidity from a position and pays its tokens to the owner. Calls POST /v1/positions/{address}/remove, where address is the path of the route, body holds its body fields. Returns TxBuild.

client.collectFees(address, body, call?)

Builds the transaction that pays a position's earned fees to its owner. Calls POST /v1/positions/{address}/collect, where address is the path of the route, body holds its body fields. Returns TxBuild.

client.settlePosition(address, body, call?)

Builds the transaction that pays a position's earnings to its owner. Anyone may send it; the payment goes to the owner. Calls POST /v1/positions/{address}/settle, where address is the path of the route, body holds its body fields. Returns TxBuild.

Solvers and stake: unbound calls

client.solvers(query?, call?)

Every solver with its stake, its bond in use, its commission and what it has paid its stakers. Calls GET /v1/solvers, where query holds its query fields. Returns SolversPage.

client.solver(address, call?)

One solver with its recent batches and its slashes. Calls GET /v1/solvers/{address}, where address is the path of the route. Returns SolverDetail.

client.stakes(query, call?)

A wallet's stakes with their rewards and any unstake in progress. Calls GET /v1/stakes, where query holds its query fields. Returns StakesPage.

client.stake(body, call?)

Builds the transaction that stakes SOL or a listed liquid staking token behind a solver. Calls POST /v1/stakes/deposit, where body holds its body fields. Returns TxBuild.

client.requestUnstake(address, body, call?)

Builds the transaction that moves part or all of a stake into its cooldown. Calls POST /v1/stakes/{address}/unstake, where address is the path of the route, body holds its body fields. Returns TxBuild.

client.withdrawStake(address, body, call?)

Builds the transaction that returns an unstaked deposit once its cooldown has passed. Calls POST /v1/stakes/{address}/withdraw, where address is the path of the route, body holds its body fields. Returns TxBuild.

client.claimRewards(address, body, call?)

Builds the transaction that pays a stake's rewards to its owner. Calls POST /v1/stakes/{address}/claim, where address is the path of the route, body holds its body fields. Returns TxBuild.

client.claimCommission(address, body, call?)

Builds the transaction that pays a solver's accrued commission to its operator, in every token it has accrued in or in one. Calls POST /v1/solvers/{address}/commission/claim, where address is the path of the route, body holds its body fields. Returns TxBuild.

Batches and cover: unbound calls

client.batches(query?, call?)

Batches, newest first. Calls GET /v1/batches, where query holds its query fields. Returns BatchesPage.

client.batch(id, query?, call?)

One batch: its hashes, its prices, its fill fractions, its solver and bond, its proof or its slash and cover. Pass wallet to get that wallet's orders in the batch and its share of the cover. Calls GET /v1/batches/{id}, where id is the path of the route, query holds its query fields. Returns BatchDetail.

client.batchInput(id, call?)

Every record folded into a batch's input hash, in the order the program folded them. Hashing them in order reproduces inputHash. Calls GET /v1/batches/{id}/input, where id is the path of the route. Returns BatchInputResponse.

client.batchState(id, call?)

The state a cleared batch was solved against and the result posted for it, as its solver published them. With the input records they are everything the guest program reads, so anyone can run the check on the batch. Calls GET /v1/batches/{id}/state, where id is the path of the route. Returns BatchStateResponse.

client.publishBatchState(id, body, call?)

Publishes the state and result of a cleared batch. The API hashes both and accepts them only when the hashes equal the batch's state_hash and result_hash on chain, so what it serves is what the proof commits to. The solver node sends this after each clearing. Calls POST /v1/batches/{id}/state, where id is the path of the route, body holds its body fields. Returns BatchStateResponse.

client.claimCover(id, body, call?)

Builds the transaction that pays a wallet its share of a slashed batch's cover. Calls POST /v1/batches/{id}/cover/claim, where id is the path of the route, body holds its body fields. Returns TxBuild.

Transactions: unbound calls

client.submitTransaction(body, call?)

Hands a signed transaction to the API to send, or reports the signature of one the wallet sent itself. Calls POST /v1/transactions/submit, where body holds its body fields. Returns TxStatus.

client.transactionStatus(id, call?)

Where a submitted transaction stands. Calls GET /v1/transactions/{id}, where id is the path of the route. Returns TxStatus.

client.tx.submit(input)

client.submitTransaction without the call argument.

client.tx.status(id)

client.transactionStatus without the call argument. client.tx is the pair of functions a transaction follower needs: submit once, then ask for the status until it settles.

The batch stream

client.batchesStreamUrl()

Returns the address of the batch stream as a string, for new EventSource(url). Listen for the ready, batch and resync events and parse the data of each with the BatchStreamEvent schema.

Error handling

ApiClientError

What a call rejects with when the API answers with an error or cannot be read.

ApiClientError

statusnumber
The HTTP status of the response.
codestring
The error's code, the same as body.error.code.
messagestring
The error's message.
bodyApiErrorBody
The whole error envelope.

A response that is not JSON, such as a proxy's error page, becomes an ApiClientError with code UPSTREAM_UNAVAILABLE for a status of 500 or more and INTERNAL_ERROR below that.

errors

The error table of the API as values.

MemberWhat it is
errors.statusAn object from each error code to its HTTP status.
errors.codesThe codes as an array.
errors.KnownErrorCodeA zod enum of the codes this version knows.
errors.ErrorCodeA zod schema that accepts the known codes and any later one.
errors.ApiErrorThe zod schema of the error envelope.

BASE_ERROR_STATUS and UNA_ERROR_STATUS are the two halves of errors.status: the codes any API of this kind raises, and the ones only Una raises. ERROR_STAGES is the array of stage names, and ErrorStage and ProgramError are the zod schemas of the envelope's stage and programError. defineErrors(extra) builds a table like errors from the base codes plus extra. The types ApiError, ApiErrorBody, ErrorCode, KnownErrorCode, BaseErrorCode, UnaErrorCode and KnownErrorStage are exported beside them.

The codes and when each is raised are in the API reference.

UNA_PROGRAM_ERRORS

The program's errors as an array of { code, name, message }, 42 of them, numbered from 6000. UnaProgramErrorName is the union of the names and UnaProgramErrorEntry the type of one entry. UNA_PROGRAM_ERROR_BY_CODE and UNA_PROGRAM_ERROR_BY_NAME are the same entries keyed by number and by name, and unaProgramError(code) returns the entry for a number, or undefined. The table is generated from the program's IDL when the package is built. The program reference lists the errors with what raises each.

Constants

ExportValueWhat it is
CONTRACT_VERSION"0.1.9"The version of the contract this package speaks.
UNA_PROGRAM_ID"BAP8m3hSZnrkpJij3Pmya12LvKNLCseq8c441qHFQB2F"The address of the una program.
UNA_IDL_ADDRESS"BAP8m3hSZnrkpJij3Pmya12LvKNLCseq8c441qHFQB2F"The program address in the IDL the error table was generated from.
UNA_FEE_RECIPIENT"8HUwDE2r2AuQLd2YEip8VMCgo9Fe1Pb161d4xfu6wmhj"The address that receives the protocol share of the clearing fee.
DEFAULT_BATCH_WINDOW_SLOTS10The default batch window. una.protocol() returns the live setting.
DEFAULT_PROOF_WINDOW_SLOTS300The default proof window. una.protocol() returns the live setting.
SLOT_MS200The length of a slot in milliseconds, for turning slots into time.
Q64_ONE18446744073709551616n1 in Q64.64, 1n << 64n. Multiply a ratio by it to get a price or a limit.
FILL_ONE9223372036854775808nA fill fraction of 1, 1n << 63n.
U64_MAX18446744073709551615nThe largest u64.
U128_MAX340282366920938463463374607431768211455nThe largest u128.
I128_MIN-170141183460469231731687303715884105728nThe smallest i128.
I128_MAX170141183460469231731687303715884105727nThe largest i128.
BATCH_STATUSES"open", "sealed", "cleared", "proven", "slashed", "rolled"The statuses of a batch.
ORDER_STATUSES"open", "filled", "partial", "rolled", "expired", "cancelled", "settled"The statuses of an order.
STAKE_STATUSES"staked", "unstaking", "withdrawable"The statuses of a stake.
CANDLE_INTERVALS"S1", "M1", "M5", "M15", "H1"The candle intervals: one second, then 1, 5 and 15 minutes, then one hour.
TX_STATUS_NAMES"submitted", "unconfirmed", "confirmed", "finalized", "failed", "expired"The statuses of a submitted transaction.
TX_STAGES"build", "wallet-rejected", "wallet-changed", "simulation", "send", "confirm"The stages a transaction can fail at.
HEALTH_STATUSES"live", "waiting"The two states of the API.
API_MODES"fixture", "chain"Where the API reads from.
CLUSTERS"localnet", "devnet", "mainnet"The Solana clusters an API can serve.

Schemas and types

Every object and every request of the API is exported twice under one name: as a zod schema, to parse or validate a value, and as the TypeScript type of what that schema returns.

TypeScript
import { Order } from '@una/sdk'

const order: Order = Order.parse(value)

Objects and requests, each documented under its name in the API reference or at the route that takes it:

AccruedCommission, AddLiquidityBuild, AddLiquidityRequest, BatchCover, BatchDetail, BatchDetailQuery, BatchFillFraction, BatchInputRecord, BatchInputResponse, BatchResultData, BatchResultFill, BatchResultPrice, BatchStateData, BatchStatePair, BatchStateResponse, BatchStateTick, BatchStateToken, BatchStreamEvent, BatchSummary, BatchTokenPrice, BatchesPage, BatchesQuery, BondMint, CancelOrderBuild, CancelOrderRequest, Candle, CandlesQuery, CandlesResponse, ClaimCommissionRequest, ClaimCoverRequest, ClaimRewardsRequest, CollectFeesRequest, CoverParticipant, HealthResponse, LiquidityPosition, LiquidityQuote, LiquidityQuoteQuery, LiveOverview, OpenBatchSummary, Order, OrdersPage, OrdersQuery, PageInfo, PageQuery, PairDetail, PairSummary, PairsResponse, PlaceOrderBuild, PlaceOrderRequest, PositionsPage, PositionsQuery, PostBatchStateRequest, ProgramError, ProtocolParams, QuoteQuery, QuoteResponse, RemoveLiquidityRequest, RequestUnstakeRequest, SettleOrderRequest, SettlePositionRequest, SolverDetail, SolverSlash, SolverSummary, SolversPage, StakeDepositRequest, StakePosition, StakesPage, StakesQuery, TickLiquidity, Token, TokenRef, TokensResponse, TxBuild, TxFailure, TxProgramFailure, TxStatus, TxSubmission, UnstakeRequest, WalletBalancesResponse, WalletTokenBalance, WithdrawStakeRequest.

Enums. A name ending in Filter or Param accepts only the known values and is what a query takes; the others also accept values added later:

ApiMode, BatchStatus, BatchStatusFilter, CandleInterval, CandleIntervalParam, Cluster, ErrorStage, HealthStatus, OrderStatus, OrderStatusFilter, StakeStatus, TxStage, TxStatusName.

The building blocks the schemas are made of, named as the API reference names them:

ExportAccepts
Addressaddress
Signaturesignature
U64u64 string
PositiveU64u64 string, above 0
U128u128 string
PositiveU128u128 string, above 0
I128i128 string
BaseUnitsinteger string
Hash32hex, 32 bytes
HexByteshex
DecimalTextdecimal string
Base64base64
Timestamptime

page(item) returns the schema of a page of item, openEnum(values) the schema of an enum that also accepts later values, and paginate(rows, query) cuts one page out of an array in the shape page describes.

Helpers

ExportWhat it does
toBase64(bytes)Encodes a Uint8Array as base64, for a signed transaction.
fromBase64(text)Decodes base64 to a Uint8Array, for transactionBase64.
toBase58(bytes)Encodes bytes as base58, for a signature or an address.
fromBase58(text)Decodes base58 to bytes. Throws on a character outside the alphabet.
shortAddress(address, n = 4)The first and last n characters of an address with an ellipsis between.
createHttp(baseUrl, options)The fetch layer the client is built on: get, post, request, url and streamUrl, each parsing the response with a schema you pass. HttpOptions, CallOptions and Http are its types.