
Developer Notes: The Birth of Aggregator Hook
TechFlow Selected TechFlow Selected

Developer Notes: The Birth of Aggregator Hook
This article will explore the origin and operational mechanism of Aggregator Hooks, as well as the profound impact it brings to Uniswap and the broader DEX ecosystem.
Authors: Attens & Bruce
Edited by: Lisa, DODO Research
This (Aggregator Hook) is great for other DEXs—adding a piece of code enables access to another "super aggregator," so why not? It's also great for Uniswap, which can seamlessly and costlessly absorb liquidity from other DEXs for its own use.
— Attens, DODO DEV Leader
Uniswap V4's release quickly sparked a storm among developers: the Hook architecture brings rich extensibility to traditional, rigid templated pool contracts. The Uniswap V4 Hook interface covers nearly the entire lifecycle of pool-funds interaction, providing fertile ground for developer brainstorming. From relatively simple TWAMM Hooks introducing time-weighted oracles for protection, to LimitOrder Hooks showcasing even greater potential, or cross-chain trading Hooks born at hackathons—various Hooks are sprouting like mushrooms after rain.
As Defi practitioners, we naturally wouldn't stay on the sidelines. At ETH Global in November, we proposed a new Hook design and were honored to win the "Best Use of Hook" award. Due to its high versatility, it can serve as a code component embedded within various liquidity pool contracts—we named it: Aggregator Hook.
The Aggregator Hook aims to act as a "bridge," directly linking market liquidity to Uniswap V4 pools; while leveraging the "Just-in-Time (JIT)" principle to dynamically manage liquidity funds—injecting liquidity before trades and withdrawing afterward—to minimize impact on the original pool. This integration allows LPs to manage funds with unprecedented convenience, leveraging Uniswap’s robust architecture while tapping into liquidity across the broader DEX ecosystem.
This article explores the origin, operational mechanism, and profound implications of Aggregator Hook for Uniswap and the wider DEX ecosystem.
I. The Birth of Aggregator Hook
Initially, this idea stemmed from a simple need: we had a highly efficient quoting DODO V3 pool—could we migrate this system onto Uni V4 via Hook?
While researching LimitOrderHook, we gained inspiration: Hooks can hold custody of funds. An unremarkable discovery—but one that opened Pandora’s box. If “a Hook is an independent contract” and “a Hook can hold custody of funds,” could we deduce: a Hook itself could be a pool? And suppose we have a contract that might be another DEX’s pool, or has other logic (e.g., a crowdfunding pool or transaction escrow system), but simultaneously satisfies Uni V4’s requirements for Hook contracts and implements corresponding Hook functions—then it can also function as a Hook.
Thus emerged our initial concept: Aggregator Hook is a pool-centric Hook—both a DODO V3 pool and a Uni V4 Hook. We aimed to migrate the quoting system into Hook functions, using JIT so users get identical quotes when trading on Uni V4 versus DODO V3. Our initial approach was natural: we had price caps, floors, and sell quantities—convert price bounds into ticks, fill liquidity according to sell quantity, execute trade, success—wait! We encountered significant slippage.
We tried numerous combinations of tickSpacing and Fee settings, applied various tick configurations based on price bounds—the best result still showed a 0.2% price difference compared to native DODO V3 pricing, enough to degrade user experience. Clearly, this discrepancy arose from algorithmic differences between DODO V3 and Uni V4. To resolve this gap, two doors stood before us:
-
Front door: Fully account for algorithmic differences between Uni V4 and DODO V3, derive a liquidity remapping formula
-
Back door: Use fromAmount to obtain a price from DODO V3, then directly determine liquidity parameters using this price to eliminate slippage
After brief experimentation, we毫不犹豫 chose the back door! While we believe the first solution—if analytically solvable—could yield an elegant little paper, alas, we aren’t mathematicians. The second approach clearly introduces higher gas costs due to an extra pricing query—but its advantages are equally clear: the function deriving price from fromAmount isn’t unique to DODO V3. All Dex pools have similar pricing functions: getAmountsOut, get_dy, querySellTokens… Regardless of naming, there’s always a way to retrieve a quote from a contract. Thus, this Hook component isn’t limited to DODO V3—it can integrate into any Dex pool, or even non-pool systems like solver-based pricing modules. Any contract possessing liquidity with a pricing mechanism, by adding this Hook code, can become a Hook without affecting its standalone functionality, and through Hook-Pool, form a valid Uni V4 pool. Ideally, Uni V4 routing could route not only to traditional Uni V4 pools but also to these trick pools we create.
We felt excited—this is great news for other DEXs: add one piece of code and gain access to a "super aggregator"—why wouldn’t they? For Uniswap too, it’s beneficial: it can effortlessly and costlessly absorb liquidity from other DEXs for its own use.
Of course, this grand vision depends on what routing algorithm Uni V4 ultimately adopts and how it prioritizes these pools—a separate topic perhaps worthy of another article. But due to Hook’s nature, regardless of the routing method, it must consider Hook impacts since operations within Hooks directly affect final user prices.
We hope you recall our foundational assumption: we obtain a quote, then find a liquidity provisioning method that projects this quote within Uni V4, ensuring users receive identical prices whether trading via Uni V4 or directly through the Hook-Pool.
Ultimately, we succeeded. That’s why we formally call it “Aggregator Hook.”
II. Aggregator Hook Operational Flow
When discussing Aggregator Hook’s actual implementation, you’ll realize the magic is merely a coin hidden in the performer’s sleeve:
-
User initiates swap call
-
Triggers beforeSwapHook, where Hook performs three actions:
-
Remove all remaining liquidity from the pool (Hush! It’s the key point.)
-
Use user’s fromAmount to fetch native trade price from Hook-Pool
-
Calculate modifyPosition parameters via trade price, then provision liquidity
-
swap call ends
-
Outer Router handles user transferIn and transferOut
As shown below:

As user orders approach, the BeforeSwap hook activates, injecting liquidity into the Uniswap V4 pool. Added liquidity accommodates incoming orders, enabling successful execution. However, instead of withdrawing this liquidity post-trade, it remains in the pool—forming part of the first trade’s complete lifecycle.
The innovation lies in handling subsequent trades. Before the next trade begins, the BeforeSwap hook triggers again. Its primary task: remove any excess liquidity left over from the previous trade.
Once residual liquidity is withdrawn, LPs repeat the initial step: analyzing new trade demands and precisely adding liquidity across two price ranges. This meticulous provisioning ensures optimal utilization and highest efficiency placement—reducing slippage and improving overall trade execution within the Uniswap ecosystem.
III. Mechanism and Code Analysis
Save the best for last.
When to Remove Liquidity
First, we explain why removing liquidity is necessary—based on two considerations:
-
Within this Hook, the Hook-Pool is primary—liquidity should remain concentrated there as much as possible.
-
Price remapping calculations are simpler when the pool holds no excess liquidity.
In JIT, common practice involves injecting liquidity before user swaps and withdrawing afterward. Initially, we thought similarly: add liquidity in beforeSwapHook, remove in afterSwapHook—logic seemed smooth—yet Hooks always bring surprises. Let’s examine Uni V4’s latest testRouter structure:



See? The core obstacle blocking our grand plan: users only exchange tokens with poolManager after manager.swap completes. This means: afterSwapHook doesn’t truly occur “after swap”—we cannot handle liquidity removal within afterSwapHook. The removeLiquidity function loses its ideal timing, leaving us scrambling, forced to awkwardly place this abandoned actor alone on a line right after swap function calls in tests, looking clownishly out of place. Desperate, we considered manipulating swap’s hookData or modifying testRouter; then, one of the golden apple makers, Uni’s @ken and their Dev @saucepoint, gave us crucial advice: remove liquidity at the start of the next trade.
This solution is clearly optimal for us. First, it requires minimal code changes—we were only 7 hours from the hackathon presentation. Second, it no longer relies on unpredictable testRouter behavior for automated liquidity removal. Just wait briefly—when the next user arrives, leftover funds return exactly as expected.
Of course, the Hook-Pool owner can withdraw liquidity from Uni V4 at any time—not necessarily waiting for the next trade. The following remove function is public:


Additionally, to protect funds, we use the beforeModifyPosition Hook to verify msg.sender attempting to modify liquidity

How to Fill Liquidity
Uni V4 uses the same calculation formulas as Uni V3, although Uni V4’s pool became a library. We only consider filling unilateral liquidity within an extremely narrow tick interval—for example, between tick -46874 and tick -46873—to minimize cross-tick consumption. By studying code and related analytical articles, one can derive the following formula using Uni’s algorithms:

Corresponding code:

But this isn’t the end. Observing Uni V3/V4 liquidity distribution reveals:

After liquidity provisioning, only 50% of the price range within that segment meets our unilateral trading needs. If selling token0 for token1, the selected tick interval [tickLower, tickUpper] corresponds to price range [priceLower, priceUpper]. During trading, expected price movement descends toward the target price—but this target price must not fall below (priceLower + priceUpper)/2. If it drops below (priceLower + priceUpper)/2, it manifests as price_next exceeding the lower bound, requiring correction at the lower tick limit. Similar corrections apply to opposite-direction trades. Example:

Code implementing this correction:

Price Balance
So far, we’ve delivered on most promises. Aggregator Hook is good, but not flawless. The core limitation concerns trade direction. This restriction manifests as follows:
-
Current V4 pool price sits at tick 0’s corresponding price, denoted currentPrice
-
When targetPrice > currentPrice, the V4 pool can only execute swap 1 to 0
-
When targetPrice < currentPrice, the V4 pool can only execute swap 0 to 1
There’s actually an intuitive explanation for this constraint. View targetPrice as the market price and currentPrice as the price generated by trades within the legacy Dex pool. When the Dex pool price is lower than market price, the pool restricts users to buying token0 to raise the price toward equilibrium; when the Dex pool price exceeds market price, the pool restricts users to buying token1 to lower the price toward equilibrium.
This condition expressed in code:

IV. In-depth Discussion and Outlook
We believe Aggregator Hook’s greatest significance lies in redefining Hook design perspectives.
Previously, Hook designs followed a Uni V4 Pool-centric view—considering what new functionalities Hooks could bring to “trading.” Aggregator Hook offers a completely new angle. Due to Hook independence, such contracts don’t need to be “All in Hook”—the Hook may represent just one feature: building a bridge to Uni V4 pools—while the contract itself performs any operation, making “trading” and integration with Uni V4 merely components of its broader functionality.
A simple example: some small projects claim they’ll allocate a portion of raised funds and tokens to Uniswap after crowdfunding. In the Uni V3 era, crowdfunding and Uni V3 contract operations were asynchronous—users relied solely on project teams for fund transfers. But with Uni V4 Hook: why not leverage Hook independence to directly integrate liquidity provisioning within the same contract? Even executing liquidity additions upon user deposits (though gas-heavy, some users may value such transparency). It sounds crazy—but it hints at infinite possibilities for Hooks.
Aggregator Hook’s biggest limitation is its gas consumption per trade. Normal Uni V3 gas usage is around 120k; due to multiple liquidity add/remove operations, single trade gas reaches 420k–550k via forge snapshot—far exceeding normal swap behavior. This inevitably confines such integrated pools to L2s insensitive to storage gas or chains with very low gas prices. Tricks pay the price of being tricks—it’s reasonable.
There’s room for improvement, particularly regarding liquidity provisioning mechanics. Two possible directions—one simpler, one more complex. Starters first:
-
In the Price Balance section, we discussed trade direction constraints. If maintaining our liquidity removal scheme, rules governing targetPrice and currentPrice cannot change—but tick0 and limitTick need not be unequal. Only when limitTick = tick0 does liquidity provisioning become bilateral, requiring revised formulas for calculating liquidity amounts. This adjustment slightly relaxes trade direction requirements—by one tick.
More complex:
-
Since we’re already considering bilateral liquidity provisioning, why not go all the way—stop forcing liquidity removal altogether? Only allow removeLiquidity when the Hook-Pool manager deems necessary. Further reduce user swap gas costs, making Aggregator Hook more “usable.” Of course, this likely introduces significantly more complex liquidity provisioning algorithms than the simpler alternative above.
Current source code for Aggregator Hook pools:
https://github.com/Attens1423/Aggregator-Hook
To visually observe trade results, we added afterSwap Hook call output printing—but this isn’t mandatory. Numerous intermediate values are printed internally; use forge test to witness Aggregator Hook’s performance.
DODO V3 may become the first pool to eat the crab. Our next step is integrating Aggregator Hook into DODO V3 pools. Some essential pool reserve and state updates remain. After completing all tests, we will open-source it, realizing our original Hook-Pool vision.
Join TechFlow official community to stay tuned
Telegram:https://t.me/TechFlowDaily
X (Twitter):https://x.com/TechFlowPost
X (Twitter) EN:https://x.com/BlockFlow_News














