Skip to content

Custom Layer | Hook

Hooks allow developers to add customization to a pool by having callbacks in the various stage of the lifecycle. There are 10 possible callbacks before / after 5 key actions which happen in an AMM. The key actions include pool initialization, swap, addLiquidity, removeLiquidity and Donate

Type of callbacks

Initialize a pool with hook

In order to initialize a pool with the hook, there are a few pointers to note:

  1. Have the hook contract deployed (no address mining is required) and the callback required defined in getHooksRegistrationBitmap method
/// @dev Below indicate `beforeSwap` callback required
function getHooksRegistrationBitmap() external pure override returns (uint16) {
  return _hooksRegistrationBitmapFrom(
    Permissions({
      beforeInitialize: false,
      afterInitialize: false,
      beforeAddLiquidity: false,
      afterAddLiquidity: false,
      beforeRemoveLiquidity: false,
      afterRemoveLiquidity: false,
      beforeSwap: true, // beforeSwap enabled
      afterSwap: false,
      beforeDonate: false,
      afterDonate: false,
      noOp: false
    })
  );
}
  1. When initializing the pool, specify the hook contract in the pool key and remember to call hook.getHooksRegistrationBitmap() in parameters so the callback are saved in PoolKey.
key = PoolKey({
  currency0: currency0,
  currency1: currency1,
  hooks: hook, // hook contract address 
  poolManager: poolManager,
  fee: uint24(3000), // 0.3% swap fee 
  // parameters include hook callback and tickSpacing: 10
  parameters: bytes32(uint256(hook.getHooksRegistrationBitmap())).setTickSpacing(10)
});
 
/// Initialize the pool 
poolManager.initialize(key, Constants.SQRT_RATIO_1_1, new bytes(0));

FAQ(s)


Q1: Can the hook contract be at any address?

Hook can be deployed on any address. The callback permission required are defined in poolkey.parameters and are immutable. Any changes to callback permission will require a new pool.


Q2: Can you explain more about poolKey.parameters?

poolKey.parameters is a bytes32 parameters which includes hook callback required and the format is as follows:

// first 16 bits for hooks callback 
[0 - 15]: reserve for hooks callback
 
// other bits can be used by each pool type. eg.
[16 - 39] concentrated liquidity pool tick spacing 
[16 - 31] bin pool bin step  
[16 - xx] other new pool type config

For example in ICLHooks.sol, if the bit 0 is has the value of 1, beforeInitialise callback is required.

uint8 constant HOOKS_BEFORE_INITIALIZE_OFFSET = 0;

However, all of this are made easier for you! eg. To define callback required in parameters simply overwrite getHooksRegistrationBitmap in your hooks and call hooks.getHooksRegistrationBitmap shown above

List of hooks

Visit https://github.com/pancakeswap/pancake-v4-hooks for more hooks example