Guides

Write a hook

A hook is written as one object and checked by defineHook. This guide writes one for a real instruction, Kamino's deposit_reserve_liquidity, field by field, then simulates it and publishes it with the SDK. The result is the same record as the launch hook kamino.supply, under a name of your own.

To build a hook by pointing at an IDL in the browser, see Publish a hook from an IDL. The hook schema lists every field and limit.

Start from the instruction

A hook describes one instruction of a program that exists. Before writing anything, lay the instruction out: its program, its data, and its accounts in order.

deposit_reserve_liquidity on Kamino Lend, KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD:

  • Data: an 8-byte discriminator, a9c91e7e06cd6644, then liquidity_amount as a u64.
  • Accounts, in order: owner (signer), reserve, lending market, lending market authority, reserve liquidity mint, reserve liquidity supply, reserve collateral mint, the user's source liquidity account, the user's destination collateral account, the collateral token program, the liquidity token program, the instructions sysvar.

The work of a hook is to say, for every byte and every account, whether it is fixed for good or filled by each run, and where Pook stands in for the user.

Write the definition

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

const KAMINO_LEND = 'KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD'
const TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'
const INSTRUCTIONS_SYSVAR = 'Sysvar1nstructions1111111111111111111111111'

export const supply = defineHook({
  // What the registry shows
  id: 'yourname.supply',
  protocol: 'kamino',
  protocolName: 'Kamino',
  label: 'Supply',
  description: 'An asset in, its Kamino deposit token out.',

  // What it calls
  kind: 'flow',
  targetProgram: KAMINO_LEND,
  instructionName: 'deposit_reserve_liquidity',
  discriminator: 'a9c91e7e06cd6644',

  // What may go in and come back. null: the caller names the mint.
  mintIn: null,
  mintOut: null,
  wrapSolIn: true,
  unwrapSolOut: false,

  // The instruction data, with the amount left as a slot
  dataTemplate: {
    baseHex: 'a9c91e7e06cd6644' + '00'.repeat(8),
    slots: [
      { name: 'liquidityAmount', kind: 'amount_in', offset: 8, length: 8, type: 'u64', label: 'Liquidity amount' },
    ],
  },

  // The accounts, in the order the program reads them
  accountsTemplate: [
    { index: 0, name: 'owner', role: 'stage_authority', writable: false, signer: true },
    { index: 1, name: 'reserve', role: 'caller_supplied', writable: true, signer: false },
    { index: 2, name: 'lendingMarket', role: 'caller_supplied', writable: false, signer: false },
    { index: 3, name: 'lendingMarketAuthority', role: 'caller_supplied', writable: false, signer: false },
    { index: 4, name: 'reserveLiquidityMint', role: 'caller_supplied', writable: false, signer: false },
    { index: 5, name: 'reserveLiquiditySupply', role: 'caller_supplied', writable: true, signer: false },
    { index: 6, name: 'reserveCollateralMint', role: 'caller_supplied', writable: true, signer: false },
    { index: 7, name: 'userSourceLiquidity', role: 'stage_in', writable: true, signer: false },
    { index: 8, name: 'userDestinationCollateral', role: 'stage_out', writable: true, signer: false },
    { index: 9, name: 'collateralTokenProgram', role: 'program', address: TOKEN_PROGRAM, writable: false, signer: false },
    { index: 10, name: 'liquidityTokenProgram', role: 'caller_supplied', writable: false, signer: false },
    { index: 11, name: 'instructionSysvarAccount', role: 'sysvar', address: INSTRUCTIONS_SYSVAR, writable: false, signer: false },
  ],

  // Instructions that must sit beside the run
  companionInstructions: [
    {
      programId: KAMINO_LEND,
      instructionName: 'refresh_reserve',
      discriminator: '02da8aeb4fc91966',
      position: 'before',
    },
  ],

  // The inputs the run screen shows
  formFields: [
    { name: 'mintIn', kind: 'asset_in', label: 'Asset to supply', required: true },
    { name: 'amountIn', kind: 'amount', label: 'Amount', required: true },
  ],
})

defineHook validates the object and returns it frozen. A field that is missing or out of range throws, naming the field.

The parts, one at a time

Name and kind

id is the name people run the hook by: lowercase, in the form protocol.action, 2 to 48 characters. A name can be published once, by whoever publishes it first.

kind is flow when the action takes an asset and returns one in the same run, as here. It is seat when the action leaves a position open at the protocol that someone has to own. Seats covers that case.

Mints

mintIn and mintOut say what may go in and come back. An address fixes the mint. null leaves it to the caller, which suits an instruction that works for many assets: this one supplies any asset Kamino has a reserve for and returns that reserve's deposit token.

wrapSolIn: true lets a holder supply native SOL to a protocol that takes wrapped SOL: the program wraps the amount before the call. unwrapSolOut does the reverse for what comes back.

The data template

baseHex is the instruction data as the program expects it, with the per-run values zeroed. A slot marks where one of those values goes.

Slot kindFilled with
amount_inThe run's amount in, the amount the proof fixed.
min_outThe run's minimum out.
caller_argA value the caller supplies for this run.
seat_argA value the caller supplies on a seat hook.

Here there is one slot: liquidityAmount at byte 8, 8 bytes, the amount in. Mark the amount argument as amount_in whenever the instruction has one. It is what makes the protocol take exactly the amount the holder proved.

The account template

List every account in the instruction's own order and give each a role.

roleThe account passed at run time
stage_authorityPook's stage. It signs, standing where the user's wallet would.
stage_inThe stage's token account holding the amount in.
stage_outThe stage's token account the result arrives in.
seat_pdaThe seat. Seat hooks only.
payerThe relayer. Seat hooks only, where the protocol needs rent paid. Relayers submit runs of a hook with this slot only when it is a launch hook.
fixed, program, sysvarThe address you give, the same in every run.
caller_suppliedAn account named for each run.

The pattern for almost any instruction is the one above. The account that signs as the user becomes stage_authority. The token account the user pays from becomes stage_in. The token account the user receives into becomes stage_out. Addresses that never change are fixed. What depends on the asset or the market, here the reserve and its mints and vaults, is caller_supplied.

The program refuses to pass its own accounts to a hook's call, so a hook cannot reach the authority that owns holders' notes. Hooks lists what is refused.

Companions

Some instructions need another beside them. Kamino wants refresh_reserve in the same transaction before a deposit. A companion names the program, the instruction's discriminator and whether it comes before. The relayer adds it, and the Pook program checks it is there.

Form fields

formFields describe the inputs the hook's run screen shows and the names pook.run takes them by. They are stored with the registry's record of the hook, and change nothing on chain.

The same holds for the label, the description, the instruction's name and the names of the slots and accounts: publishing through the SDK or the builder keeps them for the hook's page. A hook published straight to the program has none, so its page names its accounts by position and role and builds its form from its slots.

Simulate

Simulation sends the hook's instruction to the chain, with the stage in place and a sample amount, without publishing anything.

TypeScript
const result = await pook.simulateHook({
  hook: supply,
  sampleAmountIn: '1000000',
  sampleMintIn: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  sampleArgs: {
    reserve: '<the reserve>',
    lendingMarket: '<its lending market>',
    // one entry for each caller_supplied account, by its name
  },
})

result.passed          // true when the program accepted the instruction's shape
result.computeUnits    // what the call used
result.accountCount    // accounts in the call
result.estimatedTxBytes
result.logs            // the program's own log lines
result.error           // when it did not pass

sampleArgs gives an address for each caller_supplied account, keyed by the account's name. The logs are the target program's own, so a wrong account order or a wrong discriminator reads there exactly as the program reports it.

Publish

TypeScript
const published = await pook.publishHook({ hook: supply })

published.tx.status // 'confirmed'
published.signature // the transaction

The connected wallet signs one transaction and becomes the hook's author. It pays the rent of the hook's account. From then on every run through the hook pays that wallet the author's share.

A published hook cannot be edited or removed. To change one, publish a new hook under a new name.

Run it

Your hook runs like any other, from its page in the registry or with pook.run. Two things differ from a launch hook, which has a resolver that works them out. The caller names each caller_supplied account in args, by the account's name. And when the hook returns an asset, the caller names minimumOut, the least it accepts back in the out asset's smallest unit. The program fails the run if less arrives. The fees are worked out from that amount, and leaving it out is refused with VALIDATION_ERROR.

TypeScript
await pook.run('yourname.supply', {
  in: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  out: 'B8V6WVjPxW1UGwVDfxH2d2r8SyT4cqn7dQRK6XneVa7D',
  amount: '1000000',
  minimumOut: '<the least kUSDC you accept>',
  args: {
    reserve: '<the reserve>',
    lendingMarket: '<its lending market>',
    // one entry for each caller_supplied account
  },
})

On the hook's run screen the same value is the Minimum out field.

What makes a hook refuse

WhenWhat you seeWhy
defineHookA ZodErrorA field is missing, too long or not in its allowed set.
PublishingHOOK_ALREADY_EXISTS, or HookAlreadyPublished from the programThe name is taken.
PublishingInvalidHookDefinitionThe record breaks a rule of the program: a flow hook with no asset in, a seat account on a flow hook, more than one remaining-accounts slot, or a target the program will not call.
A runDataSlotOutOfBoundsA data slot reaches past the end of the template.
A runCallerAccountsMismatchThe accounts given for a run do not match the caller slots.
A runForbiddenHookAccountOne of the accounts given is Pook's own.
A runMissingCompanionInstructionA companion the hook names is not in the transaction.
A runMintConstraintViolatedThe run's assets are not the ones the hook allows.

The hook schema gives the full list of rules.