What are the principles and changes in Uniswap v4, an important piece of DeFi puzzle?

What are the key principles and changes in Uniswap v4, a vital part of DeFi?

Author: Joseph Xu

Layout: @createpjf

I. Preface

In 1620, a British ship named the Mayflower left England with 102 passengers and about 30 crew members on board, sailing towards America. They left England because they believed that the Church of England not only resisted reform but was also too corrupt, so they decided to cross the Atlantic to North America, where they would establish their own new immigrant community.

In July 2017, Hayden Adams was fired by his first employer Siemens after graduating from college. At that time, he was still a mechanical engineer with no blockchain development experience. In August 2018, in the 13th month of Hayden’s unemployment, Hayden and his partners completed the development of Uniswap v1 and launched it on the Ethereum mainnet, becoming one of the most indispensable pieces in the DeFi world. And 48 hours before the writing of this article, Uniswap released their fourth iteration. We browsed their whitepaper and contract code for the first time, trying to analyze the two-year-long update and compare it with the previous generation.

II. Uniswap’s Persistence

To be frank, the v4 contract is not yet in a fully developed state, and its readability and referenceability have been somewhat affected. However, we can still confirm that v4 has retained many features that have been proven effective in previous generations:

  • The constant product formula x*y = k is still in use;
  • The limit order liquidity is still based on the tick scale system;
  • Liquidity distribution is still horizontally distributed within the limit order range, and the liquidity depth of each pool is still the result of stacking all the liquidity in the market;

It can be said that after two years of market validation, Uniswap v3 has proven its advantage in capital utilization, and the extremely creative design of limit order liquidity alone is still used in v4.

III. Uniswap’s Innovation

Combining the whitepaper and contract code, we are pleased to find that v4 has completed many innovations and changes based on the above persistence, and these innovations mainly focus on the following four aspects:

  • New contract structure
  • Clever ledger design
  • More developer freedom
  • More protection for liquidity providers

Next, we will discuss these four aspects in detail from their design and engineering implementation:

3.1 New contract structure

Those who are familiar with the Uniswap code in previous versions know that the factory-pool contract structure, which has been used since v1, is the most widely used contract structure in the DeFi world. However, Uniswap decided to abandon this structure in v4 and introduced a new singleton contract structure, which aims to minimize gas consumption in creating liquidity pools and cross-pool (contract) calls.

We can see that in v4-core, only one contract, PoolManager, bears the core business logic, and PoolManager will be responsible for all liquidity calculations of the protocol, using the PoolKey field to index the corresponding currency pair market, while the AMM curve and liquidity-related calculations are abstracted to libraries contract.

In terms of contract structure, it is also worth mentioning that there have been significant changes in the storage and encapsulation of v4 liquidity positions:

  • In v2, because liquidity is distributed throughout the entire interval, the protocol uses homogeneous liquidity tokens (ERC-20) as proof of liquidity shares;
  • In v3, because of the introduction of limit-order liquidity, ERC-20 cannot be used to tokenize liquidity between positions, so non-fungible tokens (ERC-721) were used to encapsulate liquidity related data, and the NonfungiblePositionManager contract was used to manage liquidity-related operations.
  • In v4, we were surprised to find that liquidity positions are no longer encapsulated in tokenized form, but are managed by addresses.

It can be said that v3’s operation of encapsulating ERC721 certificates in the outer layer of liquidity position data is somewhat fragmented, while v4’s simple and direct binding of liquidity data to addresses may lose some of the composability of liquidity tokens, but there are great advances in gas economics and engineering aesthetics.

3.2 Ingenious Accounting Design

Flash Accounting can be said to be one of the most innovative designs in v4. Looking back at most of the liquidity protocols in the past market, their transaction and liquidity-related operations were accompanied by token transfers, and the process was nothing more than: security check -> calculate the amount of token conversion based on the set target -> update accounting data -> token transfer. However, v4 subverted this inherent coding logic and built a set of double-entry accounting books using the characteristics of callback functions.

What is double-entry accounting? Double-entry accounting is a method of accounting that uses the balance between assets and equity as the basis of bookkeeping. For each economic transaction, an equal amount must be registered in two or more interrelated accounts to systematically reflect the results of changes in fund movements. To give a simple example, if Alice borrows 1000 USDC from Bob, this economic activity will be recorded as follows:

From the table above, we can understand that: Assets = Equity – Liabilities. (The liabilities here are absolute values)

Let’s expand this example a bit more: Alice borrows 1000 USDC from Bob, Bob borrows 1 ETH from Carl, and Carl borrows 1000 DAI from Alice. Then our double-entry accounting table will be:

Obviously, the Uniswap liquidity pool is the object of traders’ borrowing, and the essence of the swap transaction is: after the transaction is completed, the liquidity pool and the trader are debt-free to each other. That is to say, when Alice tries to use 1800 USDC to buy 1 ETH, her relationship with the liquidity pool can also be recorded using double-entry accounting:

If at this moment the value of ETH in the ETH-USDC pool is exactly 1800 USDC, then after the swap transaction is completed, Alice and the pool are debt-free to each other, and the transaction can be successfully executed. In v4, each operation updates an internal net balance called delta, which can be regarded as the asset we mentioned above. Regardless of how many trading pairs the transaction crosses, each transaction must ensure that delta is zero when it is completed, otherwise it will be rejected. The newly added take() and settle() functions in v4 can be used to lend or deposit funds into the pool, and the protocol uses these two functions to enforce pool settlement and payments to ensure that there are no outstanding tokens between PoolManager and the caller at the end of the call.

Meanwhile, the protocol introduces ERC-1155, a semi-fungible token, and tokenizes the protocol’s debt. This means that when a trader or LP causes the protocol to owe them money in any operation, they can use the mint() function instead of take() to mint ERC-1155 tokens that correspond 1:1 to the assets they owe to receive a claim certificate with a fixed payoff. Incentives or derivative products based on this claim certificate will have great creative space, which also means that more liquidity will be left in the liquidity pool to provide traders with better liquidity depth and trading experience.

The combination of singleton contract structure and flash accounting makes it possible to route more efficiently between multiple v4 pools, reducing the cost of liquidity fragmentation.

3.3 More Developer Freedom

Hooks contracts are introduced in the v4-periphery repo. Hooks are code fragments that run at various points in the life cycle of a liquidity pool. Developers can use the provided BaseHook contract to build their own personalized transaction operations.

Uniswap v4 currently supports eight such hook callbacks:

  • beforeInitialize / afterInitialize
  • beforeModifyPosition / afterModifyPosition
  • beforeSwap / afterSwap
  • beforeDonate / afterDonate

This means that both LPs and traders can use customized hooks to execute business logic outside of core logic when operating in a liquidity pool. This undoubtedly provides the possibility of on-chain operations for many functions that were originally only possible through off-chain centralized services (such as Gelato Network):

  • Dynamic fees
  • Lower slippage swap splitting based on time-weighted average liquidity providers
  • On-chain limit orders
  • Custom on-chain price oracles, such as geometric mean oracles

On top of this, we can expand our imagination, and more scenarios have space for implementation:

  • Dynamic fees can be quantified based on the tick jump quantity generated by a single swap, rather than simply changing linearly based on time, to dynamically change fees and hedge against LP impermanent loss risk
  • On-chain quantitative trading and liquidity rebalancing strategies
  • Automatic fee reinvestment

Additionally, after introducing hooks, the number of pools is expected to increase significantly, which also makes the new design of singleton contract structure and compound accounting have more room to play, that is, different design updates are interrelated.

In summary, v4 continues to fulfill its mission as DeFi infrastructure, abstracting its core business logic from the complicated product demands, and handing endless imagination space to the community and developers, leading more people to participate. In this regard, Uniswap v4 does better than its predecessors and other competitors.

3.4 More incentives for liquidity providers

The lack of incentives and protection for LPs, which has been criticized by v3, has been improved in v4.

The built-in donate() method in PoolManager will allow users, protocol integrators, and hooks to pay fees to LPs in the pool with any token within the price range. This new mechanism can internalize MEV into the returns of LPs, so that LPs can benefit from MEV.

3.5 The shadow of other protocols

As the leader of the DEX track, Uniswap has always been at the forefront of AMM research, but other AMM competitors also have their own innovations in AMM research. We can also see the shadow of other protocols in the update of Uniswap v4:

  • The Singleton and Flash Accounting structures of Uniswap v4 are highly consistent with the Vault <-> Pool logic structure of Balancer v2. Both adopt a virtual ledger to uniformly account for multiple pools to reduce gas consumption in the transaction routing process.
  • Dynamic handling fees, on-chain native limit orders, and the use of ERC-1155 to concretize liquidity are features that have already been implemented in the just-launched Joe v2.1.
  • At the same time, as mentioned in section 3.4, by internalizing MEV, LPs can bring them into their own value cycle due to hooks, and by adding MEV auction/distribution protocols such as Flashbot or Eden Network, incentives can be doubly distributed to LPs who provide effective liquidity. In this regard, although Osmosis is not a product in the EVM ecosystem, ProtoRev developed and designed by Skip Protocol also has many things to learn from.

IV. Reflection

Undoubtedly, the current crypto market is in a deep bear phase, with liquidity shrinking and SEC regulation upgrading like a dark cloud over the entire market. At the same time, Uniswap’s trading volume has exceeded Coinbase’s for four consecutive months, and under regulatory pressure, excellent DeFi products have increasingly proven their value. To this day, we can still say without hesitation that Uniswap is one of the greatest use cases on Ethereum.

The story goes back to the beginning of this article. After 10 weeks of arduous sea voyage, the Mayflower arrived in the United States and anchored near Cape Cod, Massachusetts on November 21, 1620. When they arrived in North America, the winter of 1620 was particularly cold, and half of the 102 passengers died of illness. But the 50 survivors continued to take root and live in New England, North America. They have given birth to a large number of offspring, and their descendants have reached 35 million by the 21st century. Many famous American figures are among their descendants, including about one-fifth of U.S. presidents, such as President Adams and his son, President Roosevelt, and the Bush father and son presidents, as well as many figures in politics, law, culture, science, and religion. On the voyage of the Mayflower to North America, these passengers signed the famous Mayflower Compact at a meeting, which became the spiritual foundation of the U.S. Constitution 160 years after the founding of the United States.

In 2017, in the months when Hayden Adams had just lost his job, he learned to write smart contracts, and then met friends who shared his ideals, such as Vitalik Buterin, Philip Daian, Dan Robinson, etc. With their influence and help, holding on to the crypto spirit of anti-censorship and open source, Hayden built Uniswap, the Mayflower of the DeFi world. And today, it is about to set out again and continue to venture into the unknown.

References

https://github.com/Uniswap

https://blog.uniswap.org/uniswap-v4

https://github.com/Uniswap/v4-core/blob/main/whiteBlockingper-v4-draft.pdf

We will continue to update Blocking; if you have any questions or suggestions, please contact us!

Share:

Was this article helpful?

93 out of 132 found this helpful

Discover more

Blockchain

Deep analysis of the intent behind SEC's lawsuit against Binance: a jurisdictional dispute or a show of power?

Some observers believe that the SEC may be suing Binance to compete with the Commodity Futures Trading Commission (CF...

Market

Three days after listing, trading volume is lackluster. The first-ever leveraged BTC ETF in the US did not have a good start.

First leveraged cryptocurrency ETF in the US underperforms expectations three days after listing.

Market

FTX Latest Debt and Asset Summary How much money is owed and how much debt can be repaid?

Wu said the author | Cat Brother this issue editor | According to the latest court documents on September 10th, as of...

Market

Is CoinDesk selling at a loss with a valuation of $125 million after being in business for ten years?

On the occasion of its tenth anniversary and after being held by DCG Group for eight years, CoinDesk, the cryptocurre...

Opinion

Checklist of 9 popular cryptocurrencies virtual credit cards

Cryptocurrency virtual credit cards launched by cryptocurrency exchanges (such as Binance) allow for consumption and ...

Blockchain

The wave of "absolute deflation" of platform currency is coming. How should the exchange make a choice?

This article Source: Odaily Daily Planet , author: the the Platform currency refers to tokens issued by digital asset...