Uniswap Hook Incubator — Limit Orders Part1 & Part2 #4

Zuhaib Mohammed
2 min readSep 11, 2024

--

The example used to understand the use of hooks in this chapter involves building a hook that executes ‘Take-Profit Orders,’ where a user wants to sell a token once its price reaches a specified level. For instance, if ETH is currently trading at 3,500 USDC, we can place a take-profit order such as, ‘Sell 1 ETH when it reaches 4,000 USDC.’

Before implementing the hook, it’s important to consider which hooks best serve our purpose. We can use either beforeSwap or afterSwap for the take-profit order, but we prefer afterSwap since, once a swap is performed, the tick values change. Executing the swap beforehand might interfere with the user’s actual trade. The correct approach is to wait for the actual swap, then trigger the pending trade based on the updated tick value.

Apart from placing the order, two other essential functionalities — canceling the order and redeeming the tokens — must also be implemented.

Since we don’t have any prior tick value at the beginning, we can initialize the lastTicks value in the afterInitialize hook.

Security Issues

Working with hooks can be tricky, as issues like recursion or reentrancy can arise. While this isn’t a core issue with UniswapV4 itself, developers can inadvertently introduce these problems by following unsafe coding practices. Adding the following line of code can help prevent recursion issues in our implementation.

if (sender == address(this)) return (this.afterSwap.selector, 0);

Full code and walkthrough coming soon,

Thanks for Reading ! Stay Tuned for the updates !

Connect with me: https://linktr.ee/zuhaib44

--

--