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

Program

The Hadal program's id, accounts, instructions, events, errors and status values.

Hadal is one Solana program built as an Arcium MXE. An instruction that changes sealed state queues a computation on the cluster and returns. The cluster's result arrives in a second transaction, the callback, which writes the new ciphertext to the accounts. The lifecycle is told in Arcium, and what each computation does with its inputs in Circuits.

Program id

ProgramAddress
hadalHb4CKfTCoERvV2sCATZcu337DK2j1pV2Xkj7sWwFeghE
ArciumArcj82pX7HxYKLR92qvgZUAd7vGS1k4hQvAFcPATFdEQ

The program is written with Anchor. Its IDL names every instruction, account, event and error on this page with the same spelling, in snake case for instructions and fields.

Accounts and seeds

Every account is a program derived address of the Hadal program. Seeds are the literal string, then the addresses in order. seq and id are u64 values in 8 little-endian bytes.

AccountSeedsHolds
Config["config"]The venue's settings: authority, keeper, fee recipient, the HADAL mint, the fee rates, the protocol's share of the sweep fee, the sounding interval and the default attempts per taker.
Market["market", base_mint, quote_mint]One pair of tokens: the sealed book (the pool and the resting orders), the mints and vaults, the creator and the slot it was created in, the order queue, which book slots are taken, the last sounding and the protocol fees owed.
Vault["vault", market, mint]A token account owned by the market that holds one of its two tokens. Each market has two.
Balance["balance", market, owner]A wallet's sealed balance in one market: base, quote, shares and the receipt of its last action, sealed to the owner's reading key. Also the public amount of a deposit or withdrawal in flight.
Order["order", market, seq]One sealed order: its sealed terms, kind, status, book slot, expiry, and the owner's ledger as the order's last computation left it, which holds its receipt.
Deal["deal", maker, id]One deal: the maker's public side, the maker's sealed terms, the sealed escrow, the counterparty, attempts per taker, status and expiry. A deal's link is this account's address.
DealAttempts["attempts", deal, taker]How many attempts one taker has used on one deal.

A market is derived from its base mint and then its quote mint, so the same two mints in the other order are a different market.

Five sealed values live in these accounts. Each is an array of 32-byte ciphertexts with a nonce beside it.

Sealed valueWhereSealed to
The bookMarket.book, 11 ciphertextsThe cluster alone. It holds the pool and the resting orders. No key outside the cluster opens it.
A ledgerBalance.ledger, 4 ciphertextsThe reading key in Balance.key, shared with the cluster. The owner reads it; the cluster computes on it.
An order's termsOrder.terms, 5 ciphertextsThe reading key in Order.key, shared with the cluster.
A deal's maker termsDeal.terms, 5 ciphertextsThe maker's reading key in Deal.terms_key, shared with the cluster. A taker cannot open them.
A deal's escrowDeal.state, 3 ciphertextsThe cluster alone.

The fields inside each sealed value are listed in Circuits. Every other field below is public.

Config

NameTypeMeaning
authoritypubkeyThe wallet that may change the settings.
keeperpubkeyA recorded address. The program gives it no right that other wallets lack.
fee_recipientpubkeyThe wallet whose token accounts receive protocol fees in pay_fees.
hadal_mintpubkeyThe mint of HADAL. The default address while not set.
protocol_share_bpsu16The protocol's share of the sweep fee, in basis points of that fee, 0 to 10000.
protocol_share_setboolWhether the share has been set. process_order is refused until it is.
sweep_bpsu16The sweep fee in basis points.
cross_bpsu16The cross fee each side pays, in basis points.
deal_bpsu16The deal fee each side pays, in basis points.
sounding_intervalu64Slots that must pass between two soundings of a market.
default_attemptsu8Attempts each taker gets on a deal opened with attempts 0.
bumpu8The bump of the address.

The rates are told in Fees.

Market

NameTypeMeaning
book[[u8; 32]; 11]Sealed to the cluster: the pool and the six resting orders.
book_nonceu128The nonce of the book ciphertext.
base_mintpubkeyThe base token.
quote_mintpubkeyThe quote token.
base_vaultpubkeyThe vault that holds the base token.
quote_vaultpubkeyThe vault that holds the quote token.
base_token_programpubkeyThe token program of the base mint.
quote_token_programpubkeyThe token program of the quote mint.
base_decimalsu8Decimals of the base mint.
quote_decimalsu8Decimals of the quote mint.
creatorpubkeyThe wallet that created the market, or the wallet that claimed it by funding it after the claim window.
created_slotu64The slot the market was created in. The claim window counts from it.
readyboolTrue once the pool is open.
pendingpubkeyThe computation account in flight on the book. The default address when none.
pending_sinceu64The slot that computation was queued in.
headu64The sequence of the next order to process.
tailu64The sequence the next placed order receives.
slots[u64; 6]For each book slot, the sequence plus 1 of the dark order resting there, or 0 when the slot is free.
seed_baseu64The creator's first liquidity in base atoms.
seed_quoteu64The creator's first liquidity in quote atoms.
first_priceu64seed_quote times 2^32 divided by seed_base.
last_sound_slotu64The slot of the last sounding, or of the pool opening before the first.
last_priceu64The pool's price at the last sounding.
last_crossedu64Crossed volume of the last sounding, in quote atoms.
last_sweptu64Swept volume of the last sounding, in quote atoms.
soundingsu64How many soundings the market has had.
fees_owed_baseu64Protocol fees revealed by soundings and not yet paid, in base atoms.
fees_owed_quoteu64The same in quote atoms.
bumpu8The bump of the address.

Prices and amounts use the units in Limits.

Balance

NameTypeMeaning
ledger[[u8; 32]; 4]Sealed to the owner's reading key: base, quote, shares and the receipt of the last action.
key[u8; 32]The owner's reading key (the x25519 public key) the ledger is sealed to.
nonceu128The nonce of the ledger ciphertext.
marketpubkeyThe market.
ownerpubkeyThe wallet.
freshboolTrue until the first computation writes the ledger.
pendingpubkeyThe computation account in flight on the balance. The default address when none.
pending_sinceu64The slot that computation was queued in.
pending_baseu64Base atoms of a deposit waiting for its computation.
pending_quoteu64Quote atoms of a deposit waiting for its computation.
withdraw_baseu64Base atoms of a withdrawal waiting for its computation.
withdraw_quoteu64Quote atoms of a withdrawal waiting for its computation.
bumpu8The bump of the address.

Order

NameTypeMeaning
terms[[u8; 32]; 5]Sealed to the owner's reading key: side, size, limit, and the owner's address in two parts.
key[u8; 32]The reading key the terms are sealed with.
nonceu128The nonce of the terms.
marketpubkeyThe market.
ownerpubkeyThe wallet that placed it.
sequ64The order's sequence in the market's queue.
kindu80 swap, 1 dark.
statusu80 pending, 1 resting, 2 closed.
slotu8The book slot a dark order was given, 0 to 5. The order holds it only while its status is resting.
closingboolTrue while a cancel of the resting order is in flight.
expiryi64Unix seconds. An order still pending after it is closed unprocessed, and a resting order can be cancelled by anyone after it. 0 for none, on a swap only.
placed_ati64Unix seconds when it was placed.
receipt[[u8; 32]; 4]The owner's ledger as the order's last computation left it, sealed to the owner's reading key. Its receipt is the order's result.
receipt_nonceu128The nonce of that ledger.
bumpu8The bump of the address.

Deal

NameTypeMeaning
state[[u8; 32]; 3]Sealed to the cluster: the deal's escrow.
state_nonceu128The nonce of the escrow.
terms[[u8; 32]; 5]Sealed to the maker's reading key: size, minimum size, limit, and the maker's address in two parts, as the maker sealed them.
terms_key[u8; 32]The maker's reading key.
terms_nonceu128The nonce of the terms.
marketpubkeyThe market.
makerpubkeyThe wallet that opened it.
takerpubkeyThe one counterparty, or the default address when any wallet holding the link may answer.
buyboolThe maker's side, public: true when the maker buys the base token. A taker trades the other side.
idu64The maker's number for the deal, part of its address.
attemptsu8Attempts each taker gets.
statusu80 opening, 1 open, 2 done, 3 cancelled, 4 expired, 5 void.
expiryi64Unix seconds after which the deal takes no answers.
created_ati64Unix seconds when it was opened.
settledboolTrue once the escrow and proceeds are back in the maker's sealed balance, or when the deal is void.
closingu8The status a settlement in flight leaves the deal in.
pendingpubkeyThe computation account in flight on the deal. The default address when none.
pending_sinceu64The slot that computation was queued in.
bumpu8The bump of the address.

A deal's link carries the address of this account. Whoever opens the link reads the public fields above and answers with take_deal.

DealAttempts

NameTypeMeaning
dealpubkeyThe deal.
takerpubkeyThe taker.
usedu8Attempts the taker has used.
bumpu8The bump of the address.

One computation at a time

A market's book, a balance and a deal each carry pending, the computation in flight on that account. An instruction that queues a computation sets pending on every account its circuit writes, and is refused with Busy when one of them is already set. The callback clears it. A callback whose computation is not the pending one is refused with StaleComputation.

InstructionAccounts it holds until the callback
deposit, withdrawThe balance.
soundThe market's book.
open_pool, process_order, collect, cancel_order, add_liquidity, remove_liquidityThe market's book and the balance.
open_deal, take_dealThe deal and the balance.
cancel_dealThe deal, the maker's balance and the market's book.

Orders of one market are therefore processed one after another, in the order of their seq. No order can hold the queue: process_order closes the head order without a computation when it cannot run.

Arcium accounts of a queue instruction

Every instruction that queues a computation takes computation_offset as its first argument and these twelve accounts first, in this order. The sections below list only what follows them.

AccountSigner, writableMeaning
payersigner, writableThe wallet that sends the instruction. It pays the computation. The sections below give its name in each instruction: owner, creator, maker, taker, signer or payer.
sign_pda_accountwritableThe address of the Hadal program with the seed ArciumSignerAccount. Created by the first instruction that needs it.
mxe_accountHadal's MXE account in the Arcium program.
mempool_accountwritableThe cluster's mempool.
executing_poolwritableThe cluster's executing pool.
computation_accountwritableThe account of this computation, derived from computation_offset.
comp_def_accountThe computation definition of the circuit the instruction queues.
cluster_accountwritableThe cluster.
pool_accountwritableArcium's fee pool, G2sRWJvi3xoyh5k2gY49eG9L8YhAEWQPtNb1zb1GXTtC.
clock_accountwritableArcium's clock, 7EbMUTLo5DjdzbN7s8BXeZwXzEwNQb1hScfRvWg8a6ot.
system_programThe system program.
arcium_programThe Arcium program.

computation_offset is a u64 the sender chooses, new for each computation. It decides the address of the computation account, and that address is what pending holds. The @arcium-hq/client package derives each address: getArciumSignerAccAddress, getMXEAccAddress, getMempoolAccAddress, getExecutingPoolAccAddress, getComputationAccAddress, getCompDefAccAddress, getClusterAccAddress, getFeePoolAccAddress and getClockAccAddress. The SDK fills all of them.

A callback is sent by the cluster through the Arcium program. It verifies the output against the cluster and the computation account, and fails with AbortedComputation when the output does not verify.

Instructions

InstructionCircuitWho may send it, and what it does
create_marketAnyone. Creates the market account and the two vaults for a pair of mints. The signer becomes the market's creator.
fund_marketThe market's creator, before the pool opens, or any wallet when the market still holds no funds after its claim window, which makes that wallet the creator. Moves the first liquidity from the wallet to the vaults. The two amounts are public and set the first price.
open_poolinit_marketThe market's creator, once. Opens the pool with the first liquidity and credits sealed shares to the creator's balance.
open_balanceAny wallet, once per market. Creates the wallet's sealed balance in the market, sealed to the reading key it passes.
depositdepositThe balance's owner. Moves tokens from the wallet to the vault at once. The sealed balance adds them when the computation lands.
withdrawwithdrawThe balance's owner. Asks for tokens back. The callback pays the wallet if the sealed balance covers the amount, otherwise nothing moves.
place_orderThe balance's owner. Puts a sealed order (side, size, limit) at the tail of the market's queue. Its kind, swap or dark, and its expiry are public. A dark order needs an expiry at most one day ahead.
process_orderprocess_orderAnyone. Runs the order at the head of the market's queue: cross at the pool's mid, then sweep (a swap) or rest (a dark order). Closes it without a computation when it was cancelled, its expiry has passed, its owner's balance is busy, or it is dark and the book is full.
collectsettle_slotThe order's owner. Moves a resting order's proceeds to the owner's sealed balance. The order keeps resting.
cancel_ordersettle_slotThe order's owner, or anyone once the order's expiry has passed. A pending order closes at once with no computation, while the market has no computation in flight. A resting order returns what it still has locked and its proceeds, and frees its book slot.
add_liquidityadd_liquidityThe owner of a funded balance. Moves sealed amounts of both tokens from the sealed balance to the pool, in the pool's ratio, for sealed shares.
remove_liquidityremove_liquidityThe owner of a funded balance. Turns a sealed number of shares back into both tokens in the sealed balance.
open_dealopen_dealThe maker. Opens a deal on a public side with sealed size, minimum size and limit, for one named counterparty or for anyone holding its link. The escrow leaves the maker's sealed balance.
take_dealtake_dealThe named counterparty, or any wallet other than the maker when the deal names none. Answers the deal with a sealed size and limit. Uses one attempt.
cancel_dealsettle_dealThe maker for an open deal; anyone for a filled deal or one past its expiry. Closes the deal and returns its remaining escrow and its proceeds to the maker's sealed balance.
soundsoundAnyone, once the sounding interval has passed since the market's last sounding. Takes a sounding of the market.
pay_feesAnyone. Pays the protocol fees that soundings revealed from the vaults to the fee recipient's token accounts.
reclaimAnyone. Releases a balance whose computation expired, and refunds a deposit that was waiting on it to the owner's token account.
release_marketAnyone. Releases a market's book whose computation expired.
release_dealAnyone. Releases a deal whose computation expired. A deal that was still opening becomes void.

Sealed arguments are 32-byte ciphertexts made with the sender's reading key and a fresh nonce; the instruction also takes that key (the x25519 public key) and the nonce as a u128. How to seal is told in The reading key.

Every sealed argument ends with the address of the wallet it was sealed for, as two u128 values: bytes 0 to 15 and bytes 16 to 31 of the address, each little-endian. They are written owner_lo and owner_hi below. The circuit compares them with the wallet the instruction acts for, and an argument sealed for another address makes the action void. The SDK's ownerLimbs computes the pair.

create_market

Takes no arguments.

AccountSigner, writableMeaning
creatorsigner, writablePays for the three accounts and becomes Market.creator.
base_mintThe base token.
quote_mintThe quote token. Must differ from base_mint.
marketwritableCreated at ["market", base_mint, quote_mint].
base_vaultwritableCreated at ["vault", market, base_mint], a token account whose authority is the market.
quote_vaultwritableCreated at ["vault", market, quote_mint].
base_token_programThe token program of base_mint.
quote_token_programThe token program of quote_mint.
system_programThe system program.

Checks both mints against the supported mints and records the mints, vaults, token programs, decimals, creator and the current slot. Emits MarketCreated.

Errors: SameMint, UnsupportedMint.

fund_market

ArgumentTypeMeaning
base_amountu64Base atoms to move to the base vault. Greater than 0.
quote_amountu64Quote atoms to move to the quote vault. Greater than 0.
AccountSigner, writableMeaning
creatorsigner, writableThe market's creator, or any wallet when the market holds no funds and the claim window has passed.
marketwritableThe market, not yet open.
base_mintThe market's base mint.
quote_mintThe market's quote mint.
base_vaultwritableThe market's base vault.
quote_vaultwritableThe market's quote vault.
creator_basewritableThe creator's token account of the base mint.
creator_quotewritableThe creator's token account of the quote mint.
base_token_programMarket.base_token_program.
quote_token_programMarket.quote_token_program.

Moves both amounts from the signer's token accounts to the vaults, adds them to seed_base and seed_quote, and sets first_price to seed_quote * 2^32 / seed_base. Both amounts are public. It emits no event. Sent more than once before the pool opens, the amounts add up.

The first price must be greater than 0 and inside the first price range. A signer who is not the creator is accepted only when the market holds no first liquidity (seed_base and seed_quote are both 0) and the claim window has passed since the market was created. That signer becomes Market.creator.

Errors: InvalidAmount, NotOwner (the signer is not the creator, and the market is funded or the claim window has not passed), Busy (the market's open_pool computation is in flight), PriceOutOfRange, MarketAlreadyOpen, WrongVault.

open_pool

Argument: computation_offset (u64). Queues init_market.

AccountSigner, writableMeaning
creatorsigner, writableThe payer: the market's creator.
marketwritableThe market, funded and not yet open.
creator_balancewritableThe signer's balance in this market, at ["balance", market, creator]. Open it with open_balance first.

The signer must be Market.creator: the wallet that created the market, or the one that claimed it with fund_market. The instruction passes seed_base and seed_quote to the circuit in plaintext. The callback writes the book, sets ready, sets last_price to first_price and last_sound_slot to the current slot, writes the creator's ledger with the shares, and emits MarketReady.

Errors: NotOwner (the signer is not the creator), MarketAlreadyOpen, NotFunded, Busy.

open_balance

ArgumentTypeMeaning
key[u8; 32]The owner's reading key (x25519 public key). Every ledger of this balance is sealed to it.
AccountSigner, writableMeaning
ownersigner, writableThe wallet. Pays for the account.
marketThe market.
balancewritableCreated at ["balance", market, owner].
system_programThe system program.

Creates the balance with fresh true and emits BalanceOpened. A wallet has one balance per market. The balance holds nothing until a deposit lands.

deposit

ArgumentTypeMeaning
computation_offsetu64See the Arcium accounts above.
sideu80 for the base token, 1 for the quote token.
amountu64Atoms to deposit. Greater than 0. Public.
AccountSigner, writableMeaning
ownersigner, writableThe payer: the balance's owner.
marketwritableThe market.
balancewritableAt ["balance", market, owner].
vaultwritableThe market's vault for the side.
mintThe market's mint for the side.
owner_tokenwritableThe owner's token account of that mint.
token_programThe token program of that mint.

Moves amount from owner_token to the vault in this transaction, records it in pending_base or pending_quote, emits DepositQueued and queues deposit with the amount in plaintext. The callback clears the pending amount, writes the ledger and emits DepositLanded. If the computation expires, reclaim sends the tokens back.

Errors: InvalidAmount, InvalidSide, WrongVault, Busy.

withdraw

Arguments: computation_offset, side and amount, as in deposit. Queues withdraw. Accounts: the same seven as deposit.

Records the amount in withdraw_base or withdraw_quote, emits WithdrawQueued and queues the circuit with the amount in plaintext. No token moves in this transaction. The callback writes the ledger and, when the circuit reveals that the sealed balance covered the amount, moves amount from the vault to owner_token. It emits WithdrawDone with paid true or false. When paid is false nothing moved and the sealed balance is unchanged.

Errors: InvalidAmount, InvalidSide, WrongVault, EmptyBalance, Busy.

place_order

ArgumentTypeMeaning
terms[[u8; 32]; 5]Sealed: side (1 buy, 0 sell), size in base atoms, limit as a price, owner_lo, owner_hi.
key[u8; 32]The reading key the terms are sealed with.
nonceu128The nonce the terms are sealed under.
kindu80 swap, 1 dark. Public.
expiryi64Unix seconds, public. A dark order requires one, in the future and at most one day ahead. A swap takes 0 for none, or a future time.
AccountSigner, writableMeaning
ownersigner, writableThe wallet. Pays for the order account.
marketwritableThe market.
balanceAt ["balance", market, owner].
orderwritableCreated at ["order", market, seq] where seq is Market.tail.
system_programThe system program.

Stores the sealed terms, gives the order the sequence Market.tail, sets its status to pending, advances tail and emits OrderPlaced. It queues no computation and takes no Arcium accounts: the order waits for process_order. The order's address is derived from tail as it is when the transaction runs. A transaction built on an earlier tail fails the address check of the order account; read the market again and rebuild it.

An order that is still pending when its expiry passes is closed by process_order without being run. A dark order that rests can be cancelled by anyone after its expiry, so no order holds a book slot longer than the resting time.

Errors: InvalidKind, InvalidExpiry (a dark order with no expiry, a past one, or one more than a day ahead; a swap with a past one), MarketNotReady, EmptyBalance.

process_order

Argument: computation_offset. Queues process_order.

AccountSigner, writableMeaning
payersigner, writableAny wallet.
configAt ["config"].
marketwritableThe market.
orderwritableThe order whose seq equals Market.head.
balancewritableThe balance of the order's owner, at ["balance", market, order.owner].

The order must be at the head of the queue, and the market must have no computation in flight. The instruction then takes the first case that applies:

  • The order was cancelled while pending: head advances and nothing else happens.
  • The order has an expiry and the current time is past it: the order closes, head advances and OrderReturned is emitted with reason 2.
  • The owner's balance has another computation in flight: the order closes, head advances and OrderReturned is emitted with reason 3.
  • The order is dark and all six book slots are taken: the order closes, head advances and OrderReturned is emitted with reason 0.
  • Otherwise the instruction picks the first free slot for a dark order and queues the circuit with the order's terms, the owner's ledger, the book, and in plaintext the owner's address, whether the order sweeps or rests, the slot, and the three fee rates from Config.

An order returned with reason 0, 2 or 3 ran no computation: its sealed balance is untouched and it has no receipt. Place it again.

The callback writes the book and the owner's ledger, copies that ledger to Order.receipt, and advances head. The circuit reveals whether a dark order rests. When it does, the order becomes resting and its sequence plus 1 is written to its slot in Market.slots. A dark order with nothing left to rest, and every swap, becomes closed and holds no slot. The callback emits OrderProcessed.

Errors: ProtocolShareUnset, NotQueueHead, Busy (the market has a computation in flight), WrongMarket.

collect

Argument: computation_offset. Queues settle_slot with close false.

AccountSigner, writableMeaning
signersigner, writableThe payer: the order's owner.
marketwritableThe market.
orderwritableThe resting order.
balancewritableThe owner's balance, at ["balance", market, order.owner].

The callback writes the book and the ledger, copies the ledger to Order.receipt and emits OrderSettled with closed false. The order stays resting in its slot.

Errors: NotOwner, NotResting, WrongMarket, Busy.

cancel_order

Argument: computation_offset. Accounts: the same as collect, and signer may be any wallet once the order's expiry has passed.

  • A pending order, cancelled by its owner: the status becomes closed in this transaction and OrderReturned is emitted with reason 1. No computation is queued, though the instruction still takes the Arcium accounts. It is refused with Busy while the market has a computation in flight, because that computation may be this order's: send it again once the callback has landed.
  • A resting order, cancelled by its owner, or by anyone when expiry is not 0 and the current time is past it: queues settle_slot with close true. The callback writes the book and the ledger, frees the slot in Market.slots, closes the order and emits OrderSettled with closed true.

Errors: NotOwner (not the owner, and the order has no expiry or has not reached it; or a pending order cancelled by another wallet), NotResting (the order is already closed), WrongMarket, Busy.

add_liquidity

ArgumentTypeMeaning
computation_offsetu64See the Arcium accounts above.
amounts[[u8; 32]; 4]Sealed: the most base atoms and the most quote atoms to add, owner_lo, owner_hi.
key[u8; 32]The reading key the amounts are sealed with.
nonceu128The nonce the amounts are sealed under.
AccountSigner, writableMeaning
ownersigner, writableThe payer: the balance's owner.
marketwritableThe market.
balancewritableAt ["balance", market, owner].

Emits LiquidityQueued with adding true and queues add_liquidity. The callback writes the book and the ledger and emits LiquidityChanged.

Errors: MarketNotReady, EmptyBalance, Busy.

remove_liquidity

Arguments: computation_offset, shares ([[u8; 32]; 3], sealed: the shares to give back, owner_lo, owner_hi), key, nonce. Accounts: the same three as add_liquidity. Queues remove_liquidity.

Emits LiquidityQueued with adding false. The callback writes the book and the ledger and emits LiquidityChanged.

Errors: MarketNotReady, EmptyBalance, Busy.

open_deal

ArgumentTypeMeaning
computation_offsetu64See the Arcium accounts above.
idu64A number the maker chooses, unique among the maker's deals. Part of the deal's address.
buyboolThe maker's side, public: true to buy the base token, false to sell it.
terms[[u8; 32]; 5]Sealed: size in base atoms, minimum size in base atoms, limit as a price, owner_lo, owner_hi.
key[u8; 32]The maker's reading key.
nonceu128The nonce the terms are sealed under.
takerpubkeyThe one counterparty, or the default address for anyone holding the link. Not the maker.
attemptsu8Attempts each taker gets. 0 takes Config.default_attempts.
expiryi64Unix seconds after which the deal takes no answers. In the future.
AccountSigner, writableMeaning
makersigner, writableThe payer. Pays for the deal account.
configAt ["config"].
marketThe market.
balancewritableThe maker's balance, at ["balance", market, maker].
dealwritableCreated at ["deal", maker, id].

Stores the side and the sealed terms with status opening, emits DealOpened and queues open_deal with the terms, the maker's ledger, and in plaintext the side, the deal fee rate and the maker's address. The callback writes the escrow and the ledger. When the circuit reveals that the sealed balance covered the escrow the status becomes open; otherwise it becomes void, settled is set and nothing left the balance. It emits DealReady.

Errors: MarketNotReady, InvalidExpiry, EmptyBalance, InvalidCounterparty (taker is the maker), Busy.

take_deal

ArgumentTypeMeaning
computation_offsetu64See the Arcium accounts above.
answer[[u8; 32]; 4]Sealed: size in base atoms, limit as a price, owner_lo, owner_hi. The taker trades the side opposite to Deal.buy.
key[u8; 32]The taker's reading key.
nonceu128The nonce the answer is sealed under.
AccountSigner, writableMeaning
takersigner, writableThe payer. Pays for the attempts account the first time.
configAt ["config"].
dealwritableThe deal, at ["deal", deal.maker, deal.id].
balancewritableThe taker's balance in the deal's market, at ["balance", deal.market, taker].
attemptswritableAt ["attempts", deal, taker]. Created on the taker's first answer.

The deal must be open and not past its expiry, the signer must not be the maker, and when the deal names a counterparty the signer must be it. The instruction adds one to the taker's used attempts, emits DealTaken and queues take_deal with the answer, the taker's ledger, the escrow, the deal fee rate and the taker's address. The attempt is used when the instruction lands, whatever the computation returns.

The callback writes the escrow and the taker's ledger and emits DealAnswered with done (the answer traded) and filled (the deal has nothing left). When filled is true the status becomes done. A deal that traded part of its size stays open for further answers. The maker's proceeds stay in the escrow until cancel_deal settles the deal.

Errors: DealNotOpen, DealExpired, InvalidCounterparty (the signer is the maker), NotCounterparty, EmptyBalance, OutOfAttempts, Busy.

cancel_deal

Argument: computation_offset. Queues settle_deal.

AccountSigner, writableMeaning
signersigner, writableThe payer. The maker for an open deal before its expiry; any wallet otherwise.
marketwritableThe deal's market.
dealwritableThe deal.
balancewritableThe maker's balance, at ["balance", deal.market, deal.maker].

Settles a deal that is not yet settled. The status the settlement ends in depends on the deal:

DealWhoEnds as
doneanyonedone (2)
open, past its expiryanyoneexpired (4)
open, before its expirythe makercancelled (3)

The callback writes the book and the maker's ledger, sets the status, sets settled and emits DealSettled. The book is written because the deal's fees and volume join the market's figures for the next sounding.

Errors: DealNotOpen (the deal is opening, void or already settled), NotOwner, WrongMarket, Busy.

sound

Argument: computation_offset. Queues sound.

AccountSigner, writableMeaning
payersigner, writableAny wallet.
configAt ["config"].
marketwritableThe market.

Requires the current slot to be at least last_sound_slot + sounding_interval. The callback writes the book, sets last_sound_slot, last_price, last_crossed and last_swept, adds the revealed protocol fees to fees_owed_base and fees_owed_quote, adds one to soundings and emits Sounding. The interval is told in Soundings.

Errors: MarketNotReady, TooEarly, Busy.

pay_fees

Takes no arguments and queues nothing.

AccountSigner, writableMeaning
signersignerAny wallet.
configAt ["config"].
marketwritableThe market.
base_vaultwritableThe market's base vault.
quote_vaultwritableThe market's quote vault.
base_mintThe market's base mint.
quote_mintThe market's quote mint.
recipient_basewritableA token account of the base mint owned by Config.fee_recipient.
recipient_quotewritableA token account of the quote mint owned by Config.fee_recipient.
base_token_programMarket.base_token_program.
quote_token_programMarket.quote_token_program.

Moves fees_owed_base and fees_owed_quote from the vaults to the recipient's token accounts, sets both to 0 and emits FeesPaid. What the fees are used for is told in The token.

Errors: WrongVault.

Release instructions

A computation the cluster does not run expires, and its callback never arrives. The accounts it held stay marked with pending until a release instruction clears them. Each release instruction can be sent by any wallet, takes no arguments, and succeeds only once the release threshold has passed since pending_since.

After an expiredSend
deposit, withdrawreclaim for the balance.
soundrelease_market.
open_pool, process_order, collect, cancel_order, add_liquidity, remove_liquidityrelease_market, and reclaim for the balance.
open_deal, take_dealrelease_deal, and reclaim for the balance.
cancel_dealrelease_deal, release_market, and reclaim for the maker's balance.

No sealed value changed, because no callback wrote one. After the release the action is sent again: an order is still pending at the head of the queue and process_order runs it; a resting order can be collected or cancelled again; a deal that was being settled can be settled again. A deal whose open_deal expired is made void by release_deal, and its escrow never left the maker's balance: open a new deal under another id. An attempt used by an expired take_deal stays used.

Errors of all three: NothingPending, ComputationStillLive.

reclaim

AccountSigner, writableMeaning
signersignerAny wallet.
marketThe balance's market.
balancewritableThe balance to release.
vaultwritableThe market's vault of the token a waiting deposit was made in.
mintThe mint of that token.
owner_tokenwritableA token account of that mint owned by Balance.owner.
token_programThe token program of that mint.

Clears pending, and clears the waiting deposit and withdrawal amounts. When a deposit was waiting, its amount moves from the vault back to owner_token. It emits DepositRefunded with the amount refunded, which is 0 when no deposit was waiting. The refund goes to the balance's owner whoever signs.

Further errors: WrongMarket, WrongVault.

release_market

Accounts: signer (signer) and market (writable). Clears Market.pending and emits ComputationReleased with the market's address.

release_deal

Accounts: signer (signer) and deal (writable). Clears Deal.pending and emits ComputationReleased with the deal's address. A deal whose status is still opening becomes void with settled true.

Events

Events are written to the transaction's logs in Anchor's event encoding. The middle column is the instruction or callback that emits each one.

EventEmitted byFields
ConfigChangedset_configThe venue's settings after a change: fee_recipient, keeper, hadal_mint, protocol_share_bps, protocol_share_set, sounding_interval.
MarketCreatedcreate_marketA market exists: market, base_mint, quote_mint, creator.
MarketReadyinit_market_callbackThe market's pool is open: market, first_price, creator, and the creator's sealed ledger.
BalanceOpenedopen_balanceA wallet opened a sealed balance: balance, market, owner.
DepositQueueddepositTokens entered a vault: balance, market, owner, mint, amount.
DepositLandeddeposit_callbackThe deposit is in the sealed balance: balance, and the owner's sealed ledger.
DepositRefundedreclaimA balance was released after its computation expired: balance, mint, and the amount refunded, 0 when no deposit was waiting.
WithdrawQueuedwithdrawA withdrawal was asked for: balance, market, owner, mint, amount.
WithdrawDonewithdraw_callbackThe withdrawal was decided: balance, mint, amount, paid (true when the tokens moved, false when the sealed balance did not cover the amount), and the owner's sealed ledger.
ComputationReleasedrelease_market, release_dealA market or a deal was released after its computation expired: account.
OrderPlacedplace_orderA wallet placed a sealed order: order, market, owner, seq, kind, expiry. Nothing of its side, size or limit.
OrderProcessedprocess_order_callbackThe order's computation landed: order, market, owner, status (1 when a dark order rests, 2 otherwise), slot, and the owner's sealed ledger with the receipt.
OrderReturnedprocess_order, cancel_orderAn order closed without a computation: order, reason (0 the book was full, 1 the owner cancelled it while pending, 2 its expiry passed before it was processed, 3 its owner's balance was busy with another computation).
OrderSettledsettle_slot_callbackA collect or a cancel of a resting order landed: order, closed (true for a cancel), and the owner's sealed ledger.
LiquidityQueuedadd_liquidity, remove_liquidityA wallet asked to change its liquidity: balance, market, adding.
LiquidityChangedadd_liquidity_callback, remove_liquidity_callbackThe liquidity computation landed: balance, adding, and the owner's sealed ledger.
DealOpenedopen_dealA wallet opened a deal: deal, market, maker, taker, buy (the maker's side), id, attempts, expiry.
DealReadyopen_deal_callbackThe deal's escrow was decided: deal, open (true when the maker's sealed balance covered the escrow, false when the deal is void), and the maker's sealed ledger.
DealTakentake_dealA wallet answered a deal: deal, taker, attempts_used.
DealAnsweredtake_deal_callbackThe answer was decided: deal, taker, done (whether it traded), filled (whether the deal has nothing left), and the taker's sealed ledger.
DealSettledsettle_deal_callbackThe deal closed and its escrow and proceeds returned to the maker: deal, status, and the maker's sealed ledger.
Soundingsound_callbackA sounding: market, index, slot, unix_time, price, crossed, swept, fee_base, fee_quote.
FeesPaidpay_feesProtocol fees left the vaults for the fee recipient: market, base, quote.

Field types: an address is a pubkey; amount, seq, id, index, slot, price, crossed, swept, fee_base, fee_quote, base, quote, first_price and sounding_interval are u64; expiry and unix_time are i64 in Unix seconds, UTC; kind, status, reason, attempts and attempts_used are u8; protocol_share_bps is u16; paid, adding, open, done, filled, closed, buy and protocol_share_set are bool.

In a Sounding, price is the pool's price, crossed and swept are in quote atoms, fee_base is in base atoms and fee_quote in quote atoms, and index counts the market's soundings from 1.

A sealed ledger travels in an event as SealedLedger:

NameTypeMeaning
ciphertexts[[u8; 32]; 4]The owner's ledger after the computation, sealed to the owner's reading key.
nonce[u8; 16]The nonce of that ciphertext, little-endian.

It is the same value the callback wrote to Balance.ledger. Its receipt is the result of the action. Reading it is told in the receipts guide.

Errors

The program's own errors, with their numbers. A transaction the program refuses carries the number as a custom program error.

ErrorCodeRaised when
AbortedComputation6000A callback received an output that does not verify against the cluster and the computation account. Nothing is written.
Busy6001The market's book, the balance or the deal the instruction needs already has a computation in flight. Also raised by process_order, by cancel_order on a pending order and by fund_market while the market has one. Send again once that computation lands, or release it after it expires.
StaleComputation6002A callback arrived for a computation that is not the one pending on the account, for example after the account was released.
NothingPending6003reclaim, release_market or release_deal was sent for an account with no computation in flight.
ComputationStillLive6004reclaim, release_market or release_deal was sent before the release threshold had passed since the computation was queued.
NotAuthority6005The signer of a setup call is not the venue's authority, or the signer of initialize is not the program's upgrade authority.
NotOwner6006The signer does not own what the instruction acts on: collect or cancel_order by a wallet other than the order's owner (before expiry, or on a pending order), cancel_deal of an open deal by a wallet other than the maker, open_pool by a wallet other than the market's creator, fund_market by a wallet other than the creator unless the market holds no funds and its claim window has passed.
InvalidConfig6007A setting is out of range: a sounding interval of 0, or a protocol share above 10000 bps.
ProtocolShareUnset6008process_order was sent while the protocol's share of the sweep fee has not been set in Config.
UnsupportedMint6009create_market was given a Token-2022 mint with one of the refused extensions: transfer fee, transfer hook, permanent delegate, default account state or pausable.
SameMint6010create_market was given the same mint as base and quote.
InvalidAmount6011An amount of 0 was passed to deposit, withdraw or fund_market.
InvalidSide6012The side of deposit or withdraw is neither 0 (base) nor 1 (quote).
WrongVault6013A vault or mint account passed is not the market's vault or mint for that side.
WrongMarket6014The order, balance or deal passed belongs to a market other than the market account passed.
MarketNotReady6015The market's pool is not open yet. Raised by place_order, add_liquidity, remove_liquidity, open_deal and sound.
MarketAlreadyOpen6016fund_market or open_pool was sent for a market whose pool is already open.
NotFunded6017open_pool was sent before fund_market put both tokens in the vaults.
PriceOutOfRange6018fund_market would set a first price of 0 or of 2^32 quote atoms per base atom or more.
EmptyBalance6019The sealed balance has never had a computation land on it. Raised by withdraw, place_order, add_liquidity, remove_liquidity, open_deal and take_deal. Deposit first.
InvalidKind6020The kind of place_order is neither 0 (swap) nor 1 (dark).
InvalidExpiry6021The expiry is not acceptable. A swap takes 0 for none or a future time. A dark order requires a future time at most one day ahead. A deal requires a future time.
NotQueueHead6022process_order was given an order that is not at the head of the market's queue.
NotResting6023collect was sent for an order that is not resting, or cancel_order for an order that is already closed.
DealNotOpen6024take_deal was sent for a deal whose status is not open, or cancel_deal for a deal that is opening, void or already settled.
DealExpired6025take_deal was sent after the deal's expiry.
NotCounterparty6026take_deal was signed by a wallet other than the counterparty the deal names.
InvalidCounterparty6027The maker tried to answer their own deal, or opened a deal naming themselves as counterparty.
OutOfAttempts6028The taker has used every attempt the deal gives each taker.
TooEarly6029sound was sent before the sounding interval had passed since the market's last sounding.

A refusal that is decided inside a circuit is not an error of the program. An order, an answer or a liquidity change that the sealed balance does not cover lands as a callback that succeeds, and its receipt says the action was void. See Circuits.

Status and kind values

FieldValueMeaning
Order.kind 0swapCrosses the book, then sweeps the pool.
Order.kind 1darkCrosses the book, then rests.
Order.status 0pendingIn the market's queue, not yet processed.
Order.status 1restingA dark order, processed, with size resting in a book slot.
Order.status 2closedFinished: a processed swap, a processed dark order with nothing left to rest, a cancelled order, or an order returned unprocessed.
Deal.status 0openingThe escrow computation has not landed.
Deal.status 1openTakes answers.
Deal.status 2doneIts whole size traded.
Deal.status 3cancelledThe maker cancelled it and it is settled.
Deal.status 4expiredIt passed its expiry and it is settled.
Deal.status 5voidThe maker's sealed balance did not cover the escrow, the terms were not valid, or the opening computation expired. Nothing moved.
side 0baseIn deposit and withdraw: the base token.
side 1quoteIn deposit and withdraw: the quote token.
OrderReturned.reason 0book fullA dark order found no free slot.
OrderReturned.reason 1cancelledThe owner cancelled the order while it was pending.
OrderReturned.reason 2expiredThe order reached the head of the queue after its expiry.
OrderReturned.reason 3balance busyThe owner's balance had another computation in flight when the order reached the head of the queue.
Deal.buy truemaker buysThe maker buys the base token and a taker sells it.
Deal.buy falsemaker sellsThe maker sells the base token and a taker buys it.

Setup calls

These are sent by the venue and by no one else.

InstructionSignerDoes
initializethe program's upgrade authorityCreates Config with fee_recipient, keeper and sounding_interval, and makes the signer its authority.
set_configConfig.authorityChanges any of authority, keeper, fee_recipient, hadal_mint, protocol_share_bps and sounding_interval. Emits ConfigChanged.
init_<circuit>_comp_defConfig.authorityOne per circuit, eleven in all. Registers the circuit with Arcium, with its hash compiled into the program.

Errors: NotAuthority, InvalidConfig.