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
Reference

Circuits

What each of Hadal's eleven circuits computes, its inputs and outputs, what it reveals and the rules it keeps.

A circuit is the computation the cluster runs on sealed values. Each instruction of the program that changes sealed state queues one circuit, and the circuit's output is written by its callback. Nothing leaves a circuit in the clear except what the Reveals column lists: a withdrawal's yes or no, whether a dark order rests, whether a deal's escrow was covered, whether an answer traded and filled the deal, and a sounding's figures.

CircuitRevealsComputes
init_marketnothingOpens a market's pool with the creator's public first amounts and credits the creator's sealed balance with shares.
depositnothingAdds a public deposit to a sealed balance.
withdrawwhether the sealed balance covered the amountTakes a public withdrawal out of a sealed balance if the balance covers it.
process_orderwhether a dark order rests in the bookRuns one sealed order against the whole book: crosses opposite resting orders at the pool's mid, then sweeps the pool's curve (a swap) or rests the remainder in a book slot (a dark order), and writes the receipt.
settle_slotnothingMoves a resting order's proceeds to its owner's sealed balance. On a cancel it also returns what the order still has locked and empties the slot.
add_liquiditynothingMoves sealed amounts of both tokens from a sealed balance to the pool, in the pool's ratio, and credits shares.
remove_liquiditynothingTurns sealed shares back into both tokens in the sealed balance.
open_dealwhether the maker's sealed balance covered the escrowMoves a deal's escrow from the maker's sealed balance into the deal.
take_dealwhether the answer traded, and whether the deal has nothing leftCompares an answer with a deal's sealed terms and, if the limits cross and the size meets the minimum, trades at the midpoint of the two limits.
settle_dealnothingReturns a deal's remaining escrow and its proceeds to the maker's sealed balance, and adds the deal's fees and volume to the market's pool for the next sounding.
soundthe pool's price, the interval's crossed volume and swept volume, and the protocol fees accrued in base and in quoteTakes a sounding: reveals the pool's figures for the interval and starts the next interval.

Who can open each value, and why the cluster can compute on it without any node seeing it, is told in Arcium.

Arithmetic

Every stored quantity is a u64. Products are taken in 128 bits, and an action whose amounts would not fit a u64 is void: it never wraps. Amounts are atoms and a price is a 2^32 fixed-point number: see Units. The formulas below use these helpers, with floor and ceil naming the rounding of the division.

text
ONE              = 2^32
apply(a, r)      = floor(a * r / ONE)        a price or a rate applied to an amount
apply_up(a, r)   = ceil(a * r / ONE)
rate(bps)        = floor(bps * ONE / 10000)  a fee in basis points as a 2^32 rate
mid(base, quote) = floor(quote * ONE / base) the pool's mid from its reserves
bid_lock(size, limit, fee_rate)
                 = n + apply_up(n, fee_rate)   where n = apply_up(size, limit)

bid_lock is the quote a buyer must put up for size base at limit, fee included. It rounds up, so a lock always covers the trade it stands for.

Rounding direction: a lock, the quote a buying sweep pays and the tokens taken for new shares round up. The quote a selling sweep receives, the shares minted and the tokens shares give back round down. The quote amount of a cross or a deal, and every fee computed with apply, round down, and both sides of the trade use the same rounded amount.

Sealed structs

Ledger

A wallet's sealed balance in one market, sealed to the owner's reading key. It is the output of every circuit but sound.

NameTypeMeaning
baseu64Base atoms the wallet holds below.
quoteu64Quote atoms the wallet holds below.
sharesu64The wallet's shares of the pool.
receiptReceiptThe result of the last action on this balance.

What an order has locked while it rests, and what a deal holds in escrow, is not in the ledger: it is in the book slot or in the deal until it is collected, cancelled or settled.

Receipt

Each circuit overwrites the receipt, so a ledger carries the receipt of the last action only. The program keeps a copy of the ledger on the order (Order.receipt) and in the callback's event, which is how an older receipt is read.

NameTypeMeaning
oku641 when the action took effect. 0 when it was void: the sealed balance did not cover it, its terms were not valid, it was sealed for another address, an amount would not fit a u64, or a deal answer did not trade.
filledu64For an order or an answer: base atoms traded. Otherwise: base atoms credited or moved.
quoteu64For an order or an answer: quote atoms paid or received for what traded. Otherwise: quote atoms credited or moved.
crossedu64Base atoms that traded by crossing.
sweptu64For an order: base atoms that traded against the pool. For a liquidity change or a pool opening: the shares minted or given back.
restedu64Base atoms left resting in the book.
feeu64The fee the action paid, in quote atoms.

An order's average price is quote / filled. Each circuit's section says what it writes here.

Book

A market's sealed state, sealed to the cluster alone: one Pool and six Slots.

Pool fieldTypeMeaning
baseu64The pool's base reserve.
quoteu64The pool's quote reserve.
sharesu64All shares of the pool.
fee_baseu64Protocol fees accrued in base atoms since the last sounding.
fee_quoteu64Protocol fees accrued in quote atoms since the last sounding.
crossedu64Crossed volume since the last sounding, in quote atoms. Deals settled in the interval are counted here.
sweptu64Swept volume since the last sounding, in quote atoms.
Slot fieldTypeMeaning
sideu80 empty, 1 bid, 2 ask.
limitu64The resting order's limit.
remainingu64Base atoms still to trade.
lockedu64What the owner put up and has not yet paid: quote atoms for a bid, base atoms for an ask.
proceedsu64What the order has received and its owner has not yet collected: base atoms for a bid, quote atoms for an ask.

Deal

A deal's escrow, sealed to the cluster alone.

NameTypeMeaning
sideu8The maker's side: 1 bid, 2 ask.
limitu64The maker's limit.
min_sizeu64The smallest answer the maker accepts, in base atoms.
remainingu64Base atoms still to trade.
lockedu64The escrow not yet paid out: quote atoms for a bid, base atoms for an ask.
proceedsu64What the maker has received: base atoms for a bid, quote atoms for an ask.
feeu64Deal fees of both sides so far, in quote atoms.
volumeu64Quote atoms traded so far.

Inputs a wallet seals

InputFieldsSent with
OrderTermsbuy (bool), size, limit, ownerplace_order
Amountsbase, quote, owneradd_liquidity
Sharesshares, ownerremove_liquidity
DealTermssize, min_size, limit, owneropen_deal
Answersize, limit, ownertake_deal

Sizes, limits, amounts and shares are u64. owner is the address of the wallet the input was sealed for, as two u128 values: lo is bytes 0 to 15 of the address and hi bytes 16 to 31, each little-endian. The program passes the address of the wallet the instruction acts for in plaintext, and the circuit compares the two. An input sealed for another address is void, so a ciphertext copied from someone else's order, deal or answer does nothing and returns nothing about its contents.

Ciphertexts and packing

A ciphertext is 32 bytes: one element of the field the Rescue cipher works in. A value a wallet seals as an input is one ciphertext per field, in the order above, with owner as two: an order's terms are 5 ciphertexts, a deal's terms 5, an answer 4, liquidity amounts 4 and shares 3. A boolean is sealed as 1 or 0.

The structs the circuits write are packed, several fields to one element, before they are encrypted:

StructCiphertextsStored in
Ledger4Balance.ledger, Order.receipt, and the SealedLedger of an event
Book11Market.book
Deal3Deal.state

A ledger's ten u64 values are packed three to an element, lowest bits first, in field order: base, quote, shares, then the receipt's ok, filled, quote, crossed, swept, rested, fee. After decrypting the four elements with the reading key and the stored nonce, value j of an element is (element >> (64 * j)) & (2^64 - 1) for j in 0, 1, 2. The SDK's unpackU64 does this, and Sealer.ledger returns the ledger as an object: see the SDK reference.

Each output is encrypted under a new nonce, which the callback stores beside the ciphertext (Balance.nonce, Market.book_nonce, Deal.state_nonce, Order.receipt_nonce).

init_market

Queued by open_pool.

InputSealed toMeaning
ledgerthe creator's reading keyThe creator's ledger.
freshplaintextWhether the balance has never been written. A fresh ledger starts from zero.
baseplaintextThe first liquidity in base atoms.
quoteplaintextThe first liquidity in quote atoms.

Outputs: the book, to the cluster, with the pool holding base and quote and all six slots empty; the creator's ledger, to the creator's reading key. Reveals nothing.

The pool's first shares are 2 * quote, all credited to the creator. Receipt: ok 1, swept the shares.

deposit

InputSealed toMeaning
ledgerthe owner's reading keyThe owner's ledger.
freshplaintextWhether the balance has never been written.
baseplaintextBase atoms deposited, or 0.
quoteplaintextQuote atoms deposited, or 0.

Output: the ledger with the amounts added. Reveals nothing; the amounts were already public in the instruction. Receipt: ok 1, filled the base added, quote the quote added.

withdraw

InputSealed toMeaning
ledgerthe owner's reading keyThe owner's ledger.
baseplaintextBase atoms asked for, or 0.
quoteplaintextQuote atoms asked for, or 0.

Outputs: the ledger, and one revealed boolean. The boolean is true when ledger.base is at least base and ledger.quote at least quote; the amounts are then subtracted. When it is false the balances are unchanged. Receipt: ok equal to the boolean, every other field 0.

The boolean is the only thing revealed: that this balance held at least the amount asked for, or did not.

process_order

InputSealed toMeaning
orderthe owner's reading keyOrderTerms: buy, size, limit, owner.
ledgerthe owner's reading keyThe owner's ledger.
bookthe clusterThe market's book.
owner_lo, owner_hiplaintextThe address of the order's owner.
sweepplaintextTrue for a swap.
restplaintextTrue for a dark order.
slotplaintextThe book slot a dark order takes.
cross_bpsplaintextThe cross fee per side.
sweep_bpsplaintextThe sweep fee.
share_bpsplaintextThe protocol's share of the sweep fee.

Outputs: the book, to the cluster; the owner's ledger with the order's receipt, to the owner's reading key; one revealed boolean, whether a dark order now rests in its slot. For a swap it is always false. The plaintext inputs are the owner's address, the order's public kind, the slot the program chose, and the venue's rates.

One order runs against the whole book in four steps. m is the pool's mid from its reserves before the order.

Coverage

The sealed balance must cover the order's worst case before anything moves.

text
buy:   ledger.quote >= bid_lock(size, limit, rate(max(cross_bps, sweep_bps)))
sell:  ledger.base  >= size

The order is valid when its terms were sealed for the owner's address, it is covered, size and limit are greater than 0, the pool has base, and the lock and the mid each fit a u64. An order that is not valid is void: nothing trades, nothing is locked, the balances are unchanged and the receipt has ok 0. A void dark order rests nothing, so it takes no slot and its Order is closed.

Cross

The order crosses only if its own limit admits the mid: m at most limit for a buy, at least limit for a sell. It then visits the six slots in order. A resting order takes part when it is on the opposite side and its limit admits the mid too: an ask with limit at most m, a bid with limit at least m. For each such slot:

text
fill = min(remainder of the order, slot.remaining)
q    = apply(fill, m)                 quote for the fill, at the mid
fee  = apply(q, rate(cross_bps))      paid by each side

The incoming order trades fill base for q quote and pays fee on top (a buy pays q + fee, a sell receives q - fee). A resting ask gives fill from its locked and adds q - fee to its proceeds. A resting bid gives q + fee from its locked and adds fill to its proceeds. Every fill is at the mid: a cross has no price impact, and no resting order gets a better or worse price than another.

Both fees of every cross, 2 * fee, are added to the pool's fee_quote. q is added to the interval's crossed volume.

Sweep

A swap sends what is left after the cross, rem, to the pool's constant-product curve. It trades all of rem or none of it. B and Q are the reserves before the order.

A buy:

text
net_in   = ceil(Q * rem / (B - rem))                    quote the curve asks for rem base
gross_in = apply_up(net_in, ceil(10000 * ONE / (10000 - sweep_bps)))
fee      = gross_in - net_in
protocol = apply(fee, rate(share_bps))

sweeps when  rem < B  and  gross_in <= apply(rem, limit)  and  net_in, gross_in fit a u64

The buyer pays gross_in and receives rem. The pool's base falls by rem and its quote rises by gross_in - protocol, so the fee less the protocol's share stays in the pool for its liquidity providers. protocol is added to fee_quote, and gross_in to the interval's swept volume.

A sell:

text
fee       = apply(rem, rate(sweep_bps))                 in base atoms
net       = rem - fee
quote_out = floor(Q * net / (B + net))
protocol  = apply(fee, rate(share_bps))                 in base atoms

sweeps when  quote_out >= apply(rem, limit)

The seller gives rem and receives quote_out. The pool's base rises by rem - protocol and its quote falls by quote_out. protocol is added to fee_base, and quote_out to the interval's swept volume. The receipt counts this fee in quote, as apply(fee, m).

The condition compares the average price of the whole sweep, fee included, with the limit. When it does not hold, the remainder does not trade and stays in the sealed balance: the receipt shows what crossed and nothing swept.

Rest

What is left of a valid dark order after the cross, resting, waits in its slot with its lock:

text
bid:  locked = bid_lock(resting, limit, rate(cross_bps))   quote atoms
ask:  locked = resting                                     base atoms

The lock leaves the sealed balance now and returns through settle_slot. A dark order never sweeps, and a swap never rests.

The revealed boolean is resting > 0. When it is true the program marks the order resting and records it in the slot. When it is false, because the whole order crossed or the order was void, the slot stays empty and the order is closed. The chain therefore sees whether a dark order rests, and not how much of it.

Ledger and receipt

text
filled = crossed + swept
buy:   base  += filled
       quote -= cross quote + cross fees + sweep quote + locked
sell:  base  -= filled + locked
       quote += cross quote - cross fees + sweep quote

Receipt: ok 1 for a valid order, filled, quote the cross quote plus the sweep quote (gross_in for a buy, quote_out for a sell), crossed and swept in base atoms, rested the base left in the slot, fee the cross fees plus the sweep fee in quote.

settle_slot

Queued by collect (close false) and by cancel_order on a resting order (close true).

InputSealed toMeaning
ledgerthe owner's reading keyThe owner's ledger.
bookthe clusterThe market's book.
slotplaintextThe order's book slot.
closeplaintextTrue for a cancel.

Outputs: the book and the ledger. Reveals nothing.

The slot's proceeds move to the ledger (base for a bid, quote for an ask) and are set to 0. With close, the slot's locked returns too (quote for a bid, base for an ask) and the slot becomes empty. Without it the order keeps resting with its remaining size and lock. Receipt: ok 1, filled the base credited, quote the quote credited.

add_liquidity

InputSealed toMeaning
amountsthe owner's reading keyAmounts: the most base and the most quote to add, owner.
ledgerthe owner's reading keyThe owner's ledger.
bookthe clusterThe market's book.
owner_lo, owner_hiplaintextThe address of the balance's owner.

Outputs: the book and the ledger. Reveals nothing.

text
shares     = min(floor(amounts.base * total / B), floor(amounts.quote * total / Q))
used_base  = ceil(shares * B / total)
used_quote = ceil(shares * Q / total)

total is the pool's shares, B and Q its reserves. The shares are the most the two amounts buy in the pool's ratio, so one of the amounts is used in full and the other in part. The change takes effect when the amounts were sealed for the owner's address, shares is greater than 0 and fits a u64, and the ledger holds used_base and used_quote. Receipt: ok 1, filled the base used, quote the quote used, swept the shares credited. Otherwise nothing moves and ok is 0.

remove_liquidity

InputSealed toMeaning
sharesthe owner's reading keyShares: the shares to give back, owner.
ledgerthe owner's reading keyThe owner's ledger.
bookthe clusterThe market's book.
owner_lo, owner_hiplaintextThe address of the balance's owner.

Outputs: the book and the ledger. Reveals nothing.

text
out_base  = floor(shares * B / total)
out_quote = floor(shares * Q / total)

The reserves hold the sweep fees the pool has kept, so the amounts include the fees the shares earned. The change takes effect when the shares were sealed for the owner's address, and shares is greater than 0, at most the ledger's shares, and less than total. Receipt: ok 1, filled the base credited, quote the quote credited, swept the shares given back. Otherwise nothing moves and ok is 0.

open_deal

InputSealed toMeaning
termsthe maker's reading keyDealTerms: size, min_size, limit, owner.
ledgerthe maker's reading keyThe maker's ledger.
buyplaintextThe maker's side, public on the deal.
deal_bpsplaintextThe deal fee per side.
owner_lo, owner_hiplaintextThe maker's address.

Outputs: the deal's escrow, to the cluster; the maker's ledger; one revealed boolean.

text
buy:   lock = bid_lock(size, limit, rate(deal_bps))   quote atoms
sell:  lock = size                                    base atoms

The boolean is true when the terms were sealed for the maker's address, lock fits a u64 and the ledger covers it, size and limit are greater than 0 and min_size is at most size. The lock then leaves the ledger and becomes the escrow's locked, with remaining set to size. When it is false nothing moves and the program marks the deal void. Receipt: ok equal to the boolean, every other field 0.

The boolean is the only thing revealed: that the deal is funded, or is not.

take_deal

InputSealed toMeaning
answerthe taker's reading keyAnswer: size, limit, owner.
ledgerthe taker's reading keyThe taker's ledger.
dealthe clusterThe deal's escrow.
deal_bpsplaintextThe deal fee per side.
owner_lo, owner_hiplaintextThe taker's address.

Outputs: the escrow, to the cluster; the taker's ledger; two revealed booleans, done and filled.

The taker trades the side opposite to the maker.

text
crosses = answer.limit >= deal.limit    when the maker sells
          answer.limit <= deal.limit    when the maker buys
fill    = min(answer.size, deal.remaining)
minimum = min(deal.min_size, deal.remaining)
price   = floor((deal.limit + answer.limit) / 2)
q       = apply(fill, price)
fee     = apply(q, rate(deal_bps))      paid by each side

done = crosses and fill > 0 and fill >= minimum and the taker's ledger covers it
       (q + fee quote when the taker buys, fill base when the taker sells)
       and the answer was sealed for the taker's address and q fits a u64

The price is the midpoint of the two limits. The minimum is the maker's min_size, or all that is left when less than that remains. When done, a taker who buys receives fill and pays q + fee, and the escrow gives fill from locked and adds q - fee to proceeds. A taker who sells gives fill and receives q - fee, and the escrow gives q + fee from locked and adds fill to proceeds. 2 * fee is added to the escrow's fee and q to its volume. Receipt: ok 1, filled and crossed the fill, quote q, fee the taker's fee.

When not done, nothing moves and the receipt has ok 0. The circuit does not say which condition failed.

done reveals that this answer traded. filled reveals that the deal has nothing left. The maker's side is public on the deal. Neither limit, neither size and the price are revealed. The maker's limit stays in the escrow for the next answer.

settle_deal

Queued by cancel_deal.

InputSealed toMeaning
ledgerthe maker's reading keyThe maker's ledger.
dealthe clusterThe deal's escrow.
bookthe clusterThe market's book.

Outputs: the book and the maker's ledger. Reveals nothing.

The escrow's locked and proceeds move to the maker's ledger: for a maker who sold, locked as base and proceeds as quote; for a maker who bought, proceeds as base and locked as quote. A buying maker locked quote at their own limit and paid the midpoint, so the difference returns here. The escrow's fee is added to the pool's fee_quote and its volume to the interval's crossed volume, where the next sounding reveals them. Receipt: ok 1, filled the base credited, quote the quote credited.

sound

InputSealed toMeaning
bookthe clusterThe market's book.

Outputs: the book, to the cluster, and five revealed u64 values in this order:

RevealedUnitMeaning
pricepriceThe pool's mid, mid(base, quote), at the time of the sounding. A mid that does not fit a u64 is reported as 2^64 - 1.
crossedquote atomsVolume crossed in the book since the last sounding, with the volume of deals settled in the interval.
sweptquote atomsVolume swept from the pool since the last sounding.
fee_basebase atomsProtocol fees accrued since the last sounding in base.
fee_quotequote atomsProtocol fees accrued since the last sounding in quote.

The four counters are then set to 0 in the book, which starts the next interval. The reserves, the shares and the slots are not revealed. The price is their ratio only.

Circuit weights

The weight of each circuit as the program's build reports it. A heavier circuit is more work for the cluster.

CircuitWeight
init_market0.41B
deposit0.33B
withdraw0.35B
process_order1.75B
settle_slot0.64B
add_liquidity1.20B
remove_liquidity0.96B
open_deal0.62B
take_deal0.69B
settle_deal0.68B
sound0.55B

The time each takes from queue to callback is in Limits and measured figures.