Build
SDK quickstart
Install @una/sdk, place an order with one call, and read the order and its batch.
@una/sdk is the Una API as typed calls. This page places an order from a script and follows it to its batch. It takes a Solana keypair that holds some SOL.
Install
npm install @una/sdk @solana/web3.jsThe SDK is an ES module for Node 22 and for browsers, with zod as its one dependency. @solana/web3.js is here only to load the keypair.
Bind a wallet
import { Keypair } from '@solana/web3.js'
import { createUna } from '@una/sdk'
const una = createUna({ apiUrl: 'https://api.una.markets', wallet: Keypair.fromSecretKey(secretKey) })createUna takes the API's address, https://api.una.markets, and a wallet. The wallet can be a Keypair, a connected Wallet Standard wallet in a browser, or any object with an address and a signTransaction function. The wallet lists the three shapes. The key stays in your process: the API builds each transaction unsigned and the SDK signs it locally.
Place an order
const placed = await una.swap({ sell, buy, amount, limit })una.swap
selladdressrequired- The mint of the token to sell.
buyaddressrequired- The mint of the token to buy.
amountu64 stringrequired- How much to sell, in atoms of the sell token.
limitu128 stringrequired- The least the order accepts, in atoms of the buy token per atom of the sell token, as a Q64.64 integer.
The one call builds the place_order transaction, signs it with the bound wallet, submits it, and follows it until it is confirmed. It resolves with the order's address, the transaction's signature, and the order as it stood when the transaction settled. The order joins the batch open when the transaction lands, which order.batchId gives.
The limit
A limit is a ratio of atoms multiplied by 2^64. limitQ64 computes it from the least output you accept:
import { limitQ64 } from '@una/sdk'
const limit = limitQ64(minOut, amount) // accept no less than minOut atoms for amount atomsparseLimitPrice('162.4', sellDecimals, buyDecimals) does the same from a price typed in whole tokens, and una.quote returns a ready limit as suggestedLimitQ64, set a little under the last proven rate.
The whole script
import { readFileSync } from 'node:fs'
import { Keypair } from '@solana/web3.js'
import { createUna, limitQ64, ApiClientError, UnaTxError } from '@una/sdk'
// A wallet: a Solana keypair file. The SDK signs with it; the key never leaves this process.
const wallet = Keypair.fromSecretKey(new Uint8Array(JSON.parse(readFileSync(process.env.KEYPAIR!, 'utf8'))))
const una = createUna({ apiUrl: process.env.UNA_API_URL ?? 'https://api.una.markets', wallet })
// 1. Pick the two tokens.
const { items: tokens } = await una.tokens()
const sol = tokens.find((t) => t.symbol === 'SOL')!
const usdc = tokens.find((t) => t.symbol === 'USDC')!
// 2. Sell 0.5 SOL. Ask what it would receive at the last proven prices.
const amount = 500_000_000n // lamports
const quote = await una.quote({ sellMint: sol.mint, buyMint: usdc.mint, amount: amount.toString() })
console.log(`last proven rate ${quote.lastPriceUi} ${usdc.symbol} per ${sol.symbol}, about ${quote.estimatedNetOut} atoms out`)
// 3. Set the limit: accept no less than 30 USDC for the 0.5 SOL.
const limit = limitQ64(30_000_000n, amount) // atoms of USDC (6 decimals) per `amount`, as Q64.64
try {
// 4. Place the order. One call builds, signs, submits and follows the transaction.
const placed = await una.swap({ sell: sol.mint, buy: usdc.mint, amount: amount.toString(), limit })
// The order joins the batch open when the transaction lands: the one it was built for, or the next.
const batchId = placed.order?.batchId ?? placed.batchId
console.log(`order ${placed.orderAddress} placed in batch ${batchId}`)
// 5. Wait for the batch to clear, then read the order and its batch.
let batch = await una.batch(batchId)
while (batch.status === 'open' || batch.status === 'sealed') {
await new Promise((r) => setTimeout(r, 400))
batch = await una.batch(batchId)
}
const order = await una.order(placed.orderAddress)
console.log(`order is ${order.status}: sold ${order.filledAmount}, received ${order.receivedAmount}, fee ${order.feeAmount}`)
console.log(`batch ${batch.batchId} is ${batch.status}, bond locked ${batch.bondLockedLamports} lamports, proof ${batch.proofSignature ?? 'pending'}`)
} catch (e) {
if (e instanceof UnaTxError) console.error(`transaction failed at ${e.failure.stage}: ${e.message}`, e.failure.program?.name ?? '')
else if (e instanceof ApiClientError) console.error(e.code, e.message)
else throw e
}Run it with the path of a keypair file:
KEYPAIR=~/.config/solana/id.json node --experimental-strip-types order.tsWhat each step did
Tokens
una.tokens()lists every token with its mint, decimals and last proven price. Orders go between any two of them.Quote
una.quotemultiplies the amount by the last proven rate and takes the clearing fee off. It is an estimate. The batch decides the fill.Place
una.swapsends the order. The sell amount moves from the wallet to the token's vault, and the order joins the open batch.placed.signatureis the transaction, andplaced.orderandplaced.batchare the order and the batch as they stood at that moment.The batch
The order sits in the open batch until the window ends, 10 slots.
una.batchthen shows the batchcleared, with its prices and the bond locked behind it, and after thatproven, withproofSignatureset. On the bound client,una.batchalso carries the wallet's own orders in the batch aswalletOrders.The fill
una.ordershows what the order sold and received. The bought tokens reach the wallet when the order is settled. The keeper settles orders once their batch is proven, anduna.settleOrder(orderAddress)does the same if you would rather send it yourself.
Reading without a wallet
createUnaClient returns a client with no wallet. Every read works on it with no key at all.
import { createUnaClient } from '@una/sdk'
const client = createUnaClient('https://api.una.markets')
const live = await client.live() // the open batch, the last cleared batch, the settings
const { items: batches } = await client.batches({ status: 'proven', limit: 10 })
const { items: theirs } = await client.orders({ wallet: 'AWalletAddress...' })
const candles = await client.candles('sol-usdc', { interval: 'M5' })To follow batches as they change, open the stream:
import { BatchStreamEvent } from '@una/sdk'
const source = new EventSource(client.batchesStreamUrl())
source.addEventListener('batch', (message) => {
const event = BatchStreamEvent.parse(JSON.parse(message.data))
console.log(event.data) // a BatchSummary
})The stream names each event by its type, ready, batch or resync, so listen for the type with addEventListener.
When a call fails
A write call on the bound client rejects with one of two errors. ApiClientError means the API refused to build the transaction; its code is one of the codes in the API reference. UnaTxError means the transaction was built and did not go through; its failure.stage says where, and failure.program.name is the program's own error name when the program refused it.
try {
const cancelled = await una.cancelOrder(orderAddress)
console.log(cancelled.build.outcome) // 'cancelled', 'filled' or 'expired'
} catch (e) {
if (e instanceof ApiClientError && e.code === 'ORDER_NOT_CANCELLABLE') {
// the order is already settled or cancelled
} else if (e instanceof UnaTxError && e.failure.stage === 'wallet-rejected') {
// the wallet did not sign
} else throw e
}While the order's batch is sealed and clearing, the API answers ORDER_LOCKED. una.cancelOrder waits and builds again by itself, for up to two minutes, so that code reaches the catch only after that. Cancel an order has what the transaction holds for each outcome.