Hadal
Start trading
  • OverviewStart
  • QuickstartStart
  • What is sealed and what is seenStart
  • Sealed balancesConcepts
  • Sealed ordersConcepts
  • The book and the pool's midConcepts
  • DealsConcepts
  • SoundingsConcepts
Concepts

Sealed orders

The terms of a sealed order, the queue it waits in, how it crosses, sweeps or rests, its statuses, and every field of its receipt.

A sealed order is one encrypted intent to buy or sell a market's base token. It is placed in the market's queue, processed in one computation against the whole book and the pool, and answered with a receipt only its owner reads. There are two kinds: a swap crosses the book and then sweeps the pool, and a dark order crosses the book and then rests in it.

  1. 01Seal
  2. 02Queue
  3. 03Cross
  4. 04Sweep
  5. 05Rest
  6. 06Receipt
  7. 07Sounding
The sealed order's path. A swap ends at the sweep, a dark order at the rest.

Terms

TermVisibilityMeaning
sidesealedBuy or sell the base token.
sizesealedHow much base to trade, in base atoms.
limitsealedThe worst price the order accepts: the highest for a buy, the lowest for a sell.
ownersealedThe address the terms were sealed for. The computation compares it with the wallet that placed the order.
kindpublicSwap or dark order.
expirypublicIn Unix seconds, UTC. Required on a dark order. See Expiry.

Side, size and limit are encrypted in the wallet with the reading key before the transaction is built, together with the wallet's own address, and are stored on the order as ciphertext. The order's account also shows its owner, its market, its sequence number in the queue, the time it was placed and its status. Amounts and prices are in atoms: see Units.

Because the sealed terms carry the address they were sealed for, ciphertext copied from someone else's order and placed under another wallet is void: it trades nothing and tells the copier nothing.

Placing an order

Placing an order is one transaction that creates the order's account and gives it the next sequence number of the market's queue. It queues no computation and moves nothing in the balance. The program refuses it with:

  • MarketNotReady when the market's pool is not open yet.
  • EmptyBalance when your balance in the market has never had a deposit land.
  • InvalidExpiry when a dark order's expiry is not in the future or is more than one day ahead, or when a swap's expiry is neither 0 nor in the future.
  • InvalidKind when the kind is neither swap nor dark.

The order's address is derived from the sequence number it will take. When another order takes that number first, the transaction is refused and nothing is placed: build it again and send it.

ts
import { priceOf } from '@hadal/sdk'

const placed = await hadal.swap({
  market,
  side: 'buy',
  size: baseAtoms,
  limit: priceOf(quoteAtoms, baseAtoms),
  key,
})
// sign and send placed.instructions with the wallet
const order = placed.account!

darkOrder takes the same parameters and an optional expiry. Left out, the expiry is set one minute short of a day from now, the longest a dark order may rest. swap places its order with no expiry.

The queue

Each market has one queue. Orders are processed strictly in arrival order, by sequence number, and each computation processes exactly one order against the whole book. An order is pending from the moment it is placed until it is processed or closed.

Nothing about your balance is checked or reserved while the order waits. The balance is read when the order is processed.

When an order reaches the head of the queue, the program first decides whether it is computed at all. It is closed there and then, with no computation, when its owner cancelled it, its expiry has passed, its owner's balance has another computation in flight, or it is a dark order and the book has no free slot. Each case is in Orders closed without a computation. Otherwise its computation is queued.

How an order is processed

One computation takes the order's sealed terms, your sealed balance and the market's sealed book, and writes the book and the balance back. Below, floor and ceil round a division down and up, mid is the pool's mid, and the fee terms are defined in Fees. Every product is taken in 128 bits before it is divided.

  1. Validity check

    The order must be its owner's, and the balance must cover its worst case before anything moves.

    text
    sealed owner = the wallet that placed the order
    size > 0  and  limit > 0
    mid fits 64 bits
    
    sell:  base  >= size
    buy:   quote >= cover  and  cover fits 64 bits
    
    notional   = ceil(size * limit / 2^32)
    cover      = notional + ceil(notional * worst_rate / 2^32)
    worst_rate = rate(max(cross_bps, sweep_bps))

    An order that fails any of these is void: it trades nothing, locks nothing, takes no slot, and its receipt has ok false with every amount zero.

  2. Cross

    If the mid is inside the order's limit (mid <= limit for a buy, mid >= limit for a sell), the order meets the book. The computation walks the book's slots in order and fills against every resting order on the opposite side whose own limit also admits the mid.

    text
    fill = min(remaining of the order, remaining of the resting order)
    q    = floor(fill * mid / 2^32)

    fill base changes hands for q quote, and each side pays the cross fee on q. The cross does not touch the pool's reserves. The book and the pool's mid tells both sides of it.

  3. Sweep (a swap)

    What is left after the cross, rem, trades against the pool's curve. It trades in full or not at all, decided by the average price of the whole remainder, fee included.

    A buy:

    text
    net_in   = ceil(pool_quote * rem / (pool_base - rem))
    gross_in = ceil(net_in * gross_rate / 2^32)
    
    sweeps if  rem < pool_base
          and  net_in and gross_in fit 64 bits
          and  gross_in <= floor(rem * limit / 2^32)

    The order pays gross_in quote and receives rem base.

    A sell:

    text
    net       = rem - sweep_fee
    quote_out = floor(pool_quote * net / (pool_base + net))
    
    sweeps if  quote_out >= floor(rem * limit / 2^32)

    The order pays rem base and receives quote_out quote.

    When the condition does not hold, none of the remainder trades. It stays in your balance and the swap is closed with what it crossed.

  4. Rest (a dark order)

    A dark order never touches the curve. If something is left after the cross, it is written into a free slot of the book with the order's side and limit, and the amount it can still trade is locked out of the balance. If nothing is left, the order takes no slot.

    The computation reveals one bit for a dark order: whether it now rests. The chain shows that, and not how much rests.

  5. Settle and receipt

    The balance is updated once, with everything the order did.

    text
    buy:   base  += filled
           quote -= cross_quote + cross_fees + gross_in + lock
    
    sell:  base  -= filled + lock
           quote += cross_quote - cross_fees + quote_out

    filled is the base crossed plus the base swept, cross_quote and cross_fees are the sums over the crosses, and lock is what a dark order's remainder locks. The receipt is written into the balance and a copy of the balance, receipt included, is stored on the order.

A swap whose limit the mid does not admit crosses nothing and sweeps nothing: it closes with ok true and filled zero, and the balance is unchanged.

What a dark order locks

When a dark order rests, the amount it can still trade leaves the balance and is held in its slot.

text
ask:  lock = resting
bid:  lock = notional + ceil(notional * rate(cross_bps) / 2^32)
      notional = ceil(resting * limit / 2^32)

An ask locks the base it still has to deliver. A bid locks the quote it would pay for its whole remainder at its limit, with the cross fee on top. Each cross pays from the lock: an ask releases fill base, a bid pays q plus the cross fee. A bid crosses at the mid, which is at or below its limit, so part of its lock is left over after it fills. That part returns to the balance on Cancel.

A resting order keeps its slot, its lock and its proceeds until it is cancelled, also after later crosses have filled it completely. The number of slots is in Limits.

Statuses

StatusMeaning
pendingPlaced and waiting in the market's queue, or being computed.
restingA dark order that was processed with something left, and holds a slot of the book.
closedFinished. The receipt, when there is one, says what happened.
FromToWhat moves it
pendingclosedA swap's computation lands.
pendingrestingA dark order's computation lands and something of it rests.
pendingclosedA dark order's computation lands and nothing rests: it crossed in full, or was void.
pendingclosedThe owner cancels before the order is processed.
pendingclosedThe order reaches the head of the queue and is closed without a computation.
restingrestingCollect lands.
restingclosedCancel lands.

If the computation of a pending order expires, the order stays pending at the head of the queue and is processed again once the market and the balance are released. See Arcium.

Collect and cancel

Both act on a resting order and each queues one computation on the book and on the owner's balance.

  • Collect moves the order's proceeds to the balance: base for a bid, quote for an ask. The order keeps resting with its remaining size and its lock. Only the owner can collect.
  • Cancel moves the proceeds and everything still locked to the balance, empties the slot and closes the order.

The receipt of either holds what was credited: filled is the base and quote the quote. The program refuses either with NotResting when the order is not resting, with NotOwner when the signer may not act on it, and with Busy while another computation is in flight on the book or the balance.

ts
const collect = await hadal.collect(order)
const cancel = await hadal.cancel(order)

collect throws before building anything when the order is not resting, and cancel when the order is closed. cancel on a pending order returns an action with no computation: see below.

Expiry

Every dark order has an expiry, at most one day after it is placed. The expiry does two things.

  • While the order is pending. An order that reaches the head of the queue after its expiry is closed without a computation. It trades nothing.
  • While the order is resting. Until the expiry only the owner can cancel it. Once the time has passed, anyone can send Cancel for it, which frees its slot. The proceeds and the lock go to the owner's balance whoever sends it. The order rests and crosses until that cancel lands.

A swap placed with the SDK has no expiry. The program also accepts a swap with one, and treats it the same way while the swap is pending.

Orders closed without a computation

In these cases an order is closed with no computation, no fill and no change to the balance. Each emits the public event OrderReturned with its reason, and the order has no receipt.

CaseWhenWhat to do
CancelledThe owner sends Cancel while the order is pending.Nothing. The order closes in that transaction and is skipped when its turn comes.
ExpiredThe order reaches the head of the queue after its expiry.Place it again with a later expiry.
Balance busyThe order reaches the head of the queue while another computation is in flight on its owner's balance.Wait for that computation to land, then place the order again.
Book fullA dark order reaches the head of the queue while every slot of the book is taken.Place it again when a slot is free.

Only the owner can cancel a pending order, expiry or not. The cancel is refused with Busy while the market has a computation in flight, because that computation may be the order's own: send it again once the computation has landed, when the order is either still pending and closes, or has been processed.

The receipt

The receipt is the result of the last action on a balance, sealed to its owner. An order keeps the receipt of its own last computation: processing, then each collect, then the cancel.

For an order that was processed:

FieldUnitMeaning
okbooleanFalse when the order was void: the balance did not cover its worst case, the terms were sealed for another address, or an amount did not fit 64 bits. True otherwise, whether or not anything filled.
filledbase atomsBase bought or sold: crossed plus swept.
quotequote atomsQuote traded for it: the quote of the crosses before their fee, plus gross_in for a buy sweep or quote_out for a sell sweep.
crossedbase atomsThe part of filled that crossed the book.
sweptbase atomsThe part of filled that swept the pool.
restedbase atomsWhat a dark order left resting in the book.
feequote atomsThe cross fees plus the sweep fee. The sweep fee of a sell is taken in base and is given here in quote at the mid.

The average price of the fill is quote / filled. A buy's balance pays quote plus its cross fees, and the sweep fee is already inside quote. A sell's balance receives quote less its cross fees, and its sweep fee was taken from the base before it reached the curve.

The other actions use the same seven fields:

ActionokOther fields
Deposittruefilled is the base credited, quote the quote credited.
Withdrawpaid or refusedAll zero.
Collect, Canceltruefilled is the base credited, quote the quote credited.
Add liquidity, Remove liquidityfalse when voidfilled is the base moved, quote the quote moved, swept the shares.

A deal's receipts are in Deals.

ts
const { status, receipt } = await hadal.order(order, key)
if (receipt) {
  const { ok, filled, quote, crossed, swept, rested, fee } = receipt.receipt
}

receipt is null until the order's first computation has landed. It is the owner's whole balance as that computation left it: receipt.base, receipt.quote, receipt.shares, and the receipt itself in receipt.receipt. Read with a key that is not the owner's, the values decode to noise, not to an error. Reading receipts through the API is told in the receipts guide.

Next