Trade
Place and cancel orders
What place_order, cancel_order and settle_order take, check, move and return, from the first signature to the last atom paid out.
An order sells an amount of one listed token for another, at a limit or better, until an expiry batch. Three instructions carry it: place_order puts it in the open batch, cancel_order takes it back out while its batch is open, and settle_order pays it after the batch clears.
Place an order
On /trade, with a wallet connected:
Sell
Enter the amount and choose the token. Balance fills in everything the wallet holds of it. Under an amount worth less than 0.0001 SOL the form reads Too small to place.
Buy
Choose the token to receive. The field shows an estimate at the last proven price, after the clearing fee.
Limit
The least the order accepts, written as the buy token per one of the sell token. It is prefilled 20 basis points under the last proven price. Type over it to set your own, and Use the last proven price puts the suggestion back. You receive at least is the amount times the limit.
Place order
Press Place order and sign. When the notice reads Confirmed the order is under Your orders with the status In window, and Open batch leads to its batch page.
const placed = await una.swap({
sell: sol.mint,
buy: usdc.mint,
amount: amount.toString(),
limit: quote.suggestedLimitQ64,
})
console.log(`order ${placed.orderAddress} placed, transaction ${placed.signature}`)una is the bound client from Quickstart. The call resolves when the transaction has confirmed.
una.swap
selladdressrequired- The mint of the token to sell.
buyaddressrequired- The mint of the token to buy. It differs from
sell. amountu64 stringrequired- Atoms of the sell token, worth at least 0.0001 SOL at its last proven price.
limitu128 stringrequired- The limit as a Q64.64 integer. Above 0.
expiryBatchIdu64 string- The last batch the order may clear in. Left out, the API sets it about five minutes of batches after the open one: see The expiry batch.
It returns
orderAddressaddress- The order's account.
batchIdu64 string- The batch that was open when the transaction was built. The order's own batch is
batchIdon its Order, fromuna.order(placed.orderAddress): it is a later one when the built batch sealed before the transaction landed. signaturesignature- The transaction that placed it.
orderOrder | null- The Order as the API has it at that moment, or
nullif it is not indexed yet. batchBatchDetail | null- The BatchDetail of the batch in
batchId.
What place_order takes
place_order
nonceu64required- A number that sets the order's address, with the owner: the address is derived from
"order", the owner and the nonce. One owner uses a nonce once. The API picks it. amountu64required- Atoms of the sell token.
limitu128, Q64.64required- The least atoms of the buy token the order accepts per atom of the sell token, times 2^64.
expiry_batch_idu64required- The last batch the order may clear in. The open batch's own number makes an order for this batch only.
The two tokens are accounts of the instruction: any two tokens the program lists. The owner signs and pays.
The instruction also names a batch account: the batch that was open when the transaction was built. If that batch is still the open one when the transaction lands, the order goes into it. If it has sealed, or its account has been closed since, the program looks through the writable Batch accounts passed after the listed ones and places the order in the one whose number is the open batch's. The API passes the next four batch addresses there, so an order built in batch n lands in whichever of n to n + 4 is open.
What it does
- Starts the batch's window again when the order is the first into a batch whose window has already passed. The batch can then be sealed
batch_window_slotsslots after this one. - Moves
amountatoms from the owner's associated token account to the sell token's vault. Each listed token has one vault, a token account under the program's authority. - Creates the order account with the status open. Its
batch_idandorigin_batch_idare the number of the batch it went into. - Adds
amountto the batch's offered total for the sell token, and adds the two tokens to the batch's token list if they are new to it. - Folds a Place record into the batch's input hash: the order's address, the two token indexes, the amount and the limit.
It emits OrderPlaced.
What it refuses
| Error | Raised when |
|---|---|
ZeroLiquidity | amount is 0. |
InvalidConfig | limit is 0. |
OrderTooSmall | amount is worth less than 100,000 lamports, 0.0001 SOL, at the sell token's last proven price. The value is ceil(amount * last_price / 2^64). An order selling SOL needs an amount of 100,000 or more. |
SameTokenOrder | The sell token and the buy token are the same. |
BatchAlreadySealed | The batch passed has sealed, and none of the writable Batch accounts after the listed ones is the open batch. |
OrderExpired | expiry_batch_id is lower than the number of the batch the order goes into. |
CapacityExceeded | The batch already holds 16 tokens and the order would add another. |
MathOverflow | The order's value in lamports, or the batch's offered total for the sell token, would pass the u64 range. |
The token program refuses the transfer when the wallet holds less than amount, and the transaction fails as a whole.
The limit
A limit is a ratio of atoms. It ignores decimals: for a token with 6 decimals bought with SOL, a price of 160 tokens per SOL is 0.16 atoms per lamport. The SDK computes it three ways.
// From the least output: no less than 80 USDC (6 decimals) for the 0.5 SOL.
const fromMinOut = limitQ64(80_000_000n, amount)
// From a price as a person writes it: 160 USDC per SOL.
const fromPrice = parseLimitPrice('160', sol.decimals, usdc.decimals)
// From the last proven prices.
const fromQuote = quote.suggestedLimitQ64limitQ64 and parseLimitPrice round up, so the stored limit is never under what was asked. suggestedLimitQ64 is the last proven rate less 20 basis points.
The batch compares the limit with its cleared price, before the clearing fee. An order that clears exactly at its limit receives floor(amount * limit / 2^64) less the fee. How fills are decided has the comparison and Fees the fee.
The expiry batch
An order may clear in every batch from the one it is placed in to its expiry batch, both included. While a remainder is left, the open batch's number is at or under the expiry and the remainder is worth at least the smallest order, settling moves the remainder into the open batch. Once the open batch's number is past the expiry, settling returns the remainder to the owner. What it pays has the rule in full.
const live = await una.live()
const open = BigInt(live.openBatch!.batchId)
const withExpiry = await una.swap({
sell: sol.mint,
buy: usdc.mint,
amount: amount.toString(),
limit: fromMinOut,
expiryBatchId: (open + 20n).toString(), // may clear in the open batch or any of the next 20
})Left out, the expiry is about five minutes of batches after the batch open when the transaction is built:
expiryBatchId = open batch + ceil(300 000 ms / (batchWindowSlots * slotMs))
slotMs is the slot time the API measures from the cluster's recent performance samples, once a minute. una.live() reports it as slotMs, next to batchWindowSlots under protocol. At 10 slots a window and 200 ms a slot that is 150 batches.
The app places orders with the API's default expiry.
Cancel an order
One call cancels an order at any point of its life. What the transaction holds depends on the batch the order is in.
| The order's batch is | The cancel build holds | outcome |
|---|---|---|
| Open | cancel_order. The whole amount returns. | cancelled |
| Sealed | Nothing: the API answers ORDER_LOCKED until the batch clears or rolls, about a second. | |
| Cleared, proven or rolled, with a remainder that moves on | settle_order, which pays the fill and moves the remainder into the open batch, then cancel_order there, which returns the remainder. | cancelled |
| Cleared or proven, with the whole amount filled | settle_order, which pays the fill. | filled |
| Cleared or proven, with part filled and a remainder worth less than the smallest order | settle_order, which pays the fill and returns the remainder. | filled |
| Cleared, proven or rolled, in the order's expiry batch, or with nothing filled and the amount now worth less than the smallest order | settle_order, which pays any fill and returns the remainder. | expired |
| Slashed | settle_order, which returns the whole amount. | cancelled |
A sealed batch holds its orders until a solver clears it. The API also answers ORDER_LOCKED for a batch that has just cleared, until it has read what the clearing did to the order.
Under Your orders on /trade, an order with the status In window, Partly filled or Rolled to next batch has a Cancel button on its row. Press it and sign.
The button reads Preparing while the transaction is built. If the order's batch is clearing, the app asks again every half second, for up to 30 seconds, and the button stays on Preparing until the build arrives. It then reads Sign in your wallet, and Sent. Confirming. If the batch seals between the build and the landing, the app builds and sends the cancel again, up to three more times, each with a new signature.
When the notice reads Confirmed, the amount is back in the wallet and the status reads Cancelled. If the batch had already filled the whole order, the notice reads The order filled before the cancel landed. If the order was past its expiry, it reads The order had already expired. In both the status reads Settled.
try {
const cancelled = await una.cancelOrder(placed.orderAddress)
console.log(`${cancelled.build.outcome} in ${cancelled.signature}`) // cancelled, filled or expired
} catch (e) {
if (e instanceof ApiClientError) console.error(e.code, e.message)
else if (e instanceof UnaTxError) console.error(e.failure.stage, e.failure.program?.name, e.failure.message)
else throw e
}una.cancelOrder resolves when the transaction has confirmed, with build, tx and signature. build.outcome is the last column of the table above.
The call waits out a clearing batch by itself. On ORDER_LOCKED, or on OrderNotCancellable from the program when the batch sealed between the build and the landing, it waits 500 ms and builds again, for up to two minutes. After two minutes it rejects with the last error.
An Order carries cancellable, which is true while its status is open, partial or rolled. A refusal while the transaction is built arrives as an ApiClientError with the API's code in code. A failure after signing arrives as a UnaTxError whose failure is a TxFailure.
What the cancel build refuses
POST /v1/orders/:address/cancel builds the transaction. It answers with one of these codes in place of a build.
| Code | Status | Raised when |
|---|---|---|
ORDER_LOCKED | 409, retryable | The order's batch is sealed, or has cleared and the API has not yet read the order's fill. |
ORDER_NOT_CANCELLABLE | 409 | The order account is already settled or cancelled. |
UNAUTHORIZED | 401 | The wallet in the request is not the order's owner. |
NOT_FOUND | 404 | No order account is at that address. |
What cancel_order does
cancel_order takes no arguments. The owner signs. The batch account it takes is the order's own batch, derived from the order's batch_id.
- Moves the order's whole
amountfrom the sell token's vault to the owner's associated token account for that token. - Sets the order's
amountto 0 and its status to cancelled. - Takes the amount off the batch's offered total and folds a Cancel record, the order's address, into the batch's input hash. The solver and the proof then leave the order out.
It emits OrderCancelled.
What cancel_order refuses
| Error | Raised when |
|---|---|
Unauthorized | The signer is not the order's owner, or the token account passed is not the owner's associated token account for the sell token. |
OrderNotOpen | The order is already settled or cancelled. |
OrderNotCancellable | The order's batch is not open: it has sealed, cleared, rolled, or been proven or slashed. After settle_order has moved the remainder into the open batch, that batch is the order's batch and the cancel goes through. |
Settle an order
Settling pays an order for the batch it was in. It is possible from the moment the batch is cleared, before the proof lands, because the solver's bond stands behind the clearing.
settle_order takes no arguments and needs no signature from the owner: anyone may send it, and everything it pays goes to the owner's own associated token accounts. The keeper sends it for every order once its batch is proven, rolled or slashed. You can send it yourself, from the clearing on.
Under Your orders, an order whose batch has cleared and that is not settled yet has a Settle button on its row. Press it and sign.
const mine = await una.orders()
for (const o of mine.items) {
if (o.settleable) await una.settleOrder(o.address)
}settleable on an Order is true while a settle would succeed.
What it pays
What happens depends on the status of the order's batch.
| The batch is | The order receives | The remainder |
|---|---|---|
| Cleared or proven | net atoms of the buy token, from the buy token's vault | amount - filled atoms of the sell token |
| Rolled | Nothing | The whole amount |
| Slashed | Nothing | The whole amount, returned to the owner |
| Open or sealed | The call is refused |
filled and net come from the batch's price vector and its fill fractions, with the band bounds and the clearing fee rate the batch stored when it cleared, by the arithmetic on How fills are decided. net is already less the clearing fee.
A remainder above 0 goes one of two ways:
- If the batch was not slashed, the open batch's number is at or under the order's expiry, and the remainder is worth at least 100,000 lamports at the sell token's last proven price, the remainder joins the open batch. The value is
ceil(remainder * last_price / 2^64), the measureplace_orderholds a new order to. The order keeps its address, its limit and its expiry, itsamountbecomes the remainder, and a Place record for it is folded into the open batch's input. Its status stays open, and it clears again there. - Otherwise the remainder moves from the sell token's vault to the owner's associated token account, and the status becomes settled.
With no remainder the status becomes settled.
settle_order also writes the order's own batch account: it takes the order off that batch's count of orders still in it. When the count is 0 and the batch is proven or rolled, anyone can close the batch's account.
It emits OrderSettled with filled, received, fee, remainder and rolled_to_batch_id, which is 0 when the order did not move on.
What it refuses
| Error | Raised when |
|---|---|
OrderNotSettleable | The order is already settled or cancelled, or its batch is still open or sealed. |
Unauthorized | A token account passed is not the owner's associated token account for the sell token or the buy token. |
InvalidIndex | One of the order's tokens is not among the cleared batch's tokens. |
MathOverflow | The fill arithmetic, the remainder's value in lamports, or the open batch's offered total, passes its integer range. |
BatchAlreadySealed | The remainder would join the open batch, and the batch passed as open is no longer open. |
CapacityExceeded | The remainder would join the open batch, which already holds 16 tokens, and add another. |
Statuses
The order account has three statuses.
| Status | Meaning | What moves it on |
|---|---|---|
| Open | The order is in a batch, with its amount in the vault. | cancel_order while that batch is open. settle_order once that batch is cleared, proven, slashed or rolled. |
| Settled | Everything is paid out or returned. | Nothing. |
| Cancelled | The owner took it back. | Nothing. |
An order with a remainder stays open across batches: each settle moves it into the next open batch until it has no remainder, its remainder is worth less than the smallest order, it is cancelled, or it is past its expiry.
The API and the app name the same life in seven statuses, which also tell what the batch did.
| Status | In the app | Meaning | What moves it on |
|---|---|---|---|
open | In window | In a batch that is open or sealed. | The batch clears or rolls. cancel_order while the batch is open. |
filled | Filled | Its batch cleared and the whole amount traded. | settle_order pays it. A cancel build holds that settle, with the outcome filled. |
partial | Partly filled | Its batch cleared and part of the amount traded. | settle_order pays the part. The remainder joins the open batch, where the order is open again, or returns, and the order is settled. A cancel settles it and cancels the remainder in the open batch, and the order is cancelled. |
rolled | Rolled to next batch | Its batch rolled, or cleared with none of the order traded, before its expiry batch. | settle_order moves it into the open batch, where it is open again, or returns it once the open batch is past its expiry. A cancel settles it and cancels it in the open batch, and the order is cancelled. |
expired | Expired | Its expiry batch rolled, or cleared with none of the order traded. | settle_order returns the amount, and the order is settled. A cancel build holds that settle, with the outcome expired. |
settled | Settled | Paid out or returned. | Nothing. |
cancelled | Cancelled | Cancelled by its owner. | Nothing. |
When a batch rolls
A sealed batch that no solver clears within the clearing timeout is rolled: roll_batch sets its status to Rolled and it never has prices. The timeout is clearingTimeoutSlots on una.protocol() and on Parameters.
An order in a rolled batch keeps its whole amount in the vault. settle_order then treats it as an order with nothing filled: the whole amount joins the open batch as the same order. It returns to the owner instead if the open batch is past the order's expiry or the amount is now worth less than the smallest order. No fee is charged. A cancel after the roll settles the order into the open batch and cancels it there, in one transaction.
When a batch is slashed
A cleared batch whose proof never lands is slashed. An order settled before the slash keeps what it was paid. An order not yet settled gets its whole amount back from settle_order, with nothing filled and no fee, and it does not move on to another batch. Its owner also has a share of the batch's cover: see Slashing and cover.
What an order costs
| Cost | Amount | Paid by | When |
|---|---|---|---|
| The order account | The rent-exempt balance of a 103-byte account, in SOL | The owner | place_order |
| The buy token's associated token account | Its rent-exempt balance, if the wallet has none yet | The owner, in the transaction the API builds | place_order |
| The batch's account | Its rent-exempt balance, returned when the batch is closed | The sender of the seal_batch that opens it, the keeper by default | seal_batch |
| The clearing fee | A share of the order's output, in the buy token | Taken from the fill | Each batch the order fills in |
| The Solana transaction fee | The base fee and the priority fee the API sets from recent fees | Whoever sends each transaction | Place, cancel, settle |
The program charges nothing to place an order and nothing to cancel one. Fees has the clearing fee and the pair's liquidity fee in full.
An order that sells SOL sells wSOL. The transaction the API builds creates the wallet's wSOL token account if it has none and wraps the SOL the order needs beyond what that account already holds. SOL an order buys, and SOL returned by a cancel or a settle, arrives as wSOL in that account.
The transactions the API builds for cancelling and settling create the owner's associated token accounts when they are missing, paid by the sender.