Reference

SDK

Every export of @pook/sdk: the client and its methods, the standalone functions, the types they take and return, the errors they throw, and the lower-level helpers. Call a hook from your app is the guided version.

Shell
npm i @pook/sdk @pook/circuits

loadCircuits() from @pook/circuits returns the circuits for the runtime it is called in, the browser or Node. Pass what it resolves to as wasm.

The package is an ES module, typed, and runs in the browser and in Node. Amounts are in an asset's smallest unit, as a decimal string or a bigint. Addresses and mints are base58 strings. SOL is named by the wrapped SOL mint.

createPook

TypeScript
function createPook(config: PookConfig): Pook

Makes a client. One client holds one signer, that signer's keys while unlocked, and a cache of the last scan of notes.

PookConfigTypeMeaning
apiUrlstringThe Pook API.
wasmPookWasmModuleThe circuits, from loadCircuits() of @pook/circuits. Required by run, leave, openSeat and closeSeat.
relayerUrlstringA relayer to submit through, in place of the one the API uses.
proverTeeProverTeeHow Rings spend proofs are requested. By default on mainnet, each request is encrypted to the attested Rings prover enclave. See Notes and the private balance.
signerWalletSignerThe wallet. Can be set later with setSigner.
keysHolderKeysKeys from an earlier unlock, to start unlocked.
proverUrlstringA prover service to read circuit files from. Defaults to the API.
photonUrlstringA Rings indexer to scan notes from. Defaults to the API.
rpcUrlstringA Solana RPC. Defaults to the API’s pass-through.
fetchtypeof fetchA fetch to use in place of the global one.
headersRecord<string, string>Headers sent with every request.
credentialsRequestCredentialsThe credentials mode of every request.
keyDerivationKeyDerivationSeamReplaces how keys are derived from the signer.
noteScannerNoteScannerSeamReplaces how notes are fetched and decrypted.
proverProverSeamReplaces how a proof request is answered.

configurePook

TypeScript
function configurePook(config: PookConfig): Pook

Makes a client and keeps it as the default for the standalone functions below.

The session

MethodTypeMeaning
pook.setSigner(signer)voidSets or clears the wallet. A different wallet locks the client.
pook.unlock(signer?)Promise<HolderKeys>Asks the wallet to sign the message POOK/derive/v1 and derives the holder’s keys from the signature.
pook.lock()voidDrops the keys and the cached notes.
pook.isUnlocked()booleanWhether keys are held.
pook.clientPookApiClientThe typed API client the SDK calls through, one method for each route.

run

TypeScript
pook.run(hookId: string, params: RunParams): Promise<RunResult>

Runs a published hook against the private balance: quote, prove, relay, follow. On a seat hook with no seat, it opens a seat first.

RunParamsTypeMeaning
amountstring | bigintThe amount in. For a hook with no asset in, the amount asked of the protocol.
instringMint of the asset in. Alias: mintIn.
outstringMint of the asset out. Alias: mintOut.
slippageBpsnumberSlippage in basis points. Default 50.
minimumOutstring | bigintThe least accepted back, in the out asset’s smallest unit. Required for a hook with an asset out that is not one of the launch hooks.
seatstringThe seat’s address, for a seat hook.
argsRecord<string, string>Values for the hook’s own inputs, by name.
onStage(stage: RunStage, detail?) => voidCalled at each stage.
signalAbortSignalCancels the call.

RunStage is 'quoting' | 'opening_seat' | 'proving' | 'relayed' | 'confirmed'.

RunResultTypeMeaning
quoteQuoteResponseThe quote the run was proved against.
relayRelaySubmissionResponseThe relayer’s record of the submission.
signaturestring | nullThe run’s transaction.
seatstring | nullThe seat used or opened.
openSeatSignaturestring | nullThe transaction that opened the seat, when this run opened one.

Throws ApiClientError with INSUFFICIENT_BALANCE when no one or two notes cover the amount, NOT_FOUND when a seat hook is given a seat the holder has no note for, and whatever the quote or the relayer answers. A hook outside the launch set that has an asset out answers VALIDATION_ERROR naming minimumOut when it is left out, and its quote carries minimumOutFromCaller: true. A transaction that fails on chain does not throw: relay.status is failed or expired, and relay.error says why.

enter

TypeScript
pook.enter(params: EnterParams): Promise<EnterResult>

Moves an asset from the signer's wallet into the private balance. The wallet signs one transaction.

EnterParamsTypeMeaning
mintstringThe asset.
amountstring | bigintHow much.
source'wallet' | 'rings'Where it comes from. Default wallet.
signerWalletSignerA signer for this call, in place of the client’s.
onStage(stage: EnterStage, detail?) => voidCalled at each stage.
signalAbortSignalCancels the call.

EnterStage is 'building' | 'proving' | 'signing' | 'submitted' | 'confirmed'. proving is reported when the source is a Rings private balance, which spends up to two Rings notes in one enter. EnterResult holds build (the TxBuildResponse), tx (the TxStatusResponse) and signature.

Throws ApiClientError with UNAUTHORIZED when no signer is set and WALLET_REJECTED when the wallet declines.

leave

TypeScript
pook.leave(params: LeaveParams): Promise<LeaveResult>

Moves an asset out of the private balance to a public address or a Rings private balance. A relayer submits it.

LeaveParamsTypeMeaning
mintstringThe asset.
amountstring | bigintHow much leaves the balance. The relayer’s fee comes off it.
destinationstringA Solana address. For a Rings destination, the wallet address the recipient registered with Rings: the SDK looks up their Rings address from it.
destinationType'wallet' | 'rings'Default wallet.
destinationViewTagstringFor a caller that already holds the recipient’s Rings owner hash: pass the hash in hex as destination and the 32-byte view tag here, base58.
onStage(stage: LeaveStage, detail?) => voidCalled at each stage.
signalAbortSignalCancels the call.

LeaveStage is 'quoting' | 'proving' | 'relayed' | 'confirmed'. LeaveResult holds relay and signature.

Throws ApiClientError with NOT_FOUND when a Rings destination is a wallet address with no record in the Rings user registry.

openSeat and closeSeat

TypeScript
pook.openSeat(options?: OpenSeatOptions): Promise<SeatActionResult>
pook.closeSeat(seatAddress: string, options?: { openerRelayer?: string; signal?: AbortSignal }): Promise<SeatActionResult>

openSeat opens a seat and creates its seat note. run calls it for you on a first seat run. OpenSeatOptions takes protocol ('kamino', the default, which also creates the seat's Kamino accounts, or 'none'), lendingMarket (a Kamino market, default the main market), seatIndex and signal.

closeSeat closes a seat that holds and owes nothing and returns its rent to the relayer that opened it. It throws NOT_FOUND when the holder has no note for that seat, and SEAT_NOT_EMPTY while the seat still holds collateral or owes debt.

SeatActionResult holds relay, seatAddress, seatCommitmentHex and signature.

balance, seats and activity

TypeScript
pook.balance(options?): Promise<BalanceResult>
pook.seats(options?): Promise<SeatPosition[]>
pook.activity(options?): Promise<ActivityItem[]>

All three scan the holder's notes on the device first. options takes signer and signal.

ReturnsTypeMeaning
BalanceResultobjectassets: one AssetBalance for each asset held (mint, symbol, decimals, amount, noteCount). notes: every DecryptedNote. asOf: when it was read.
SeatPositionobjectseatAddress, protocol, protocolName, obligationAddress, status (open, empty or closed), collateral and debt (each mint, symbol, decimals, amount, usdValue), healthFactor, actions, openerRelayer, updatedAt.
ActivityItemobjectid, kind (enter, run or leave), hookId, mint, symbol, decimals, amount, signature, slot, timestamp. Newest first.
TypeScript
pook.publicBalance(mint?: string, options?): Promise<PublicBalanceResponse>

Reads the public balance of the connected wallet, or of options.wallet, for one mint. Default SOL.

defineHook, simulateHook and publishHook

TypeScript
defineHook(input: DefineHookInput): HookDefinition
pook.simulateHook(params: SimulateHookParams): Promise<SimulateHookResponse>
pook.publishHook(params: PublishHookParams): Promise<EnterResult>

defineHook checks a hook definition against the hook schema and returns it frozen. It throws a ZodError naming each field that is wrong. It talks to nothing.

simulateHook runs the hook's instruction against chain state with the stage in place. SimulateHookParams takes hook, sampleAmountIn, and optionally sampleMintIn, sampleMintOut and sampleArgs. The response holds passed, computeUnits, logs, estimatedTxBytes, accountCount and error when it failed.

publishHook builds the publish_hook transaction, has the wallet sign it and submits it. PublishHookParams takes hook, and optionally signer, onStage and signal. The signer becomes the hook's author. It answers HOOK_ALREADY_EXISTS when the name is taken.

claimAuthorFees

TypeScript
pook.claimAuthorFees(params: ClaimAuthorFeesParams): Promise<EnterResult>
pook.authorFees(wallet: string): Promise<AuthorFeesResponse>

authorFees lists what an author's hooks have earned and what is claimable, for each hook and asset. claimAuthorFees takes hookIds, optionally mint to claim one asset, signer, onStage and signal. The wallet signs one transaction, and the claimable amount is paid to it.

Reading the registry

No wallet is needed for these. Each returns the API's response as typed.

MethodTypeMeaning
pook.hooks(query?)Promise<HooksPage>The registry. Filters: protocol, kind, q. Paged.
pook.hook(id)Promise<HookDetailResponse>One hook in full, with its recent runs.
pook.quote(hookId, body)Promise<QuoteResponse>A quote without a run.
pook.runs(query?)Promise<RunsPage>The public feed of runs. Filters: hookId, protocol.
pook.runsStreamUrl(query?)stringThe address of the live feed, for an EventSource.
pook.stats()Promise<StatsResponse>Counts of hooks, runs and open seats, and volume by asset.
pook.config()Promise<ConfigResponse>The program and its addresses, the fee rates and the supported assets.
pook.health()Promise<HealthResponse>Whether the API is ready.
pook.parseIdl(body)Promise<ParsedIdlResponse>A program’s instructions, from its ID or its IDL as JSON.

Standalone functions

After configurePook, the methods are also plain functions. Each takes a client as an optional last argument.

TypeScript
import { configurePook, run, enter, leave, balance, seats, activity } from '@pook/sdk'
import { loadCircuits } from '@pook/circuits'

configurePook({ apiUrl: 'https://api.pook.codes', wasm: await loadCircuits(), signer })
await run('jupiter.swap', { in, out, amount })

The functions are run, enter, leave, openSeat, closeSeat, balance, publicBalance, seats, activity, publishHook, simulateHook, claimAuthorFees and defineHook. Calling one before configurePook throws an Error.

Types

TypeTypeMeaning
WalletSignerobjectpublicKey: string. signMessage(message: Uint8Array): Promise<Uint8Array>. signTransaction?(transactionBase64: string): Promise<{ signedTransactionBase64?: string; signature?: string }>.
HolderKeysobjectWhat unlock derives: wallet, authorityPda, ownerHash, viewingPkBase64, and the secrets seed, viewingSecret and nullifierSecretHex. Keep it on the device.
DecryptedNoteobjectOne note: commitment, kind (balance or seat), action (enter, run or leave), mint, symbol, decimals, amount, spent, nullifier, signature, slot, timestamp, and for a seat note seatAddress.
PookobjectThe client createPook returns.
PookConfigobjectThe options of createPook.
HookDefinition, DefineHookInputobjectA hook definition, after and before defineHook.
PookWasmModuleinterfaceThe shape of the circuits module.
KeyDerivationSeam, NoteScannerSeam, ProverSeamobjectThe three replaceable parts of a client.

The request and response types of the API are exported under the names the API reference uses: QuoteRequest, QuoteResponse, RelaySubmissionResponse, TxBuildResponse, TxStatusResponse, HookSummary, HookDetail, HookDetailResponse, HookDraft, HooksPage, RunsPage, PublicRun, SeatPosition, SimulateHookResponse, ParsedIdlResponse, AuthorFeesResponse, AuthorHookFee, ConfigResponse, HealthResponse, StatsResponse, AssetInfo, PublicBalanceResponse, ProverCircuitsResponse, MintConstraint, OnChainDataSlot, OnChainAccountSlot, OnChainCompanion, WirePublishHookArgs, PookApiClient.

Errors

Every failure the SDK reports is an ApiClientError, apart from a ZodError from defineHook and an Error from a standalone function called before configurePook.

ApiClientErrorTypeMeaning
codeErrorCodeA stable code to branch on.
messagestringA sentence fit to show.
statusnumberThe HTTP status.
stageErrorStageWhere it failed: validation, build, wallet, wallet_rejected, simulation, proving, relay, send, confirmation or expired, among others.
retryablebooleanWhether the same call can succeed later.
programErrorProgramErrorWhen a program refused: programId, name and number.
fieldErrorsRecord<string, string[]>For VALIDATION_ERROR, the messages for each field.
bodyApiErrorBodyThe whole error as the API sent it.

The SDK raises three codes itself: UNAUTHORIZED when a signer is needed and none is set, WALLET_REJECTED when the wallet declines to sign, and INSUFFICIENT_BALANCE when the notes do not cover an amount. Every other code comes from the API, and the API reference lists them all. Program errors by name and number are in the program reference, and POOK_ERROR_NAMES maps number to name.

Constants and pure helpers

ExportTypeMeaning
POOK_ERROR_NAMESRecord<number, string>The program’s errors, number to name.
POOK_TAGSobjectThe program’s instruction tags, by name.
errorsobjectThe API’s error table: errors.status maps each code to its HTTP status, errors.knownCodes lists them.
CONTRACT_VERSIONstringThe version of the API contract the SDK was built against.
WSOL_MINT, SYSTEM_PROGRAM_IDstringThe wrapped SOL mint and the System program.
RINGS_DERIVE_MESSAGEstringThe message unlock signs.
computeFeeSplit(out, runFeeBps, authorShareBps)objectThe run fee and its two parts for a result, rounded as the program rounds: runFee, protocolFee, authorFee.
computeCallHash(targetProgram, hasMintOut, mintOut, data, accounts)Uint8ArrayThe hash of a resolved call, as the program computes it and the proof fixes it.
resolveCpiData(dataTemplateHex, dataSlots, amountIn, minOut, callerData)Uint8ArrayA hook’s instruction data with its slots filled.
hookIdHash(hookId)Uint8ArrayThe 32 bytes a hook’s address is derived from.
hookDraftToOnChain(draft)WirePublishHookArgsA hook definition as publish_hook stores it.
shortAddress(address, n?)stringAn address shortened for display.
createClient(baseUrl, options?)PookApiClientThe typed API client on its own, without keys or proving.

Keys and addresses

These derive what the client derives. They are exported for tools that work below run.

ExportTypeMeaning
deriveAuthorityPda(programId)Promise<[string, number]>The authority and its bump.
deriveStagePda(programId)Promise<[string, number]>The stage and its bump.
deriveConfigPda(programId)Promise<[string, number]>The config account and its bump.
deriveSeatPda(programId, commitment)Promise<[string, number]>A seat’s address from its commitment.
deriveSeatStatePda(programId, commitment)Promise<[string, number]>A seat’s state account.
deriveAuthorFeesPda(programId, author, mintBytes)Promise<[string, number]>An author’s fee account for one asset.
deriveAtaAddress(owner, mint, tokenProgram?)Promise<string>An associated token account.
derivePookPda(programId, seeds)Promise<[string, number]>Any address derived from the program.
deriveSppSplInterfaceWithBump(ringsProgramId, mint)Promise<[string, number]>The Solana Privacy Program’s account for a token.
deriveNullifierSecretBytes(seed, index)Uint8ArrayThe one-time secret for note number index.
deriveSeatSecretBytes(seed, seatIndex)Uint8ArrayThe secret of seat number seatIndex.
deriveSeatCommitmentBytes(seed, seatIndex)Uint8ArrayThat seat’s commitment.
deriveOneTimePdaKeys(keys, index)Promise<object>Everything for one note number: owner hash, nullifier key, Rings address.
deriveProgramOwnerZeroAddress(keys)Promise<Uint8Array>The Rings address a seat’s commitment is reserved under.
authorityIdentityFieldDec(authorityPda)stringThe authority as the circuits take it.
buildKaminoOpenSeatSetup(seatPda, lendingMarket?)Promise<object>The setup calls that create a seat’s Kamino accounts when it opens.
deriveRingsWalletKeys(signer, spr)Promise<LocalKeys>The holder’s own Rings keys, from one wallet signature. Used to enter from a Rings private balance.
buildRingsEnterTransact(params)Promise<object>The Rings transfer that moves a holder’s Rings notes into a Pook note, proved and ready for enter.
resolveRingsRecipientAddress(spr, walletAddress, signal?)Promise<{ ownerHash, viewTag }>A recipient’s Rings owner hash and view tag, looked up from the wallet address they registered with Rings.
clearScanState(keys)voidDrops the key material a client cached while scanning notes for these keys.
defaultKeyDerivation, defaultNoteScanner, defaultProverseamThe parts a client uses unless createPook is given others.
loadCircuitArtifacts, proveProgramAndSpp, createMultiKeyProofAuthorityfunctionThe proving steps run uses: fetch a circuit’s files, prove the Pook circuit and the Rings spend together, and sign for several one-time keys.

The package also passes through the pieces of the Rings client it builds on: createSprClient, syncWallet, buildDepositTransaction, buildRegistrationTransaction, the types LocalKeys and ShieldedAddress, Wallet, AssetRegistry, ProofInputUtxo, toProgramWalletUtxo, initializePoseidon, poseidon, hashBytes, solanaOwnerIdentity, kitAddress, addressEncoder, and the constants DEFAULT_TREE_ID, NATIVE_SOL_MINT, SHIELDED_POOL_PROGRAM_ID, SOL_INTERFACE and SPL_TOKEN_PROGRAM_ID.