Understanding the New Iteration of Uniswap – A Primer on Uniswap v4 & Hooks

Introduction

When you think of DeFi, the first thing that comes to mind is likely Uniswap. Since pioneering automated market makers (AMMs) more than five years ago, Uniswap has gone on to lead the paradigm shift into on-chain exchanges (DEXs). DEXs now make up almost 15% of spot volume generated by their counterparts, CEXs and Uniswap make up ~50% of that DEX volume.



While this is impressive and shows how far DEXs have come in just a few years, their dominance still wanes relative to CeFi (e.g., CEXs) and especially TradFi, which facilitates hundreds of billions of dollars more in weekly volume than Uniswap.

What gives? Why aren’t DEXs more dominant in today’s landscape?

Sure, maybe it’ll take a little more time for DEXs to gain dominance over traditional trading and settlement institutions, but haven’t people already learned from the FTX and various other CEX fiascos that DEXs have zero counterparty risk, especially to bad actors?

Why haven’t we seen significant improvements in DEX spot volume (relative to CEX spot volume) since major CeFi fallouts like the FTX blow-up in late 2022?

The answer might be that DEXs don’t offer significant noticeable advantages over CEXs.

After all, trading on DEXs is expensive – you’re constantly getting frontrun (leading to worse execution costs), you need to pay gas fees to approve your tokens for trading and then executing the trade itself, and trading on DEXs is slow – e.g., blocktimes on Ethereum are ~12 seconds. Now contrast this with CEXs – since trading is centralized and there’s no public mempool, your transactions aren’t frontrun, you don’t pay any gas fees since trades are effectively entries onto said CEXs off-chain spreadsheet, and trading is near instant, as trades are executed on a high-performance centralized database running on a single server (e.g., @Coinbase uses PostgreSQL as its primary database).

However, with innovations in chain abstraction, MEV infrastructure, and other scaling solutions (all of which we’ll dive into in future posts), gas fees have either been abstracted away completely or compressed to near zero, frontrunning MEV is being mitigated, and confirmation times have reached subsecond latencies – all of which allow for a more seamless DEX UX with faster, cheaper, and better-executed trades.

Okay – so maybe the UX of trading on DEXs will soon be on par with trading on CEXs. But there’s still a missing piece – a missing piece that will finally give DEXs an edge over their counterpart. And to avoid any doubt, this edge doesn’t come through “decentralization.” You see, decentralization itself isn’t a benefit – it’s a means to an end. And that end is censorship resistance. But let’s be honest – a tiny subset of traders care about that. It’s not every day that a national state puts a target on your back and cuts you off from the legacy financial system. DEXs cannot compete on levels of decentralization relative to CEXs – they just cannot. They can, however, compete on things like democratizing liquidity provision to the masses (something that Uniswap v2 did with its constant product AMMs) or composability (e.g., using tokens that represent the liquidity you provide on an AMM as collateral to take out a loan on-chain), etc. But so far, this hasn't been enough to siphon away market share from DEXs.

So, where does this edge come from if it isn’t decentralization?

Uniswap v4 – Ushering in the New Age of DEXs 

We believe Uniswap v4 is the answer. V4 of the Uniswap protocol marks the new iteration of DEX design – from increased gas efficiency to endless customizability – this iteration of the protocol has what it takes to revolutionize the UX of trading on DEX and increase the surface area of DEX innovation exponentially. 

Uniswap Hooks 

Without a shadow of a doubt, hooks are the defining characteristic of Uniswap v4. This is because they completely change the landscape of what’s possible with DEXs today.

With previous Uniswap iterations (e.g., v2 and v3), the protocol was more opinionated – e.g.,  before a swap on the protocol, the price on said AMM was stored in a smart contract. This way, prices for any given Uniswap AMM were accumulated before swaps occurred, allowing oracles to be built on top of the protocol. However, this resulted in higher gas costs for swappers (traders). This inbuilt protocol design (of price accumulation) increased the gas cost the trader had to bear by ~10% for a swap on the Uniswap protocol. This was not ideal – if an AMM for a memecoin paired against USDC was spun up, the chances of a price oracle being needed for this pair were minimal. Memecoins are highly volatile, often lack liquidity depth on-chain, and are not taken seriously. All of these factors combined would mean that DeFi projects like lending markets would likely not integrate said memecoin into their protocol (and, hence, a decentralized price oracle would become obsolete for this memecoin). So, for no reason whatsoever, traders of said memecoin would pay higher gas costs.

This changes with Uniswap hooks – innovation and value judgments are outsourced for the market to decide on.

Effectively, every pool can be customized in the way imaginable – accumulate prices before swaps or don’t; it’s up to you. This example of why hooks are needed might seem trivial, but it aims to convey a bigger picture.

So far, any innovations and/or value judgments were decided internally by the Uniswap protocol. For e.g., should pools default to accumulate prices before swaps? Should pools trade 24/7/365? Should pools have X, Y, and Z fee tiers to choose from?

You get the idea – each pool’s customization wasn’t in the hands of the beholder. The surface area for innovation was small. Developers were constrained by what they could do in the DEX design space. This is what Uniswap v4’s hooks change. Developers finally have control over their pools and can build customizations, applications, and features on top of their previously unimaginable.

Before discussing some potential use cases of hooks, let’s first understand what hooks are and when they’re used.

Simply put, hooks are external smart contracts connected to liquidity pools that can be called at four different action points: before or after creating a pool, before or after a position is modified by an LP, before or after a swap occurs, and before or after donate (e.g., you can give fees to LPs for being in a specific price range — interesting liquidity mining campaigns can be built using this customization). This’ll start to make more sense as we dive into potential use cases (examples) of Uniswap hooks. 

Hooks – Potential Use Cases

  1. NYSE trading hook: imagine there’s some token issued on the blockchain that can only be, for regulatory reasons, traded during NYSE hours (a regular NYSE trading session from 9:30 AM to 4:00 PM ET and is closed on weekends and specific holidays). The liquidity pool for this token has a hook that’s called before any swap to see if the trade falls within NYSE hours, and if it does, the trade goes through. E.g., if the trade occurs on Christmas or Friday after 4 PM ET, it will be reverted. You can extend this use case to something more esoteric – like having trading happen only in bullish environments (e.g. when BTC is up 10% WoW).

  2. Dynamic (custom) fees: currently, Uniswap v3 pools are limited to the following fee tiers for swaps: 0.01%, 0.05%, 0.3%, and 1%. Hooks allow you to customize the fees (e.g., set a fee tier of 5%) for your pool, even making them dynamic if you want. What use cases, apart from discovering the price sensitivity of your users/traders, are unlocked with this?

    i) You can price discriminate based on the trader/swap transaction. Generally, there are two types of orderflow – non-toxic (usually retail) orderflow and toxic orderlow (usually arbitrageurs). The latter orderflow contributes heavily to the losses of LPs. However, since toxic orderflow often originates from wallets with tens of thousands of high-frequency transactions, you can imagine a hook that charges fees to trade in said pool proportionate to transaction count and frequency to hopefully deter toxic flow to some extent. Of course, arbitrageurs are intelligent and can make a new wallet each time they interact (rebalance/arbitrage) with a pool. Still, you can envisage more sophisticated hooks that follow the general premise of deterring toxic orderflow (or internalizing MEV – more on this below) being built. Furthermore, MEV transactions (e.g., frontrunning a trade – like a sandwich attack) often spend a lot of gas to ensure their transaction is at the top of a block. By virtue of this characteristic (of MEV transactions), you can imagine a hook being built to charge more to traders who consume more gas, thereby disincentivizing MEV extraction from traders, leading to better execution prices for them [traders].

    ii) You can offer fee discounts to whales that induce price impact. Picture this: the liquidity in your pool is shallow, and a whale comes in and buys a ton of tokens, pushing its price up by double digits. Since the whale is already leaking a large percentage of the notional value of his/her trade, you offer a fee rebate/discount to offset this value leakage, thereby promoting price impact-inducing trades without an increase in underlying liquidity.

    iii) You can charge separate fees for buying and selling the token. Imagine charging zero fees to buy the token but relatively high fees to sell it – this, too, is enabled with hooks.

    iv) You can auction off the right to set the dynamic fee for your pool. Imagine a contentious (highly competed on) transaction to backrun (e.g., to arbitrage) a given trade on your Uniswap pool.  You can build a hook to auction off the right to make this backrun. Simply put, this means that all the MEV bots compete by setting higher fees (essentially bidding up the dynamic fee) for their backrun transaction until virtually all of the backrunning profit is shared with the LPs. A variant of this is discussed in the am-AMM paper. Alternatively, you can give the right to backrun a transaction to a benign actor, with the hook specifying that said trade can only go through if the transaction right behind it (the backrun) is carried out by said benign actor, which will later share the profit. The latter scenario, however, doesn’t maximize the profit due to a lack of competition.

    v) You can set volume-adjusted fees & capture a percentage of fees for your DAO. In times of high activity (volume), fees can be high, as traders are less price sensitive, and vice versa in times of low demand/activity, to ensure an incentive (lower fees) is present to stimulate volume. Furthermore, another hook can stipulate that a percentage of fees in high-volume environments get funneled back to the DAO, or for any given swap, 50% of the fees are used to buy back the DAO’s native token and burn it – the possibilities are limitless!

    vi) You can levy fees on liquidity deposits & withdrawals. Fees don’t need to be limited to traders – e.g., you can charge fees on LPs who withdraw liquidity and redistribute these fees to existing LPs in the pool. Apart from incentivizing long-term liquidity provision, this mechanism of “taxing” liquidity withdrawals can serve as a way to favor passive (retail) LPs over more active (institutional) LPs, as the latter rebalance liquidity more often.

  3. Yield optimization: imagine earning a yield on liquidity you deploy that’s out of range. For instance, if only half of the liquidity you deploy is in the trading range and is earning fees, the rest of the liquidity is lent out on Aave until this liquidity is needed on the AMM (e.g. if the trading range moves into where this liquidity was deployed). This especially favors retail LPs, as they’re the least sophisticated and rebalance their liquidity less often, meaning a lot of the time, some of their liquidity is not earning a yield, which is where these yield hooks (e.g., lending out unutilized liquidity on Aave) come in very handy.

  4. Limit orders & TWAMMs: with hooks, developers can enable traders to place limit orders (e.g., execute this trade at a price “X”). Furthermore, expanding upon the “yield optimization” hook above, you can extend this hook to earn a yield on capital that has been deposited into the protocol for a limit order but is currently unutilized (for instance, if deposit 100 USDC into the protocol to buy wBTC when it’s at $100,000, but the current wBTC price is only $60,000, there’s a long way to go until my limit order will be executed, so earning a yield on this 100 USDC in the meantime ameliorates the cost of capital, i.e., opportunity cost). Additionally, TWAMM (time-weighted average market maker) hooks can automatically split large swap orders into smaller ones that steadily get filled (executed) over time. This use case can be tailored to institutions like DAOs (for e.g., TWAMMs would have come in very handy for ENS DAO when it was offloading 10,000 ETH (~$16 million at the time) into USDC).

  5. Sponsor gas costs: we all know UX in crypto is broken. Gas costs are variable and denominated in tokens that you might not hold. A potential hook can be built to abstract away these complexities and sponsor gas costs on behalf of the user.

  6. Token-gated & KYCed pools: for example, an NFT community issues a token but only wants the holders of the NFT collection to trade the token. A hook can be created for this. This could be a way to prevent other NFT communities from trading the token and also drive demand for the NFT collection (as you need to buy the NFT to trade the token). Furthermore, imagine a real-world institution (e.g., a state-chartered bank) tokenizes treasury securities but only wants KYCed individuals to trade these RWAs – they can input a set of KYCed addresses that are allowed to trade the token to ensure non-KYC addresses cannot.

  7. Truncated & specialized oracles: as previously mentioned, pools by default don’t have prices accumulate in a smart contract before every swap. Some pools, however, may choose to do so but in different ways to create specialized oracles. For example, a hook can be built to create a truncated price oracle, which calculates the price of an asset in a pool before every swap using a geometric mean formula and then truncated (meaning that the calculated price can only move up or down to a certain extent in each block), subsequently avoiding any price manipulation (as the oracle smoothes out the price impact of large trades) and creating more resilient price oracles for a given asset. Of course, different assets require different oracles – so the design landscape for oracle creation with hooks isn’t limited to any one design. Some oracles can calculate a 3h trailing mean price, and some can have a rudimentary design to save on gas costs if oracle manipulation is not anticipated (e.g., for long-tail assets).

  1. Stop losses: studies show that ~50% of Uniswap LPs are unprofitable. What’s even more pernicious and unfortunate is that some LPs don’t even know that they’re unprofitable as an LP due to how impermanent loss works. A great hook, therefore, could incorporate impermanent loss (or even LVR) calculations to create a profitability methodology that allows LPs to create stop losses for their positions. 

Gas Optimizations

While Uniswap hooks are the star of the show in terms of the v4 protocol upgrade, the upgrade also brings numerous gas optimizations that drastically decrease the cost of trading and building on the protocol. This post will cover the major ones below. 

Singleton Pool Manager

Previous iterations of Uniswap have had a factory-type pool creation mechanism, wherein each pool created was a separate smart contract that lived independently of the other contracts [pools]. To put it plainly, Uniswap, with its v4 upgrade, is introducing a pool manager of sorts (a singleton pool manager, to be precise) that allows other pools to live in it and be assigned unique IDs. Essentially, instead of creating a new contract for a new pool, your new pool is “under” the singleton contract and is just assigned a new ID. Not only does this save on gas costs tremendously (Uniswap Labs claims that just this optimization alone cuts down on ~99% of the cost when creating a new pool), but it also makes Uniswap pools easier to reference by developers.



An interesting data point, as seen above, is that almost all (>90%) Uniswap pools created are still v2 pools. Is this because the cost of deploying a v2 pool is lower than that of a v3 pool? Maybe. But one thing is for certain: v4 blows the cost of deploying even a v2 entirely out of the water.

Considering that Uniswap v4 can be completely compatible with v2, in the sense that a v2-style hook provides liquidity across all ranges (so a de-facto constant product AMM pool), it’s hard to see how the thousands of v2 pools created weekly won’t deploy on v4 to save on gas costs and have hooks make UX and functionality greater for their traders. 

Flash Accounting & The Reintroduction of Native ETH

Apart from the singleton pool manager, Uniswap v4 also devised a way to increase gas efficiency further and improve trading UX by introducing flash accounting and reintroducing native (vanilla) ETH trading.



As seen above, instead of moving the tokens being traded in and out of pools after every swap like in v3, flash accounting transfers only the net balances (e.g., instead of routing ETH→USDC→USDC→DAI, the route will just be ETH→DAI).

Furthermore, accompanying flash accounting is the reintroduction of native ETH into the v4 upgrade, which enables trading directly with ETH. The current workflow for trading ETH is wrapping it to wETH and then approving it for trade on the contract. Native ETH (which is not an ERC 20 token) doesn’t need to be approved and is more gas efficient to trade by ~50% than wETH (native ETH transfers cost around 21,000 gas while the cost of ERC-20 transfers like wETH is around 40,000 gas).

Many of these gas optimizations also have second-order consequences that further amplify gas efficiency, like allowing traders to leave the tokens they purchased in the smart contract itself if they plan to sell it soon, which further cuts down on trading costs. 

Wrapping Up

While this post focused on breaking down the core components of Uniswap v4, it is in no way an exhaustive list of the use cases of Uniswap hooks and the optimizations and upgrades Uniswap v4 encompasses.

The fact is that Uniswap v4 opens up the DEX design space completely and stands to revolutionize decentralized exchanges through an unprecedented level of customization for liquidity pools, which also positions Uniswap as a strong contender against today’s centralized exchanges. 

When will Uniswap v4 hit mainnet? Likely sometime at the end of 2024. The v4 contracts have been already audited by firms and a bug bounty program that commenced at the start of this month is concluding at the end of this month (September). Another matter of anticipation is whether Uniswap v4 will also include the long-awaited fee switch. Some think this is imminent.

Ultimately, while Uniswap v4 marks a turning point in DEX design, the lingering question remains: will it succeed in bringing price discovery on-chain? We’ll have to wait and see – maybe all DEX adoption requires is a few more FTX-esque blowups.

Get 1:1 onboarding support