Guides

Call a hook from your app

Any app can run a hook for its users with @pook/sdk. The SDK quotes the run, proves it, hands it to a relayer and follows it to confirmation. This guide sets the SDK up, runs a hook, follows the run, handles each failure, and reads the balance, the seats and the history.

Install

Shell
npm i @pook/sdk @pook/circuits

@pook/sdk is the client. @pook/circuits is the compiled circuits, a WebAssembly module of about 7 MB that the SDK proves with. Load it when the user first needs the private side, not with your first page.

Create the client

TypeScript
import { createPook } from '@pook/sdk'
import { loadCircuits } from '@pook/circuits'

export const pook = createPook({
  apiUrl: 'https://api.pook.codes',
  wasm: await loadCircuits(), // fetches and starts the WebAssembly module
})

createPook takes these options.

OptionTypeMeaning
apiUrlstringThe Pook API. The registry, quotes, the relayer and the prover are all reached through it.
wasmmoduleThe circuits, from loadCircuits(). Needed for anything that proves: run, leave, opening and closing a seat.
relayerUrlstringA relayer to submit through, in place of the one the API uses.
proverTeeProverTeeHow Rings spend proofs are requested. On mainnet each request is encrypted to the attested Rings prover enclave by default.
signerWalletSignerThe user’s wallet. It can be set later with setSigner.
proverUrlstringA prover service to fetch circuit files from directly. Defaults to the API.
photonUrlstringA Rings indexer to scan notes from directly. Defaults to the API.
rpcUrlstringA Solana RPC. Defaults to the API’s pass-through.
fetchfunctionA fetch to use in place of the global one.
headersobjectHeaders sent with every request.

Give it a signer

The SDK asks three things of a wallet. Any wallet library can supply them.

TypeScript
import type { WalletSigner } from '@pook/sdk'

const signer: WalletSigner = {
  // The wallet's address, base58.
  publicKey: wallet.address,

  // Signs a message. Used once, to derive the user's keys.
  signMessage: (message: Uint8Array) => wallet.signMessage(message),

  // Signs a transaction given as base64 and returns it signed, as base64.
  // Used for entering, publishing and claiming.
  signTransaction: async (transactionBase64: string) => ({
    signedTransactionBase64: await wallet.signTransactionBase64(transactionBase64),
  }),
}

pook.setSigner(signer)

wallet stands for your wallet connection. A wallet that sends the transaction itself can return { signature } from signTransaction in place of the signed bytes.

Unlock

TypeScript
await pook.unlock()

unlock asks the wallet to sign one message, the text POOK/derive/v1, and derives every key from the signature. The keys stay in memory on the device. pook.lock() drops them, pook.isUnlocked() reports the state, and changing the signer to another wallet locks.

Calls that need keys unlock on their own if you have not, so unlock is for choosing the moment the wallet prompt appears.

Run a hook

TypeScript
const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
const SOL = 'So11111111111111111111111111111111111111112'

const result = await pook.run('jupiter.swap', {
  in: USDC,
  out: SOL,
  amount: '10000000',
})

The first argument is the hook's name. The second holds the run's values.

ParameterTypeMeaning
amountstring | bigintThe amount in, in the asset’s smallest unit. For a hook that takes nothing in, such as a borrow, the amount asked of the protocol.
instringThe mint of the asset in. Also accepted as mintIn. Use the wrapped SOL mint for SOL.
outstringThe mint of the asset out. Also accepted as mintOut.
slippageBpsnumberHow far below the expected out the result may land, in basis points. Defaults to 50.
minimumOutstring | bigintThe least you accept back, in the out asset’s smallest unit. Required for a hook that has an asset out and is not one of the launch hooks.
seatstringThe seat’s address, for a seat hook. Left out on a seat hook, a new seat is opened first.
argsRecord<string, string>Values for the hook’s own inputs, by name. A hook’s page in the registry lists them.
onStagefunctionCalled as the run moves through its stages.
signalAbortSignalCancels the call.

The launch hooks work out the expected and minimum out themselves from slippageBps. For any other hook that returns an asset, you name minimumOut, and the program fails the run if less comes back.

Which of in and out a hook needs depends on the hook. pook.hook(id) returns its record, with formFields naming every input a run takes.

Follow a run

run resolves when the run has settled or 60 seconds have passed. onStage reports each step on the way.

TypeScript
const result = await pook.run('jupiter.swap', {
  in: USDC,
  out: SOL,
  amount: '10000000',
  onStage: (stage, detail) => {
    // 'opening_seat' | 'quoting' | 'proving' | 'relayed' | 'confirmed'
    showProgress(stage)
  },
})
StageWhat is happeningdetail
opening_seatA seat hook was run with no seat, and one is being opened.
quotingThe hook's resolver is building the call and the fees.
provingThe quote is back and the proofs are being made.The quote
relayedThe relayer has taken the run.The relayer's first answer
confirmedThe transaction is confirmed.The relayer's final answer

The result holds everything the run produced.

FieldTypeMeaning
quoteQuoteResponseThe quote the run was proved against: amounts, fees, minimum out, the resolved call.
relayRelaySubmissionResponseThe relayer’s record: relayId, status, signature, slot, and error when it failed.
signaturestring | nullThe run’s transaction.
seatstring | nullThe seat the run used or opened.
openSeatSignaturestring | nullThe transaction that opened the seat, when this run opened one.

relay.status is one of accepted, submitted, confirmed, finalized, failed and expired. If it is still submitted when run returns, read it again with pook.client.relayStatus(relay.relayId) until it settles.

Handle what can go wrong

A run fails in one of two ways, and neither spends a note.

Before the transaction is sent, run throws an ApiClientError. It carries a stable code, a message fit to show, the stage that failed and whether a retry can help.

After it is sent, run returns with relay.status of failed or expired, and relay.error holds the same fields. When the Pook program refused the transaction, relay.error.programError.name is the program's own error.

TypeScript
import { ApiClientError } from '@pook/sdk'

try {
  const { relay } = await pook.run('jupiter.swap', { in: USDC, out: SOL, amount })

  if (relay.status === 'failed') {
    const reason = relay.error?.programError?.name ?? relay.error?.code
    if (reason === 'SlippageExceeded') return retryWithFreshQuote()
    return show(relay.error?.message)
  }
  if (relay.status === 'expired') return retryWithFreshQuote()
} catch (e) {
  if (!(e instanceof ApiClientError)) throw e
  switch (e.code) {
    case 'NO_ROUTE':             return show('No route for this pair and amount.')
    case 'INSUFFICIENT_BALANCE': return show('Your private balance does not hold that much.')
    case 'UNAUTHORIZED':         return connectWallet()
    default:
      if (e.retryable) return retryLater()
      show(e.message)
  }
}
CodeWhenWhat to do
UNAUTHORIZEDA call needed the wallet and no signer is set.Connect a wallet and set the signer.
WALLET_REJECTEDThe user declined to sign.Nothing moved. Offer the action again.
INSUFFICIENT_BALANCENo one or two notes of the asset in cover the amount.Lower the amount.
NO_ROUTEThe hook's resolver found no way to do this.Change the amount or the assets.
SEAT_NOT_EMPTYcloseSeat on a seat that still holds collateral or owes debt.Repay and withdraw first.
TRANSACTION_EXPIREDThe proof's expiry passed before the relayer took it.Run again.
RELAY_REFUSEDThe relayer would not take the run, for example a fee under its quote.Run again for a fresh quote.
CHAIN_REFUSED, SIMULATION_FAILEDThe transaction failed on chain or in the relayer's simulation.Read programError.name.
PROGRAM_UNAVAILABLEThe API is not connected to the program at the moment.Retry later.

The API reference lists every code, and the program reference every program error.

Read the balance

TypeScript
const { assets, notes } = await pook.balance()

for (const a of assets) {
  console.log(a.symbol, a.amount, a.decimals, a.noteCount)
}

balance fetches the encrypted notes, decrypts the user's own on the device and sums the unspent ones by asset. assets holds one entry for each asset with its mint, symbol, decimals, total amount in base units and noteCount. notes is every note behind them.

Read the seats

TypeScript
const seats = await pook.seats()

Each seat comes back with its seatAddress, protocol, status, its collateral and debt at the protocol, its healthFactor and the hook names in actions. Borrow from a seat uses them.

Read the history

TypeScript
const history = await pook.activity()

activity returns the user's own enters, runs and leaves, newest first, read from their notes: kind, hookId for a run, the asset and amount, the signature, slot and timestamp. It is private to the device. The public feed of every run is pook.runs().

Read the registry

These calls need no wallet.

TypeScript
const { items } = await pook.hooks({ protocol: 'kamino' }) // every hook, or a filter
const { hook } = await pook.hook('jupiter.swap')           // one hook in full
const feed = await pook.runs({ hookId: 'jupiter.swap' })   // public runs
const stats = await pook.stats()                           // hooks, runs, seats, volume