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

SDK

Every export of @hadal/sdk: the client and its options, the Action a call returns, and each call with its parameters, result, instructions and errors.

@hadal/sdk is the TypeScript package the app trades through. It seals values with the reading key, builds the program's instructions, follows the computations they queue and reads what comes back. It is an ES module that runs in a browser and in Node, and it never holds a wallet's secret key: every call that changes something returns instructions for the wallet to sign.

Amounts are token atoms as bigint. Prices and limits are fixed-point bigint values built with priceOf. Both are defined in Units. Public keys, connections and instructions are the types of @solana/web3.js.

A complete script that uses these calls in order is in Trade from a script with the SDK.

The client

HadalClient

new HadalClient(options: HadalOptions)

ts
import { Connection, PublicKey } from '@solana/web3.js'
import { HadalClient } from '@hadal/sdk'

const connection = new Connection(rpcUrl, 'confirmed')
const hadal = new HadalClient({ connection, owner: new PublicKey(walletAddress), clusterOffset })
OptionTypeMeaning
connectionConnectionThe RPC connection every read and every instruction build goes through. Required.
ownerPublicKeyThe wallet that signs and pays for the instructions the client builds. Required.
clusterOffsetnumberThe Arcium cluster the venue computes on: 2026 on mainnet, 456 on devnet. Required.
programIdPublicKeyThe Hadal program. Optional. Default: PROGRAM_ID.

The client exposes what it was built with and the Anchor program underneath:

PropertyTypeMeaning
connectionConnectionAs passed.
ownerPublicKeyAs passed.
clusterOffsetnumberAs passed.
programIdPublicKeyAs passed, or PROGRAM_ID.
programProgram<HadalIdl>The Anchor program, for fetching any account (hadal.program.account.config.fetch) or building an instruction the client has no call for.
providerAnchorProviderThe provider the program reads through, at commitment confirmed. Its wallet signs nothing.

One client serves one wallet. A desk that trades from several wallets makes one client for each.

One reading key serves a wallet everywhere: pass the same key to openBalance, to every order, deal and liquidity call, and to every read. A sealed value read with another key decodes to meaningless numbers, not to an error.

Actions

Action

Every call that changes something returns an Action, or a promise of one.

FieldTypeMeaning
instructionsTransactionInstruction[]The instructions of one transaction, in order. The wallet at owner signs it and pays its fee.
computationBN | undefinedThe offset of the computation the transaction queues. Absent when the call queues none. Follow it with awaitComputation.
accountPublicKey | undefinedThe account the action creates or acts on: the order, the deal, the balance or the market.

Building an action sends nothing. Three steps complete it:

  1. Send. In Node, sendWithKeypairs signs and sends. In a browser, compile the instructions into a transaction, have the wallet sign it and send it, or relay it through POST /v1/transactions.
  2. Follow. When computation is set, the transaction only queued the work. awaitComputation resolves when the cluster's result has been written by the program's callback, and throws when the result was refused or did not arrive in time.
  3. Read. The result is sealed. Read it with balance, order or deal.
ts
import { ComputeBudgetProgram, TransactionMessage, VersionedTransaction } from '@solana/web3.js'

const action = await hadal.deposit({ market, side: 'quote', amount: 50_000_000_000n })

const { blockhash } = await connection.getLatestBlockhash('confirmed')
const message = new TransactionMessage({
  payerKey: hadal.owner,
  recentBlockhash: blockhash,
  instructions: [ComputeBudgetProgram.setComputeUnitLimit({ units: 400_000 }), ...action.instructions],
}).compileToV0Message()
const signed = await wallet.signTransaction(new VersionedTransaction(message))
await connection.sendTransaction(signed)

if (action.computation) await hadal.awaitComputation(action.computation)
const ledger = await hadal.balance(market, key)

Calls that queue a computation

CallCircuitcomputation
createMarket (its open action), openPoolinit_marketAlways
depositdepositAlways
withdrawwithdrawAlways
swap, darkOrdernone: the order waits in the market's queueNever
collect, cancelsettle_slotWhen the order is resting
addLiquidityadd_liquidityAlways
removeLiquidityremove_liquidityAlways
openDealopen_dealAlways
takeDealtake_dealAlways
cancelDealsettle_dealAlways
processOrderprocess_orderWhen the order at the head is run and not closed by the transaction itself
soundsoundAlways
openBalance, reclaim, releaseMarket, releaseDeal, payFeesnoneNever

What each circuit computes and reveals is in Circuits. The lifecycle of a computation is in Arcium. What a queued computation costs its payer is in Limits.

Errors every queued call can meet

Error names on this page are the program's. Each is defined with its code in the program reference.

One computation at a time runs on a sealed balance, on a market's book and on a deal. A call that queues a computation on an account that still has one in flight is refused with Busy. Wait for the computation in flight, then send again. A computation that expired keeps its account locked until the account is released: a balance with reclaim, a market's book with releaseMarket, a deal with releaseDeal.

A callback whose output the cluster's signature does not verify fails with AbortedComputation, and a callback for a computation that is not the one in flight fails with StaleComputation. Neither changes any state, and awaitComputation then throws.

Setup and the reading key

How the key is derived, what it seals and what it reads is told in The reading key. This section is the calls.

deriveReadingKey

deriveReadingKey(signMessage: (message: Uint8Array) => Promise<Uint8Array>): Promise<ReadingKey>

ParameterTypeMeaning
signMessage(message: Uint8Array) => Promise<Uint8Array>Signs the bytes it is given with the wallet's Ed25519 key and returns the 64-byte signature. A browser wallet's signMessage fits.

Calls signMessage once with READING_KEY_MESSAGE as UTF-8 bytes and returns the ReadingKey derived from the signature. Sends nothing on chain. Rejects with whatever signMessage rejects with, for example when the person declines the signature.

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

const key = await deriveReadingKey((message) => browserWallet.signMessage(message))

readingKeyFromSecret

readingKeyFromSecret(secretKey: Uint8Array): ReadingKey

Builds the key pair from a 32-byte x25519 secret key. deriveReadingKey calls it with the SHA-256 of the signature.

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

const key = readingKeyFromSecret(storedSecret)

READING_KEY_MESSAGE

READING_KEY_MESSAGE: string

The message deriveReadingKey has the wallet sign. Its text is on The reading key.

ReadingKey

FieldTypeMeaning
secretKeyUint8ArrayThe x25519 secret key, 32 bytes. It stays on the device.
publicKeyUint8ArrayThe x25519 public key, 32 bytes. Calls send it on chain beside the ciphertext.

mxePublicKey

hadal.mxePublicKey(): Promise<Uint8Array>

Returns the cluster's x25519 public key for the Hadal program, read from chain once and kept by the client. Throws The cluster has not published its key yet when the program's Arcium account holds no key.

sealer

hadal.sealer(key: ReadingKey): Promise<Sealer>

Returns the Sealer for a reading key, made from the key and mxePublicKey(). The client keeps one sealer for each key it is given. Every call that takes key uses this sealer.

ts
const sealer = await hadal.sealer(key)

Balances

openBalance

hadal.openBalance(market: PublicKey, key: ReadingKey): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account.
keyReadingKeyThe wallet's reading key. The balance is sealed to it from now on. Only its public half is sent.

Returns an action with no computation. account is the balance's address, the same as balanceAddress(market, hadal.owner).

On chain: open_balance. It creates the owner's Balance account in the market and stores the key's public half. The balance holds nothing until a first deposit lands.

Fails when the balance already exists: a wallet has one balance for each market, and the account cannot be created twice.

ts
const action = await hadal.openBalance(market, key)
await sendWithKeypairs(connection, action.instructions, [keypair])

deposit

hadal.deposit(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account.
side'base' | 'quote'Which of the market's two tokens to deposit.
amountbigintAtoms to deposit. Public.

Returns an action with a computation. account is the balance.

On chain: deposit. The tokens move at once from the owner's associated token account to the market's vault. The deposit computation adds the amount to the sealed balance, and the receipt in the ledger then holds the credit: filled for base, quote for quote.

Fails with InvalidAmount when amount is 0, and with Busy. The transaction also fails when the balance has not been opened or the token account holds less than amount. A deposit whose computation expires is refunded by reclaim.

ts
const action = await hadal.deposit({ market, side: 'quote', amount: 50_000_000_000n })
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)

withdraw

hadal.withdraw(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account.
side'base' | 'quote'Which token to withdraw.
amountbigintAtoms to withdraw. Public.

Returns an action with a computation and two instructions: the first creates the owner's associated token account when it does not exist. account is the balance.

On chain: withdraw. The withdraw computation checks that the sealed balance covers the amount. When it does, the callback pays the tokens from the vault to the owner's token account. When it does not, the withdrawal is refused and nothing moves. The chain shows only paid or refused. For the owner, receipt.ok in the ledger is true when paid and false when refused.

Fails with InvalidAmount when amount is 0, EmptyBalance when no deposit has landed in the balance yet, and Busy.

ts
const action = await hadal.withdraw({ market, side: 'base', amount: 15_000_000_000n })
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)
const paid = (await hadal.balance(market, key))!.receipt.ok

reclaim

hadal.reclaim(params: { market: PublicKey; owner?: PublicKey }): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account.
ownerPublicKeyWhose balance to release. Optional. Default: the client's owner. Anyone may send it for any balance.

Returns an action with no computation. account is the balance.

On chain: reclaim. It releases a balance whose computation expired, so the balance accepts calls again. A deposit that was waiting on that computation is paid back from the vault to the balance owner's token account, and a withdrawal that was waiting is dropped.

Fails with NothingPending when the balance has no computation in flight, and ComputationStillLive until the release window has passed since the computation was queued. The window is in Limits. Rejects when the balance does not exist.

ts
const action = await hadal.reclaim({ market })
await sendWithKeypairs(connection, action.instructions, [keypair])

Orders

A sealed order is placed in the market's queue and processed there in arrival order. The mechanism is in Sealed orders, and the rates an order pays in Fees.

swap

hadal.swap(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account. Public.
side'buy' | 'sell'Buy or sell the base token. Sealed.
sizebigintBase atoms to trade. Sealed.
limitbigintThe worst price the order accepts, from priceOf. Sealed.
keyReadingKeyThe reading key that seals the terms.

Returns an action with no computation. account is the order's address. The order is pending until it is processed in the market's queue, then closed.

On chain: place_order with kind 0. The chain shows that the wallet placed a swap in this market. When the order is processed it crosses resting orders at the pool's mid, then sweeps the curve for all of the remainder if the average price of the sweep is within limit. What neither crosses nor sweeps stays in the sealed balance.

The order is void, with receipt.ok false and nothing moved, when the sealed balance does not cover its worst case: for a buy, size at limit plus the fee, in quote; for a sell, size in base. It is also void when size or limit is 0 or an amount it would move does not fit 64 bits.

An order is closed without a computation and without a receipt when its owner's balance has another computation in flight at the moment the queue reaches it. Wait for that computation, then place the order again.

Fails with MarketNotReady before the market's pool is open and EmptyBalance when no deposit has landed in the balance yet. The order's address comes from the queue's tail at the time of the call: when another order is placed first, the transaction fails and the call is made again.

ts
const action = await hadal.swap({
  market,
  side: 'buy',
  size: 15_000_000_000n,
  limit: priceOf(110_000_000n, 1_000_000_000n),
  key,
})
await sendWithKeypairs(connection, action.instructions, [keypair])
const { status, receipt } = await hadal.order(action.account!, key)

darkOrder

hadal.darkOrder(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account. Public.
side'buy' | 'sell'Buy or sell the base token. Sealed.
sizebigintBase atoms to trade. Sealed.
limitbigintThe worst price the order accepts, from priceOf. It fills at the pool’s mid while the mid is within it. Sealed.
keyReadingKeyThe reading key that seals the terms.
expirynumberUnix seconds after which the order no longer rests and anyone may cancel it. In the future, and at most MAX_REST_SECONDS from now. Optional. Default: 60 seconds less than the longest a dark order may rest. Public.

Returns an action with no computation. account is the order's address. The order is pending until it is processed, then resting when part of it waits in the book, or closed when nothing of it does.

On chain: place_order with kind 1. When the order is processed it crosses resting orders at the pool's mid and never touches the curve. What is left takes a slot in the sealed book and locks its funds there: receipt.rested is the size that waits. The chain shows whether the order rests. While it rests, other orders cross it and its proceeds wait in the book until collect or cancel. An order that crossed in full on arrival, or is void, takes no slot and is closed.

The order is void under the same rule as a swap. It is closed without a computation and without a receipt when the book has no free slot, when its expiry has passed before the queue reaches it, and when its owner's balance has another computation in flight at that moment. The number of slots is in Limits.

Fails as swap does, and with InvalidExpiry when expiry is not in the future or is more than MAX_REST_SECONDS ahead.

ts
const action = await hadal.darkOrder({
  market,
  side: 'sell',
  size: 10_000_000_000n,
  limit: priceOf(95_000_000n, 1_000_000_000n),
  key,
  expiry: Math.floor(Date.now() / 1000) + 3600,
})
await sendWithKeypairs(connection, action.instructions, [keypair])

collect

hadal.collect(order: PublicKey): Promise<Action>

ParameterTypeMeaning
orderPublicKeyThe resting order's address.

Returns an action with a computation. account is the order. Throws Only a resting order has proceeds to collect when the order is pending or closed, and rejects when no order exists at the address.

On chain: collect, which queues settle_slot. The order's proceeds move from the book to the owner's sealed balance and the order keeps resting. The order's receipt then holds the credit: filled for base, quote for quote.

Fails with NotOwner when the signer is not the order's owner, NotResting when the order stopped resting after the action was built, and Busy.

ts
const action = await hadal.collect(order)
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)

cancel

hadal.cancel(order: PublicKey): Promise<Action>

ParameterTypeMeaning
orderPublicKeyThe order's address.

Returns an action whose computation is set when the order is resting. account is the order. Throws The order is closed when it already is, and rejects when no order exists at the address.

On chain: cancel_order. A pending order closes at once, with no computation, and is skipped when the queue reaches it. A resting order queues settle_slot: what it still has locked and its proceeds return to the owner's sealed balance, the slot is freed and the order closes. The receipt holds what was credited.

Fails with NotOwner when the signer is not the owner, unless the order is resting and its expiry has passed, NotResting when the order closed after the action was built, and Busy. A pending order is also refused with Busy while the market's book has a computation in flight, since that computation may be the order itself: send again once it lands.

ts
const action = await hadal.cancel(order)
await sendWithKeypairs(connection, action.instructions, [keypair])
if (action.computation) await hadal.awaitComputation(action.computation)

Deals

A deal is told in Deals: what trades, at which price, and what each side sees.

openDeal

hadal.openDeal(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account. Public.
side'buy' | 'sell'The maker's side. Public.
sizebigintBase atoms on offer. Sealed.
minSizebigintThe smallest fill the maker accepts, in base atoms, at most size. Sealed.
limitbigintThe maker's limit, from priceOf. Sealed.
takerPublicKey | nullThe one wallet that may answer, or null for anyone holding the link. Public.
attemptsnumberAnswers each taker gets, 1 to 255. Optional. Default: 3. Public.
expirynumberUnix seconds after which the deal takes no answer. Public.
keyReadingKeyThe reading key that seals the terms.
idbigint | stringThe deal's id, an unsigned 64-bit integer unique for the maker. Optional. Default: a random one.

Returns an action with a computation. account is the deal's address, the same as dealAddress(hadal.owner, id). The address is the deal's link: it is what the counterparty needs in order to answer.

On chain: open_deal. The deal is opening until the open_deal computation lands. The computation moves the maker's escrow out of the sealed balance: size in base for a sell, size at limit plus the fee in quote for a buy. The deal is then open. When the balance does not cover the escrow, or size or limit is 0, or minSize is above size, the deal is void and nothing moved. The chain shows the deal's side and which of the two happened.

Fails with MarketNotReady, InvalidExpiry when expiry is not in the future, EmptyBalance, InvalidCounterparty when taker is the maker, and Busy. The transaction also fails when the maker already has a deal with this id.

ts
const action = await hadal.openDeal({
  market,
  side: 'sell',
  size: 20_000_000_000n,
  minSize: 5_000_000_000n,
  limit: priceOf(98_000_000n, 1_000_000_000n),
  taker: counterparty,
  expiry: Math.floor(Date.now() / 1000) + 3600,
  key,
})
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)
const { status, side } = await hadal.deal(action.account!, key)

takeDeal

hadal.takeDeal(params): Promise<Action>

ParameterTypeMeaning
dealPublicKeyThe deal's address. Public.
sizebigintBase atoms the taker will trade, on the side opposite the maker's. Sealed.
limitbigintThe taker's limit, from priceOf. Sealed.
keyReadingKeyThe taker's reading key.

Returns an action with a computation. account is the deal.

On chain: take_deal. The answer uses one of the taker's attempts when the transaction lands. The take_deal computation trades when the two limits cross, the fill meets the maker's minimum and the taker's sealed balance covers it. The chain shows whether the answer traded and whether the deal is now filled. The taker reads the result in their ledger: receipt.ok true with filled, quote and fee when it traded, receipt.ok false when it did not. A deal that is filled becomes done. Otherwise it stays open for what is left.

Fails with DealNotOpen when the deal's status is not open, DealExpired after its expiry, InvalidCounterparty when the taker is the maker, NotCounterparty when the deal names another wallet, EmptyBalance when no deposit has landed in the taker's balance in the deal's market, OutOfAttempts when the taker has used every attempt, and Busy.

ts
const action = await hadal.takeDeal({ deal, size: 20_000_000_000n, limit: priceOf(102_000_000n, 1_000_000_000n), key })
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)
const { receipt } = (await hadal.balance(market, key))!

cancelDeal

hadal.cancelDeal(deal: PublicKey): Promise<Action>

ParameterTypeMeaning
dealPublicKeyThe deal's address.

Returns an action with a computation. account is the deal.

On chain: cancel_deal, which queues settle_deal. The escrow that is left and the deal's proceeds move to the maker's sealed balance. The deal ends cancelled when the maker closes an open deal, expired when it is closed after its expiry, and stays done when it was filled. The maker cancels an open deal. Anyone may close a deal that is filled or past its expiry, and the funds still go to the maker.

Fails with NotOwner when the deal is open, not expired, and the signer is not the maker, DealNotOpen when the deal is opening, void or already settled, and Busy.

ts
const action = await hadal.cancelDeal(deal)
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)

releaseDeal

hadal.releaseDeal(deal: PublicKey): Promise<Action>

ParameterTypeMeaning
dealPublicKeyThe deal's address. Anyone may send it for any deal.

Returns an action with no computation. account is the deal.

On chain: release_deal. It releases a deal whose computation expired, so the deal accepts calls again. A deal that was still opening becomes void: its escrow was never taken.

Fails with NothingPending when the deal has no computation in flight, and ComputationStillLive until the release window has passed. The balance that shared the computation is released with reclaim.

ts
const action = await hadal.releaseDeal(deal)
await sendWithKeypairs(connection, action.instructions, [keypair])

Liquidity and markets

The pool, its shares and what they earn are told in Liquidity.

createMarket

hadal.createMarket(params): Promise<{ market: PublicKey; create: Action; open: Action }>

ParameterTypeMeaning
baseMintPublicKeyThe mint of the base token.
quoteMintPublicKeyThe mint of the quote token. Not the base mint.
baseAmountbigintBase atoms of the pool's first liquidity. Public.
quoteAmountbigintQuote atoms of the pool's first liquidity. Public. With baseAmount it sets the first price.
keyReadingKeyThe creator's reading key.

Returns the market's address and two actions, sent as two transactions in this order:

ActionInstructionsDoes
createcreate_market, open_balanceCreates the market's account, its two vaults and the creator's balance. No computation.
openfund_market, open_poolMoves both amounts from the creator's associated token accounts to the vaults, then queues init_market. When it lands the market is ready and the creator's sealed balance holds the first shares. When that computation expires, openPool queues it again.

The mints a market accepts are listed in Supported mints.

Throws Mint not found when either mint does not exist. Fails with SameMint, UnsupportedMint, InvalidAmount when either amount is 0, PriceOutOfRange when the first price the two amounts set is 0 or does not fit 64 bits, MarketAlreadyOpen when the pool is already open, and Busy. The create transaction also fails when a market for this pair of mints, in this order, already exists.

ts
const created = await hadal.createMarket({
  baseMint,
  quoteMint,
  baseAmount: 1_000_000_000_000n,
  quoteAmount: 100_000_000_000n,
  key,
})
await sendWithKeypairs(connection, created.create.instructions, [keypair])
await sendWithKeypairs(connection, created.open.instructions, [keypair])
await hadal.awaitComputation(created.open.computation!)
const { ready } = await hadal.market(created.market)

openPool

hadal.openPool(market: PublicKey, computation?: BN): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account, already funded.
computationBNThe computation offset to queue under. Optional. Default: a random one.

Returns an action with a computation. account is the market.

On chain: open_pool, which queues init_market. createMarket puts it in its open action. Sent on its own, it opens a funded market whose first opening expired, after the market and the creator's balance have been released.

Fails with NotFunded when the vaults hold no first liquidity, MarketAlreadyOpen, NotOwner when the signer is not the market's creator and the market has not been left unopened long enough to be claimed, and Busy. The transaction also fails when the signer has no balance opened in the market.

ts
const action = await hadal.openPool(market)
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)

releaseMarket

hadal.releaseMarket(market: PublicKey): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account. Anyone may send it for any market.

Returns an action with no computation. account is the market.

On chain: release_market. It releases a market's book whose computation expired, so orders, liquidity, the closing of deals and soundings run again.

Fails with NothingPending when the book has no computation in flight, and ComputationStillLive until the release window has passed.

ts
const action = await hadal.releaseMarket(market)
await sendWithKeypairs(connection, action.instructions, [keypair])

addLiquidity

hadal.addLiquidity(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account. Public.
basebigintThe most base atoms to add from the sealed balance. Sealed.
quotebigintThe most quote atoms to add from the sealed balance. Sealed.
keyReadingKeyThe reading key that seals the amounts.

Returns an action with a computation. account is the balance.

On chain: add_liquidity. The computation takes the two amounts in the pool's ratio, as much as both allow, from the sealed balance and adds shares to it. The receipt holds what was used and minted: filled for base, quote for quote, swept for the shares. receipt.ok is false and nothing moved when the amounts mint no share or the balance does not cover them.

Fails with MarketNotReady, EmptyBalance when no deposit has landed in the balance yet, and Busy.

ts
const action = await hadal.addLiquidity({ market, base: 5_000_000_000n, quote: 600_000_000n, key })
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)
const { shares } = (await hadal.balance(market, key))!

removeLiquidity

hadal.removeLiquidity(params): Promise<Action>

ParameterTypeMeaning
marketPublicKeyThe market's account. Public.
sharesbigintShares to give back. Sealed.
keyReadingKeyThe reading key that seals the amount.

Returns an action with a computation. account is the balance.

On chain: remove_liquidity. The computation turns the shares into their part of both reserves and adds it to the sealed balance. The receipt holds the credit: filled for base, quote for quote, swept for the shares given back. receipt.ok is false and nothing moved when shares is 0, more than the balance holds, or every share of the pool.

Fails with MarketNotReady, EmptyBalance when no deposit has landed in the balance yet, and Busy.

ts
const action = await hadal.removeLiquidity({ market, shares, key })
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)

Reading

Reads send nothing. Each one fetches an account and opens its sealed part on the device.

balance

hadal.balance(market: PublicKey, key: ReadingKey, owner?: PublicKey): Promise<Ledger | null>

ParameterTypeMeaning
marketPublicKeyThe market's account.
keyReadingKeyThe wallet's reading key, the one the balance was opened with.
ownerPublicKeyWhose balance to read. Optional. Default: the client's owner.

Returns the Ledger: base, quote, shares and the receipt of the balance's last action. Returns null when the balance does not exist or no computation has written to it yet. A key other than the one the balance is sealed to opens to meaningless numbers, not an error.

ts
const ledger = await hadal.balance(market, key)
if (ledger) console.log(ledger.base, ledger.quote, ledger.shares, ledger.receipt.ok)

order

hadal.order(order: PublicKey, key?: ReadingKey)

ParameterTypeMeaning
orderPublicKeyThe order's address.
keyReadingKeyThe owner's reading key. Optional. Without it only the public part is returned.

Returns an object with three fields:

FieldTypeMeaning
accountOrder accountThe account as stored: terms, key, nonce, market, owner, seq, kind (0 swap, 1 dark), status, slot, closing, expiry, placedAt, receipt, receiptNonce, bump.
status'pending' | 'resting' | 'closed'The order's public status, one of ORDER_STATUS.
receiptLedger | nullThe owner's ledger as the order's last computation left it. Its receipt field is the order's receipt. null without a key, and until a computation has written to the order.

An order closed without a computation has no receipt: receipt is null and status is closed. Rejects when no order exists at the address.

ts
const { status, receipt } = await hadal.order(order, key)
if (receipt?.receipt.ok) console.log(status, receipt.receipt.filled, receipt.receipt.rested)

deal

hadal.deal(deal: PublicKey, key?: ReadingKey)

ParameterTypeMeaning
dealPublicKeyThe deal's address.
keyReadingKeyThe maker's reading key. Optional.

Returns an object with four fields:

FieldTypeMeaning
accountDeal accountThe account as stored: state, stateNonce, terms, termsKey, termsNonce, market, maker, taker (the default address when anyone with the link may answer), buy, id, attempts, status, expiry, createdAt, settled, closing, pending, pendingSince, bump.
statusstringOne of DEAL_STATUS.
side'buy' | 'sell'The maker's side. Public: anyone reads it.
termsobject | nullThe maker's terms: side, size, minSize and limit. Present only when a key is passed and the client's owner is the deal's maker.

Rejects when no deal exists at the address.

ts
const { status, side, terms } = await hadal.deal(deal, key)
if (terms) console.log(status, side, terms.size, terms.minSize, terms.limit)

market

hadal.market(market: PublicKey)

Returns the market's account as stored. Its public fields:

FieldTypeMeaning
baseMint, quoteMintPublicKeyThe two mints.
baseVault, quoteVaultPublicKeyThe two vaults.
baseTokenProgram, quoteTokenProgramPublicKeyThe token program of each mint.
baseDecimals, quoteDecimalsnumberThe decimals of each mint.
creator, createdSlotPublicKey, BNThe wallet that created the market, or claimed it unopened, and the slot it was created at.
readybooleanTrue once the pool is open.
pending, pendingSincePublicKey, BNThe computation in flight on the book, the default address when none, and the slot it was queued at.
head, tailBNThe order queue: the sequence of the next order to process and of the next order to be placed.
slotsBN[]For each book slot, the sequence plus 1 of the dark order resting there, 0 when free.
seedBase, seedQuote, firstPriceBNThe creator's first liquidity and the price it set.
lastSoundSlot, lastPrice, lastCrossed, lastSweptBNThe last sounding: its slot, the price, and the crossed and swept volume it revealed.
soundingsBNHow many soundings have been taken.
feesOwedBase, feesOwedQuoteBNProtocol fees soundings have revealed and payFees has not yet paid.
book, bookNoncenumber[][], BNThe sealed book. Only the cluster opens it.

Rejects when no market exists at the address.

ts
const m = await hadal.market(market)
const queued = BigInt(m.tail.toString()) - BigInt(m.head.toString())

Sealing and decoding

Sealer class

new Sealer(key: ReadingKey, mxePublicKey: Uint8Array)

Seals values to the cluster under a reading key and opens what is sealed to that key. hadal.sealer(key) makes one with the cluster's key already fetched. The cipher is told in The reading key.

MemberSignatureMeaning
keyReadingKeyThe key the sealer was made with.
seal(values: (bigint | number | boolean)[]) => { ciphertexts: number[][]; nonce: Uint8Array }Encrypts each value into one 32-byte ciphertext under a fresh random nonce. A boolean is sealed as 1 or 0.
open(sealed: Sealed) => bigint[]Decrypts ciphertexts sealed to this key, one value for each ciphertext.
ledger(sealed: Sealed) => LedgerOpens the four ciphertexts of a sealed ledger and decodes them: a balance, the receipt stored on an order, a ledger carried by an event, or one the API serves.
ts
const sealer = await hadal.sealer(key)
const { account } = await hadal.order(order)
const [buy, size, limit] = sealer.open({
  ciphertexts: account.terms,
  nonce: nonceFromBigInt(BigInt(account.nonce.toString())),
})

The first three values of an order's terms are its side, size and limit. The two that follow are the owner's address.

Reading the receipts the API serves with ledger is shown in the script guide.

Sealed input shapes

Every sealed input ends with the address of the wallet it was sealed for, as the two values of ownerLimbs. The circuit compares it with the account that acts, so ciphertext copied from another wallet's order or deal is void and tells the copier nothing. The calls build these shapes themselves:

CallCiphertextsValues sealed, in order
swap, darkOrder5buy (1 or 0), size, limit, owner low, owner high.
openDeal5size, minSize, limit, owner low, owner high. The side is public.
takeDeal4size, limit, owner low, owner high.
addLiquidity4base, quote, owner low, owner high.
removeLiquidity3shares, owner low, owner high.

ownerLimbs

ownerLimbs(owner: PublicKey): [bigint, bigint]

Returns an address as two 128-bit integers: bytes 0 to 15 and bytes 16 to 31, each read little-endian.

ts
const [low, high] = ownerLimbs(hadal.owner)

Sealed

Ciphertexts with the nonce they were sealed under, as accounts, events and the API carry them.

FieldTypeMeaning
ciphertexts(number[] | Uint8Array)[]Each ciphertext is 32 bytes.
nonceUint8Array16 bytes.

Ledger

A sealed balance as its owner reads it.

FieldTypeMeaning
basebigintBase atoms held.
quotebigintQuote atoms held.
sharesbigintShares of the market's pool held.
receiptReceiptThe receipt of the last action on the balance.

Receipt

The result of one action. The same seven fields carry every action's result:

FieldTypeMeaning
okbooleanFalse when the action was void and nothing moved: the balance did not cover it, a withdrawal was refused, a deal answer did not trade, an amount did not fit 64 bits, or the input was sealed for another address.
filledbigintAn order or a deal answer: base atoms filled. A deposit, collect, cancel or liquidity change: base atoms credited or used.
quotebigintAn order or a deal answer: quote atoms paid or received for the fill. A deposit, collect, cancel or liquidity change: quote atoms credited or used.
crossedbigintBase atoms that crossed in the book. For a deal answer, the fill.
sweptbigintAn order: base atoms swept from the curve. A liquidity change: the shares minted or given back.
restedbigintA dark order: base atoms left resting in the book.
feebigintThe fee paid, in quote atoms.

A withdrawal and the opening of a deal set only ok.

randomNonce

randomNonce(): Uint8Array

Returns 16 random bytes. seal calls it for every sealing.

nonceToBigInt and nonceFromBigInt

nonceToBigInt(nonce: Uint8Array): bigint

nonceFromBigInt(value: bigint): Uint8Array

Convert a 16-byte nonce to and from the little-endian integer the program stores: nonce, receiptNonce and termsNonce on accounts are this integer.

ts
const nonce = randomNonce()
const same = nonceFromBigInt(nonceToBigInt(nonce))

unpackU64

unpackU64(elements: bigint[], count: number): bigint[]

Splits opened values into count unsigned 64-bit integers, three to a value, lowest bits first. It is the packing the circuits use for a ledger, and ledger calls it with a count of 10.

Sending

sendWithKeypairs

sendWithKeypairs(connection, instructions, signers, computeUnits?): Promise<string>

ParameterTypeMeaning
connectionConnectionThe RPC connection.
instructionsTransactionInstruction[]An action's instructions.
signersKeypair[]The keypairs that sign. The first pays the fee.
computeUnitsnumberThe compute unit limit set on the transaction. Optional. Default 400000.

For Node: builds one versioned transaction, signs it, sends it and polls its status. Resolves with the signature once the transaction is confirmed. A browser signs with its wallet instead.

Throws Transaction <signature> failed: <error> when the program refuses the transaction, with the error as the RPC reports it, and Transaction <signature> expired when the blockhash passes its last valid height before confirmation. A transaction refused in simulation rejects with the RPC's error before it is sent.

ts
const action = await hadal.openBalance(market, key)
const signature = await sendWithKeypairs(connection, action.instructions, [keypair])

awaitComputation

hadal.awaitComputation(computation: BN, timeoutMs?: number): Promise<string>

ParameterTypeMeaning
computationBNAn action's computation.
timeoutMsnumberHow long to wait, in milliseconds. Optional. Default 120000.

Polls the computation's account at commitment confirmed until the cluster has finished it, then looks for the program's callback among the transactions on that account. It ends one of three ways:

OutcomeResultMeaning
Landedresolves with a signatureThe callback's transaction. The program's accounts hold the result from then on.
Refusedthrows: Computation <offset> was refused: nothing changedThe cluster finished the computation and the program refused its output. The action is void and no state changed. The accounts it locked stay locked until they are released.
Not finishedthrows: Computation did not finalize within <timeoutMs>msThe time passed before the cluster finished.

What to do in each is in the script guide.

ts
const action = await hadal.deposit({ market, side: 'base', amount: 300_000_000_000n })
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!, 60_000)

randomOffset

randomOffset(): BN

Returns a random 64-bit computation offset. Every call that queues a computation draws one and returns it as computation.

Cranks anyone may send

These three instructions keep a market moving. Any wallet may send them, and the sender pays the transaction.

processOrder

hadal.processOrder(market: PublicKey): Promise<Action | null>

Returns null when the market's queue is empty. Otherwise returns an action for the order at the head of the queue, with account the order. computation is set when the order will be run. It is absent when the transaction itself closes the order, so nothing holds the queue: the order was cancelled while pending, 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.

On chain: process_order. It runs one order against the whole book.

Fails with ProtocolShareUnset until the venue has set the protocol's share, NotQueueHead when another sender processed the order first, and Busy while the market's book has a computation in flight.

ts
const action = await hadal.processOrder(market)
if (action) {
  await sendWithKeypairs(connection, action.instructions, [keypair])
  if (action.computation) await hadal.awaitComputation(action.computation)
}

sound

hadal.sound(market: PublicKey): Promise<Action>

Returns an action with a computation. account is the market.

On chain: sound. The computation reveals the pool's price and the interval's crossed volume, swept volume and protocol fees, and the market's account records them. See Soundings.

Fails with MarketNotReady, TooEarly until the sounding interval has passed since the last sounding, and Busy.

ts
const action = await hadal.sound(market)
await sendWithKeypairs(connection, action.instructions, [keypair])
await hadal.awaitComputation(action.computation!)
const { lastPrice, lastCrossed, lastSwept } = await hadal.market(market)

payFees

hadal.payFees(market: PublicKey): Promise<Action>

Returns an action with no computation and three instructions: the first two create the fee recipient's associated token accounts for both mints when they do not exist. account is the market.

On chain: pay_fees. It pays the protocol fees that soundings have revealed, feesOwedBase and feesOwedQuote on the market, from the vaults to the fee recipient's token accounts.

ts
const action = await hadal.payFees(market)
await sendWithKeypairs(connection, action.instructions, [keypair])

Addresses, prices and constants

priceOf

priceOf(quote: bigint, base: bigint): bigint

Returns the price at which quote atoms pay for base atoms, as the program reads prices: quote * PRICE_SCALE / base, rounded down. The unit is defined in Units.

ts
// 110 of a 6-decimal quote token for 1 of a 9-decimal base token
const limit = priceOf(110_000_000n, 1_000_000_000n)

Address helpers

Each returns the address of one of the program's accounts. programId is optional on all of them and defaults to PROGRAM_ID. The seeds are in the program reference.

HelperArgumentsReturns
configAddress(programId?)The venue's Config account.
marketAddress(baseMint, quoteMint, programId?)The market of two mints.
vaultAddress(market, mint, programId?)The market's vault for one of its mints.
balanceAddress(market, owner, programId?)A wallet's sealed balance in a market.
orderAddress(market, seq, programId?)The order with this sequence number in the market's queue.
dealAddress(maker, id, programId?)A maker's deal with this id.
attemptsAddress(deal, taker, programId?)The count of attempts a taker has used on a deal.
ts
const market = marketAddress(baseMint, quoteMint)
const balance = balanceAddress(market, hadal.owner)

Constants

ConstantTypeValue
PROGRAM_IDPublicKeyThe address of the Hadal program, taken from the IDL.
PRICE_SCALEbigint2^32, the factor of every price and limit.
MAX_REST_SECONDSnumberThe longest a dark order may rest, in seconds: 86400, one day.
CIRCUITSCircuit[]The names of the eleven circuits: init_market, deposit, withdraw, process_order, settle_slot, add_liquidity, remove_liquidity, open_deal, take_deal, settle_deal, sound.
ORDER_STATUSreadonly string[]pending, resting, closed: an order account's status number is the index.
DEAL_STATUSreadonly string[]opening, open, done, cancelled, expired, void: a deal account's status number is the index.
IDLobjectThe program's Anchor IDL.
Deal statusMeaning
openingThe computation that takes the escrow has not landed.
openThe escrow is in the deal and it takes answers.
doneThe whole size traded.
cancelledThe maker closed it while it was open.
expiredIt was closed after its expiry.
voidThe escrow was not taken, or the opening expired and the deal was released. Nothing moved.

The three order statuses are told in GET /v1/orders/:id.

Types

TypeDefinitionMeaning
Side'buy' | 'sell'The side of an order or a deal, in the base token.
TokenSide'base' | 'quote'One of a market's two tokens.
Circuitstring unionOne of the names in CIRCUITS.
HadalOptionsobjectThe options of the client, above.
ActionobjectWhat a call returns, above.
ReadingKey, Sealed, Ledger, ReceiptobjectAbove.
HadalIdltypeThe type of the program's IDL, for Program<HadalIdl>.

Venue setup

initialize, setConfig and initCircuit build the instructions only the venue's authority can send. They are listed in the program reference.