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
Guides

Trade from a script with the SDK

One Node script, from a keypair to a withdrawal, through every flow of Hadal, with the states each step can end in.

This guide builds one Node script for a desk or a bot. It opens a sealed balance, deposits, swaps, rests a dark order, opens and answers a deal, supplies liquidity and withdraws. The code blocks, in order, are the whole script. Each call is documented in full in the SDK reference.

What the script needs

InputRead fromMeaning
RPC_URLenvironmentA Solana RPC endpoint.
KEYPAIRenvironmentThe path of the wallet's keypair file: a JSON array of 64 bytes. The wallet pays every transaction in SOL and holds the market's two tokens in its associated token accounts.
MARKETenvironmentThe market's account address: marketAccount in GET /v1/markets/:market/config, or marketAddress(baseMint, quoteMint) in the SDK.
ARCIUM_CLUSTER_OFFSETenvironmentThe Arcium cluster the venue computes on: 2026 on mainnet.
HADAL_APIenvironmentThe base URL of the HTTP API. Used only for the receipts history.

Amounts in the script are whole tokens turned into atoms with the market's decimals, and prices are built with priceOf. Both units are defined in Units.

Construct the client

The client takes the wallet's public key, never its secret. The keypair signs in run, the one helper every step below uses: it sends an action's instructions and, when the action queued a computation, waits for the result to be on chain.

ts
import { createPrivateKey, sign } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { Connection, Keypair, PublicKey } from '@solana/web3.js'
import { HadalClient, balanceAddress, deriveReadingKey, priceOf, sendWithKeypairs, type Action } from '@hadal/sdk'

const connection = new Connection(process.env.RPC_URL!, 'confirmed')
const keypair = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(process.env.KEYPAIR!, 'utf8'))))
const market = new PublicKey(process.env.MARKET!)

const hadal = new HadalClient({
  connection,
  owner: keypair.publicKey,
  clusterOffset: Number(process.env.ARCIUM_CLUSTER_OFFSET),
})

async function run(action: Action): Promise<string> {
  const signature = await sendWithKeypairs(connection, action.instructions, [keypair])
  if (action.computation) await hadal.awaitComputation(action.computation)
  return signature
}

Derive the reading key

The reading key comes from the wallet's signature over one fixed message, so the script derives the same key the app derives for this wallet. deriveReadingKey takes a function that signs bytes. Here Node's own crypto signs with the keypair's Ed25519 key.

ts
const signer = createPrivateKey({
  format: 'jwk',
  key: {
    kty: 'OKP',
    crv: 'Ed25519',
    d: Buffer.from(keypair.secretKey.subarray(0, 32)).toString('base64url'),
    x: Buffer.from(keypair.publicKey.toBytes()).toString('base64url'),
  },
})
const key = await deriveReadingKey(async (message) => new Uint8Array(sign(null, message, signer)))

Nothing is sent. One reading key serves the wallet everywhere: the script passes this same key to every call below. The derivation and what the key opens are told in The reading key.

Open a balance and deposit

A wallet has one sealed balance for each market, opened once. A deposit moves tokens from the wallet to the market's vault at once, and the sealed balance takes the amount when the computation lands.

ts
const m = await hadal.market(market)
const base = (tokens: number) => BigInt(Math.round(tokens * 10 ** m.baseDecimals))
const quote = (tokens: number) => BigInt(Math.round(tokens * 10 ** m.quoteDecimals))
const price = (quotePerBase: number) => priceOf(quote(quotePerBase), base(1))

if (!(await connection.getAccountInfo(balanceAddress(market, keypair.publicKey)))) {
  await run(await hadal.openBalance(market, key))
}
await run(await hadal.deposit({ market, side: 'quote', amount: quote(50_000) }))
await run(await hadal.deposit({ market, side: 'base', amount: base(300) }))

const held = await hadal.balance(market, key)
console.log('balance', held?.base, held?.quote, held?.shares)
StateWhat to do
Landedrun returned. balance shows the amount added, and its receipt holds the credit.
Refusedrun threw before anything moved: the wallet holds less than the amount, the amount is 0, or the balance still has a computation in flight (Busy). Fix the cause and send again.
ExpiredThe tokens are in the vault and the computation never ran. See Following a computation below: reclaim pays the deposit back to the wallet.

Deposits are made one after the other: a balance runs one computation at a time, and run returns only when the first has landed.

Swap and read the receipt

A swap is placed in the market's queue. Placing it queues no computation of its own: the order is processed in the queue, in arrival order, and that is when it trades. The script waits by reading the order until it is no longer pending.

ts
async function processed(order: PublicKey) {
  for (;;) {
    const state = await hadal.order(order, key)
    if (state.status !== 'pending') return state
    await new Promise((resolve) => setTimeout(resolve, 1000))
  }
}

const swap = await hadal.swap({ market, side: 'buy', size: base(15), limit: price(110), key })
await run(swap)
const swapped = await processed(swap.account!)

const receipt = swapped.receipt?.receipt
if (receipt?.ok) {
  console.log('filled', receipt.filled, 'crossed', receipt.crossed, 'swept', receipt.swept)
  console.log('paid', receipt.quote, 'fee', receipt.fee)
}

The order's receipt is your ledger as the order left it: swapped.receipt holds the balances after the trade, and swapped.receipt.receipt the result.

StateHow it readsWhat to do
Pendingstatus 'pending'The order waits in the queue. Keep reading. cancel closes it at once, and is refused with Busy while the market is computing: send it again.
Filledok true, filled equals sizecrossed traded in the book at the pool’s mid and swept traded on the curve. quote is what was paid or received, fee the fee in quote.
Returnedok true, filled below sizeThe curve could not fill the remainder inside the limit, so that part stayed in the sealed balance. Place it again with another limit, or as a dark order.
Voidok falseThe sealed balance did not cover the order’s worst case and nothing moved. A buy needs size at the limit plus the fee, in quote. Deposit, or lower the size or the limit.
Closed with no receiptstatus 'closed', receipt nullThe balance had another computation in flight when the queue reached the order, so the order was closed and nothing moved. Place it again once that computation has landed.

The fee rates are in Fees, and the mechanism of the cross and the sweep in Sealed orders.

Place a dark order, collect and cancel

A dark order crosses at the pool's mid and rests what is left in the sealed book. Every dark order has an expiry, at most a day ahead: after it the order no longer rests and anyone may cancel it. Without expiry, the SDK sets the longest a dark order may rest.

ts
const dark = await hadal.darkOrder({ market, side: 'sell', size: base(10), limit: price(95), key })
await run(dark)
const rested = await processed(dark.account!)
console.log(rested.status, 'resting', rested.receipt?.receipt.rested, 'filled at once', rested.receipt?.receipt.filled)

if (rested.status === 'resting') {
  // Later: move what the order has earned so far to the sealed balance. The order keeps resting.
  await run(await hadal.collect(dark.account!))
  const collected = (await hadal.balance(market, key))!.receipt
  console.log('collected', collected.filled, collected.quote)

  // Cancel: what is still locked and any proceeds come back, and the order closes.
  await run(await hadal.cancel(dark.account!))
  console.log((await hadal.order(dark.account!)).status)
}
StateHow it readsWhat to do
Restingstatus 'resting', ok truerested is the size that waits in the book, filled what crossed on arrival. Other orders cross it while it rests. collect at any time, cancel to take it out.
Filled on arrivalstatus 'closed', ok true, rested 0The whole size crossed when the order was processed. Nothing rests and the proceeds are already in the sealed balance.
Voidstatus 'closed', ok falseThe balance did not cover the order. Nothing moved and it takes no slot.
Closed with no receiptstatus 'closed', receipt nullThe order was closed before it ran: the book had no free slot, its expiry had passed, or the balance had another computation in flight. Nothing moved. Place it again.
Collectedledger receipt: filled, quoteThe base and quote credited to the sealed balance. Both are 0 when nothing has crossed the order since the last collect.
Closedstatus 'closed'After cancel. The ledger’s receipt holds what came back: the locked remainder and the proceeds.

collect throws before building when the order is not resting, and cancel when the order is already closed. A resting order's fills are sealed in the book. The owner learns them by collecting.

Open a deal

A deal offers a size to one counterparty, or to anyone holding its link when taker is null. Its side is public. Its size, minimum size and limit are sealed. The maker's escrow leaves the sealed balance when the deal opens.

ts
const deal = await hadal.openDeal({
  market,
  side: 'sell',
  size: base(20),
  minSize: base(5),
  limit: price(98),
  taker: process.env.COUNTERPARTY ? new PublicKey(process.env.COUNTERPARTY) : null,
  expiry: Math.floor(Date.now() / 1000) + 3600,
  key,
})
await run(deal)

const opened = await hadal.deal(deal.account!, key)
console.log(opened.status, opened.side, opened.terms)
console.log('send to the counterparty:', deal.account!.toBase58())
StateHow it readsWhat to do
Openstatus 'open'The escrow is in the deal. The deal’s address is its link: give it to the counterparty, who answers it from a script or at /deals/ followed by the address in the app. terms reads back what you sealed.
Voidstatus 'void'The sealed balance did not cover the escrow, or the terms were not valid. Nothing moved. Open another deal.
Donestatus 'done'The whole size traded. Close the deal to receive the proceeds.
Still open after an answerstatus 'open'An answer did not trade, or it traded part of the size. The deal takes more answers until its expiry.

Closing the deal moves the escrow that is left and the proceeds to the maker's sealed balance. The maker closes an open deal, which cancels it. A deal that is done or past its expiry can be closed by anyone, and the funds go to the maker. In the app this is Cancel deal on an open deal and Close deal on a done or expired one.

ts
await run(await hadal.cancelDeal(deal.account!))
console.log((await hadal.deal(deal.account!)).status)

Answer a deal

The taker reads the deal's side, which is public, and answers on the opposite side with a sealed size and limit of their own. The taker's balance is the one in the deal's market, and each answer uses one of the taker's attempts.

ts
if (process.env.DEAL) {
  const theirs = new PublicKey(process.env.DEAL)
  const before = await hadal.deal(theirs)
  console.log('the maker', before.side === 'sell' ? 'sells' : 'buys', 'and the script takes the other side')
  await run(await hadal.takeDeal({ deal: theirs, size: base(20), limit: price(102), key }))

  const answer = (await hadal.balance(before.account.market, key))!.receipt
  if (answer.ok) console.log('traded', answer.filled, 'for', answer.quote, 'fee', answer.fee)
  else console.log('no deal')
}
StateHow it readsWhat to do
Doneok trueThe answer traded: filled base at the midpoint of the two limits, for quote, with fee. The tokens are in the sealed balance.
No dealok falseThe limits did not cross, the size was below the maker’s minimum, or the balance did not cover the trade. Nothing moved and one attempt is used. Answer again with other terms while attempts remain.
Refusedrun throwsThe transaction was refused: the deal is not open, is past its expiry, names another wallet, or the attempts are used up. The error names which.

Neither side sees the other's limit in any of these states. See Deals.

Add and remove liquidity

Liquidity comes from the sealed balance and goes back to it. The two amounts are the most to add: the pool takes them in its own ratio.

ts
await run(await hadal.addLiquidity({ market, base: base(5), quote: quote(600), key }))
const supplied = (await hadal.balance(market, key))!
console.log('shares', supplied.shares, 'used', supplied.receipt.filled, supplied.receipt.quote)

await run(await hadal.removeLiquidity({ market, shares: supplied.shares, key }))
const removed = (await hadal.balance(market, key))!
console.log('received', removed.receipt.filled, removed.receipt.quote)

receipt.ok is false and nothing moved when the amounts mint no share or the balance does not cover them, and when the shares to remove are more than the balance holds. Both calls are refused with EmptyBalance on a balance no deposit has landed in. See Liquidity.

Withdraw

A withdrawal names a public amount. The computation checks the sealed balance and the callback pays the wallet, or refuses.

ts
await run(await hadal.withdraw({ market, side: 'base', amount: base(15) }))
const withdrawal = (await hadal.balance(market, key))!.receipt
console.log(withdrawal.ok ? 'paid' : 'refused')
StateHow it readsWhat to do
Paidok trueThe tokens are in the wallet’s associated token account.
Refusedok falseThe sealed balance holds less than the amount. Nothing moved. Funds locked in a resting order or a deal’s escrow are not in the balance: cancel the order or close the deal first.

Following a computation

Every step above goes through the same two stages: a transaction the wallet signs, then a computation the cluster runs. Each stage ends in one of these states.

StateWhat the script seesWhat it means and what to do
Transaction refusedsendWithKeypairs throws: Transaction <signature> failed, or the RPC’s simulation errorThe program refused the instruction and nothing changed. The error carries the program’s error. Busy means the account still has a computation in flight: wait and send again.
Transaction expiredsendWithKeypairs throws: Transaction <signature> expiredThe transaction was not confirmed in time and did nothing. Build the action again and send it.
DoneawaitComputation resolves with a signatureThe callback has written the result. Read the balance, the order or the deal. receipt.ok says whether the action took effect or was void.
RefusedawaitComputation throws: 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, below.
ExpiredawaitComputation throws: Computation did not finalize within <timeout>msThe cluster did not run the computation in the time the script waited. One that is not taken up within 180 slots is void. Nothing it would have changed is changed, and the accounts stay locked until they are released, below.

awaitComputation waits for its default time unless a second argument sets another, in milliseconds. The measured time from queue to callback is in Limits, and the lifecycle in Arcium.

An account whose computation was refused or expired is released once the release window has passed. Anyone may send a release. Each kind of account has its call, and a computation that locked several needs each of them released:

ts
async function release(deal?: PublicKey) {
  // The balance. A deposit that was waiting is paid back to the wallet in the same transaction.
  await run(await hadal.reclaim({ market }))
  // The market's book: after an order, a collect, a cancel, liquidity, the closing of a deal or a sounding.
  await run(await hadal.releaseMarket(market))
  // A deal: after opening, answering or closing it. One still opening becomes void.
  if (deal) await run(await hadal.releaseDeal(deal))
}

Each release is refused with ComputationStillLive before the window has passed and with NothingPending when the account is not locked, so send only the ones the failed step locked: a deposit or a withdrawal locks the balance alone. Then the step is made again.

Receipts history through the API

A balance and an order hold only their last receipt. The HTTP API keeps every ledger a computation left for the wallet and serves each one as the ciphertexts and nonce the program emitted. Sealer.ledger opens each one with the reading key.

ts
type SealedReceipt = {
  id: string
  owner: string
  market: string
  orderId: string | null
  dealId: string | null
  transferId?: string | null
  balanceId?: string
  time: number
  signature?: string
  slot?: number
  layout?: 'ledger-v1'
  values: { sealed: true; ciphertexts: string[]; nonce: string; encryptionKey: string }
}
type ReceiptsPage = { items: SealedReceipt[]; page: { nextCursor: string | null; hasMore: boolean } }

const sealer = await hadal.sealer(key)
let cursor: string | null = null
do {
  const url = new URL(`/v1/wallets/${keypair.publicKey.toBase58()}/receipts`, process.env.HADAL_API)
  url.searchParams.set('limit', '100')
  if (cursor) url.searchParams.set('cursor', cursor)
  const body = (await (await fetch(url)).json()) as ReceiptsPage

  for (const item of body.items) {
    const ledger = sealer.ledger({
      ciphertexts: item.values.ciphertexts.map((c) => Buffer.from(c, 'base64')),
      nonce: Buffer.from(item.values.nonce, 'base64'),
    })
    const of = item.orderId ? 'order' : item.dealId ? 'deal' : item.transferId ? 'transfer' : 'balance'
    console.log(new Date(item.time).toISOString(), of, ledger.receipt, 'balance after', ledger.base, ledger.quote, ledger.shares)
  }
  cursor = body.page.nextCursor
} while (cursor)

What is public on each item: which order, deal or transfer it is the result of, the balance account it was written to, its time, slot and transaction. What it says is in values, which holds the four ciphertexts of a ledger: the balances after the action and the action's receipt. The route is GET /v1/wallets/:wallet/receipts, and reading receipts one by one is in the receipts guide. The API receives the wallet's address and returns ciphertext. The key stays in the script.

Where to go next