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
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
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.
| Option | Type | Meaning |
|---|---|---|
apiUrl | string | The Pook API. The registry, quotes, the relayer and the prover are all reached through it. |
wasm | module | The circuits, from loadCircuits(). Needed for anything that proves: run, leave, opening and closing a seat. |
relayerUrl | string | A relayer to submit through, in place of the one the API uses. |
proverTee | ProverTee | How Rings spend proofs are requested. On mainnet each request is encrypted to the attested Rings prover enclave by default. |
signer | WalletSigner | The user’s wallet. It can be set later with setSigner. |
proverUrl | string | A prover service to fetch circuit files from directly. Defaults to the API. |
photonUrl | string | A Rings indexer to scan notes from directly. Defaults to the API. |
rpcUrl | string | A Solana RPC. Defaults to the API’s pass-through. |
fetch | function | A fetch to use in place of the global one. |
headers | object | Headers sent with every request. |
Give it a signer
The SDK asks three things of a wallet. Any wallet library can supply them.
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
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
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.
| Parameter | Type | Meaning |
|---|---|---|
amount | string | bigint | The 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. |
in | string | The mint of the asset in. Also accepted as mintIn. Use the wrapped SOL mint for SOL. |
out | string | The mint of the asset out. Also accepted as mintOut. |
slippageBps | number | How far below the expected out the result may land, in basis points. Defaults to 50. |
minimumOut | string | bigint | The 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. |
seat | string | The seat’s address, for a seat hook. Left out on a seat hook, a new seat is opened first. |
args | Record<string, string> | Values for the hook’s own inputs, by name. A hook’s page in the registry lists them. |
onStage | function | Called as the run moves through its stages. |
signal | AbortSignal | Cancels 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.
const result = await pook.run('jupiter.swap', {
in: USDC,
out: SOL,
amount: '10000000',
onStage: (stage, detail) => {
// 'opening_seat' | 'quoting' | 'proving' | 'relayed' | 'confirmed'
showProgress(stage)
},
})| Stage | What is happening | detail |
|---|---|---|
opening_seat | A seat hook was run with no seat, and one is being opened. | |
quoting | The hook's resolver is building the call and the fees. | |
proving | The quote is back and the proofs are being made. | The quote |
relayed | The relayer has taken the run. | The relayer's first answer |
confirmed | The transaction is confirmed. | The relayer's final answer |
The result holds everything the run produced.
| Field | Type | Meaning |
|---|---|---|
quote | QuoteResponse | The quote the run was proved against: amounts, fees, minimum out, the resolved call. |
relay | RelaySubmissionResponse | The relayer’s record: relayId, status, signature, slot, and error when it failed. |
signature | string | null | The run’s transaction. |
seat | string | null | The seat the run used or opened. |
openSeatSignature | string | null | The 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.
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)
}
}| Code | When | What to do |
|---|---|---|
UNAUTHORIZED | A call needed the wallet and no signer is set. | Connect a wallet and set the signer. |
WALLET_REJECTED | The user declined to sign. | Nothing moved. Offer the action again. |
INSUFFICIENT_BALANCE | No one or two notes of the asset in cover the amount. | Lower the amount. |
NO_ROUTE | The hook's resolver found no way to do this. | Change the amount or the assets. |
SEAT_NOT_EMPTY | closeSeat on a seat that still holds collateral or owes debt. | Repay and withdraw first. |
TRANSACTION_EXPIRED | The proof's expiry passed before the relayer took it. | Run again. |
RELAY_REFUSED | The relayer would not take the run, for example a fee under its quote. | Run again for a fresh quote. |
CHAIN_REFUSED, SIMULATION_FAILED | The transaction failed on chain or in the relayer's simulation. | Read programError.name. |
PROGRAM_UNAVAILABLE | The 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
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
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
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.
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