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.
| Circuit | Reveals | Computes |
|---|---|---|
init_market | nothing | Opens a market's pool with the creator's public first amounts and credits the creator's sealed balance with shares. |
deposit | nothing | Adds a public deposit to a sealed balance. |
withdraw | whether the sealed balance covered the amount | Takes a public withdrawal out of a sealed balance if the balance covers it. |
process_order | whether a dark order rests in the book | Runs 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_slot | nothing | Moves 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_liquidity | nothing | Moves sealed amounts of both tokens from a sealed balance to the pool, in the pool's ratio, and credits shares. |
remove_liquidity | nothing | Turns sealed shares back into both tokens in the sealed balance. |
open_deal | whether the maker's sealed balance covered the escrow | Moves a deal's escrow from the maker's sealed balance into the deal. |
take_deal | whether the answer traded, and whether the deal has nothing left | Compares 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_deal | nothing | Returns 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. |
sound | the pool's price, the interval's crossed volume and swept volume, and the protocol fees accrued in base and in quote | Takes 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.
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.
| Name | Type | Meaning |
|---|---|---|
base | u64 | Base atoms the wallet holds below. |
quote | u64 | Quote atoms the wallet holds below. |
shares | u64 | The wallet's shares of the pool. |
receipt | Receipt | The 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.
| Name | Type | Meaning |
|---|---|---|
ok | u64 | 1 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. |
filled | u64 | For an order or an answer: base atoms traded. Otherwise: base atoms credited or moved. |
quote | u64 | For an order or an answer: quote atoms paid or received for what traded. Otherwise: quote atoms credited or moved. |
crossed | u64 | Base atoms that traded by crossing. |
swept | u64 | For an order: base atoms that traded against the pool. For a liquidity change or a pool opening: the shares minted or given back. |
rested | u64 | Base atoms left resting in the book. |
fee | u64 | The 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 field | Type | Meaning |
|---|---|---|
base | u64 | The pool's base reserve. |
quote | u64 | The pool's quote reserve. |
shares | u64 | All shares of the pool. |
fee_base | u64 | Protocol fees accrued in base atoms since the last sounding. |
fee_quote | u64 | Protocol fees accrued in quote atoms since the last sounding. |
crossed | u64 | Crossed volume since the last sounding, in quote atoms. Deals settled in the interval are counted here. |
swept | u64 | Swept volume since the last sounding, in quote atoms. |
| Slot field | Type | Meaning |
|---|---|---|
side | u8 | 0 empty, 1 bid, 2 ask. |
limit | u64 | The resting order's limit. |
remaining | u64 | Base atoms still to trade. |
locked | u64 | What the owner put up and has not yet paid: quote atoms for a bid, base atoms for an ask. |
proceeds | u64 | What 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.
| Name | Type | Meaning |
|---|---|---|
side | u8 | The maker's side: 1 bid, 2 ask. |
limit | u64 | The maker's limit. |
min_size | u64 | The smallest answer the maker accepts, in base atoms. |
remaining | u64 | Base atoms still to trade. |
locked | u64 | The escrow not yet paid out: quote atoms for a bid, base atoms for an ask. |
proceeds | u64 | What the maker has received: base atoms for a bid, quote atoms for an ask. |
fee | u64 | Deal fees of both sides so far, in quote atoms. |
volume | u64 | Quote atoms traded so far. |
Inputs a wallet seals
| Input | Fields | Sent with |
|---|---|---|
OrderTerms | buy (bool), size, limit, owner | place_order |
Amounts | base, quote, owner | add_liquidity |
Shares | shares, owner | remove_liquidity |
DealTerms | size, min_size, limit, owner | open_deal |
Answer | size, limit, owner | take_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:
| Struct | Ciphertexts | Stored in |
|---|---|---|
Ledger | 4 | Balance.ledger, Order.receipt, and the SealedLedger of an event |
Book | 11 | Market.book |
Deal | 3 | Deal.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.
| Input | Sealed to | Meaning |
|---|---|---|
ledger | the creator's reading key | The creator's ledger. |
fresh | plaintext | Whether the balance has never been written. A fresh ledger starts from zero. |
base | plaintext | The first liquidity in base atoms. |
quote | plaintext | The 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
| Input | Sealed to | Meaning |
|---|---|---|
ledger | the owner's reading key | The owner's ledger. |
fresh | plaintext | Whether the balance has never been written. |
base | plaintext | Base atoms deposited, or 0. |
quote | plaintext | Quote 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
| Input | Sealed to | Meaning |
|---|---|---|
ledger | the owner's reading key | The owner's ledger. |
base | plaintext | Base atoms asked for, or 0. |
quote | plaintext | Quote 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
| Input | Sealed to | Meaning |
|---|---|---|
order | the owner's reading key | OrderTerms: buy, size, limit, owner. |
ledger | the owner's reading key | The owner's ledger. |
book | the cluster | The market's book. |
owner_lo, owner_hi | plaintext | The address of the order's owner. |
sweep | plaintext | True for a swap. |
rest | plaintext | True for a dark order. |
slot | plaintext | The book slot a dark order takes. |
cross_bps | plaintext | The cross fee per side. |
sweep_bps | plaintext | The sweep fee. |
share_bps | plaintext | The 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.
buy: ledger.quote >= bid_lock(size, limit, rate(max(cross_bps, sweep_bps)))
sell: ledger.base >= sizeThe 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:
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 sideThe 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:
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 u64The 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:
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:
bid: locked = bid_lock(resting, limit, rate(cross_bps)) quote atoms
ask: locked = resting base atomsThe 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
filled = crossed + swept
buy: base += filled
quote -= cross quote + cross fees + sweep quote + locked
sell: base -= filled + locked
quote += cross quote - cross fees + sweep quoteReceipt: 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).
| Input | Sealed to | Meaning |
|---|---|---|
ledger | the owner's reading key | The owner's ledger. |
book | the cluster | The market's book. |
slot | plaintext | The order's book slot. |
close | plaintext | True 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
| Input | Sealed to | Meaning |
|---|---|---|
amounts | the owner's reading key | Amounts: the most base and the most quote to add, owner. |
ledger | the owner's reading key | The owner's ledger. |
book | the cluster | The market's book. |
owner_lo, owner_hi | plaintext | The address of the balance's owner. |
Outputs: the book and the ledger. Reveals nothing.
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
| Input | Sealed to | Meaning |
|---|---|---|
shares | the owner's reading key | Shares: the shares to give back, owner. |
ledger | the owner's reading key | The owner's ledger. |
book | the cluster | The market's book. |
owner_lo, owner_hi | plaintext | The address of the balance's owner. |
Outputs: the book and the ledger. Reveals nothing.
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
| Input | Sealed to | Meaning |
|---|---|---|
terms | the maker's reading key | DealTerms: size, min_size, limit, owner. |
ledger | the maker's reading key | The maker's ledger. |
buy | plaintext | The maker's side, public on the deal. |
deal_bps | plaintext | The deal fee per side. |
owner_lo, owner_hi | plaintext | The maker's address. |
Outputs: the deal's escrow, to the cluster; the maker's ledger; one revealed boolean.
buy: lock = bid_lock(size, limit, rate(deal_bps)) quote atoms
sell: lock = size base atomsThe 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
| Input | Sealed to | Meaning |
|---|---|---|
answer | the taker's reading key | Answer: size, limit, owner. |
ledger | the taker's reading key | The taker's ledger. |
deal | the cluster | The deal's escrow. |
deal_bps | plaintext | The deal fee per side. |
owner_lo, owner_hi | plaintext | The 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.
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 u64The 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.
| Input | Sealed to | Meaning |
|---|---|---|
ledger | the maker's reading key | The maker's ledger. |
deal | the cluster | The deal's escrow. |
book | the cluster | The 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
| Input | Sealed to | Meaning |
|---|---|---|
book | the cluster | The market's book. |
Outputs: the book, to the cluster, and five revealed u64 values in this order:
| Revealed | Unit | Meaning |
|---|---|---|
price | price | The 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. |
crossed | quote atoms | Volume crossed in the book since the last sounding, with the volume of deals settled in the interval. |
swept | quote atoms | Volume swept from the pool since the last sounding. |
fee_base | base atoms | Protocol fees accrued since the last sounding in base. |
fee_quote | quote atoms | Protocol 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.
| Circuit | Weight |
|---|---|
init_market | 0.41B |
deposit | 0.33B |
withdraw | 0.35B |
process_order | 1.75B |
settle_slot | 0.64B |
add_liquidity | 1.20B |
remove_liquidity | 0.96B |
open_deal | 0.62B |
take_deal | 0.69B |
settle_deal | 0.68B |
sound | 0.55B |
The time each takes from queue to callback is in Limits and measured figures.