DeFi Evaluation Method ①: Uniswap Iterative Review

Intermediate1/7/2024, 5:42:07 PM
This article takes the development of Uniswap as an example to analyze the inspiration of the principles behind its iterations on DeFi design.
https://gimg.gateimg.com/learn/a3436e0b4d77e0013318d7bb69a5d96d8ee905e4.jpg

Recently I am doing a summary of the evaluation methods of the DeFi track. After studying some cases, Uniswap is a typical representative in terms of influence and iterative logic. This article conducts a comprehensive review of Uniswap.

The internal logic of Uniswap’s iteration from V1 to V4, as well as the launch of the UniswapX protocol, is functional innovation and mechanism optimization for DEX transactions.

V1 initially implemented AMM in the encryption field, V2 reduced ETH risk exposure and launched a price oracle that is more difficult to manipulate, V3 solved the problem of low capital efficiency through centralized liquidity, V4 implemented customizable DEX, and the UniswapX protocol was strengthened through the auction mechanism The competitiveness of third-party aggregators enables optimization of price slippage.

Uniswap development history

There is no need to go into details about Uniswap’s status and influence. According to Dune’s real-time data, Uniswap is still the DEX with the largest market share.

As a leading DEX, it has not been around for a long time, but it has been iterated many times. Let’s take a look at the development process:

In June 2017, Vitalik published the article On Path Independence;

In November 2018, Uniswap V1 was released: supporting transactions between ETH and ERC-20Token;

In March 2020, Uniswap V2 was released: supporting transactions between any two ERC-20 Token pairs;

In May 2021, Uniswap V3 was released: improving the utilization rate of LP funds and proposing the concept of aggregated liquidity;

In June 2023, Uniswap V4 was launched: Hooks contract customization was introduced to prevent value leakage;

In July 2023, Uniswap X was launched: aggregating on-chain and off-chain liquidity, MEV protection.

Uniswap V1: An attempt at automated market making

In 2017, Vitalik published an article “On Path Independence” on his personal webpage, in which the automated market maker (AMM) was introduced for the first time in the encryption field, which is a trading method different from CEX. Of course, this approach has long been discussed in non-crypto circles (such as traditional financial circles).

We know that in the stock market, futures market or existing CEX, most transactions are conducted in the Order Book (order book mode). Market makers (such as brokers and centralized exchanges) match buyers’ buy orders and sellers’ sell orders when the prices match, thereby completing transactions between buyers and sellers.

However, problems have been encountered in the case of decentralization. The reason is that in the decentralized environment of DEX (anyone can participate in creating the market), it is difficult to match transactions in the order book mode to provide corresponding liquidity, transaction rate and The experience is relatively poor, and without sufficient liquidity, it is difficult to match the operational effectiveness of CEX.

In this article by Vitalik, a novel concept is introduced to the encryption market:Automatic Market Maker. In this concept, asset pricing is done through pricing algorithms rather than through the traditional order book model.

In the AMM model, there is no need for market maker quotations or system matching, and traders can directly use the liquidity in the pool to realize asset exchange.

TokenA and TokenB form a constant product relationship:tokenA_balance(p) *tokenB_balance(p)=K (K remains unchanged)

This is a liquidity driven trading system, this model is calledConstant Product Market Maker (CPMM) . Under this approach, a path-independent market maker can be formed by defining any (monotonic) relationship between tokenA and tokenB and calculating its derivatives at any time to give a price.

Three participants: LP, traders, arbitrageBy

In the AMM’s market-making mechanism, there is no specific counterparty similar to the order book model. The actual value of the asset is determined by the mathematical formula of a constant product. To a certain extent, it can be compared to the counterparty being a smart contract, which can realize the asset’s Automated trading.

Someone needs to provide liquidity in a smart contract, and the liquidity provider is LP (Liquidity Provider). LP provides liquidity for transactions by injecting assets into the smart contracts in the pool, thereby obtaining transaction fee income.

After LP builds the initial liquidity pool, traders can exchange Tokens through the pool, and arbitrageurs will take the initiative to maintain asset prices consistent with market prices through price arbitrage between different markets.

In Uniswap V1 released in November 2018, all assets can be redeemed through ETH. For transactions between ETH and ERC-20Token, anyone can add tokens to trade with native ETH. ETH is essentially an asset trading intermediary.

What happens in a single pool if we want to trade??

Assume that one ETH is currently worth 100TokenA, and an ETH/TokenA pool consists of 10 ETH and 1000 TokenA.

At this time, the value of 10 ETH and 1,000 TokenA is the same as 1,000 US dollars, and the asset value ratio is 1:1.

k=10 *1000=10000, this product remains unchanged without adding more liquidity.

Now suppose I want to sell 5 ETH to the pool, then it should be:

y=10000/(10+5)=666.67, the number of ETH in the pool increased to 15, and the number of USDC at this time became 666.67, so I exchanged 5 ETH for 333.33 TokenA, and at this time the pool The price of a single ETH is 666.67/15=44.44, that is, one ETH is equal to 44.44 TokenA.

Of course, if the price in a single pool changes significantly from that of other trading markets, arbitrageurs will immediately swarm in until they eat up the price difference. After all, the AMM mechanism can only generate transaction prices, but cannot discover market prices, so the role of arbitrageurs is very important.

Impermanent losses, LP Token, transaction slippage

Impermanent losses occur when the price ratio of deposited tokens changes compared to when they were deposited into the pool. The greater the change, the greater the loss of impermanence.

Now, as LP, we will continue to give an example:

UniswapV1 core formula: x∗y=k

Now, as a liquidity provider, we continue to add 10 ETH and 1000 TokenA to the pool as the initial liquidity. At this time, 1 ETH is equal to 100 TokenA, and the constant product of the two asset quantities is 101000=10000( xy=10000,x=100y).

At this time, if the price of 1 ETH increases to 200 TokenA, we can convert: x*y=10000, x=200y, thus calculating x=7.071, y=1414.21.

At this time, the liquidity pool changed from the initial 10 ETH and 1000 TokenA to: 7.071 ETH and 1414.21 TokenA.

Found the problem?

At this time, if I redeem all the assets, I will receive 7.071 ETH and 1414.21 TokenA. The actual value calculated using TokenA is 7.071200+1414.21=2828.41. If calculated based on the initial 10 ETH and 1000 TokenA , the current price should be 10200+1000=3000TokenA.

The difference in this part of the income (3000-2828.41=171.59TokenA) isimpermanent loss。

Impermanent losses occur because under the automatic market maker mechanism of decentralized exchanges, liquidity providers adjust funds based on price fluctuations, resulting in principal losses and missed returns.

Since they act as both buyers and sellers, they are forced to increase the amount of assets they hold when prices fall and to decrease the amount of assets they hold when prices rise, resulting in losses.

Of course, you can also choose hedging and manage risks by opening short/long contracts on ETH.

In order to motivate users to act as LPs to provide liquidity and encourage them to bear price volatility,LP TokenIt came into being. This is a reward for liquidity providers, who can get a certain percentage of the handling fee for each transaction (UniswapV1, traders pay 0.3% in the transaction, which belongs to the liquidity provider). At the same time, it also serves as a certificate for LP to withdraw the liquidity added by itself.

Another concept isTrading slippage, friends who often do DEX trading will definitely be familiar with it. As a liquidity-driven trading system, AMM’s beautiful constant product equation is a smooth curve, and the price changes at all times according to the relationship between supply and demand.

If you trade a large number of Tokens at this time, slippage will occur, and there will be a certain difference between your expected price and the price you actually get from the pool. In other words, there will be a gap between the price you want and the transaction price.

Uniswap V2: Adaptation, Oracle, Lightningloan

Uniswap V1 only supports transactions between ERC-20/ETH trading pairs. In essence, it uses ETH as a transition currency intermediary to exchange between ERC-20 Tokens. Although the transaction path is simple, it creates ETH risk exposure for LP providers. Export, impermanent loss and slippage risks.

In Uniswap V2, it is still based on the “constant product market maker” mechanism, but the upgrade of V2 has brought efficiency improvements, including: supporting any two ERC-20 Token pairs for trading, which means that any ERC20 can be created - ERC20 pairs without the need to pair through the transition path of ETH.

I won’t go into details on this point. The upgrade of V2 includes many aspects. There are two more important points: improving the price.Oracle,accomplishflash loan。

Improvements to Price Oracle

In the process of Uniswap V1, the price calculated by dividing the reserve funds of the two assets in the pool is not safe if used as an on-chain price prediction because it can be easily manipulated.

One of the purposes of this V2 upgrade is to increase the cost and difficulty of price manipulation。

In V1, assuming that other contracts use the current ETH-DAI price to settle derivatives, an attacker who manipulates the measured price can buy ETH from the ETH-DAI pair, trigger the settlement of the derivative contract at an inflated price, and then ETH is sold back to the pair, bringing its trade back to its true price. In this case, transactions can even occur as atomic transactions, or with miners controlling the order of transactions within a block.

In V2, in order to determine the market price balance, the price is updated once per block, and the token exchange price is determined before the next block, that is, the token market price is based on the last transaction in the previous block.

In this upgrade, a new price prediction data is also provided:Time weighted average price TWAP. Accumulating the relative prices of two assets at the beginning of each block allows other contracts on Ethereum to estimate the time-weighted average price of two assets over any time interval.

More specifically, in Uniswap V2, the price is accumulated by tracking the cumulative sum of the price when someone interacts with the contract at the beginning of each block. Based on the block timestamp, each price is weighted by the amount of time since the previous block was updated. This means that the value of the accumulator at any given time (after being updated) should be the sum of the spot prices for every second in the history of the contract.

Users of the oracle can choose when to start and end this period, the cost for attackers to manipulate TWAP will be higher, and the price is relatively difficult to manipulate.

Realize flash loan

Flash loan is an absolute innovation compared to traditional finance. After all, real transactions cannot be rolled back like on the blockchain.

Flash Swaps flash loans were introduced in V2. Users are free to lend assets to the pool and use them elsewhere on the chain, only returning the assets and paying corresponding interest at the end of the transaction (payment in the same atomic transaction). If the money is not returned normally Then the transaction will be rolled back.

In fact, it allows anyone to quickly lend out any asset stored in the Uniswap pool. In V1, users are not allowed to receive and use the asset before paying for it. When using A asset to purchase B asset, the A asset needs to be sent to the contract before the B asset can be obtained.

There are some other updated points:Including Uniswap V2, which has adjusted the new contract framework, using a simple binary fixed-point format to encode and process prices (accuracy), update of protocol fees, and support meta transactions for the minted pool shares, etc.

Uniswap V3: Improvement of capital efficiency

Background: Uniswap V2 has liquidity issues. According to the introduction to the AMM mechanism above, we can see that at V1 and V2, the liquidity of the pool is actually distributed in the [0, +∞] area. In other words, any price is allowed in the V2 pool. transactions occur (refer to the inverse function smooth curve in AMM constant product).

This seems to be a good thing at first glance. The trading range is very large, but in fact, there is not such sufficient demand for trading pairs with different volatilities in their price ranges, which results in serious lack of liquidity except for some trading ranges. , low asset utilization.

As you can imagine, it is pointless and wasteful to provide liquidity at a price point so far away from the price range that the price may never reach that point.

concentrated liquidity

In this case, in order to improve financial liquidity, Uniswap V3 introduced the concept of concentrated liquidity. That is:

Liquidity providers (LPs) are free to choose to provide liquidity in a certain price range, this can provide better liquidity and operate within a high capital efficiency range. At the same time, in terms of application, it can also make different configurations for asset pools with different price volatility.

Every small price range in V3 can be understood as a V2 at work. During the transaction, the price will move smoothly along the curve. When the price reaches a certain section of V2, it reaches the interval point of the price interval of V3. At this time, the price point will slide to the next price interval. .

After understanding the above concept, we can get to know the new nouns——The core of V3 is Ticks。

Ticks, ticks, are the smallest incremental amounts by which a security can be traded. In V3, by dividing the price range of [0, +∞] into countless fine-grained Ticks, restrictions on the upper and lower bound endpoints of each range are implemented.

Liquidity is aggregated through granularity control. The entire price range in V3 is calibrated by discrete, evenly distributed Ticks. Each Tick has an index and corresponding price, and each Tick will have its own liquidity depth.

The mathematical principles of Uniswap V3 have changed, although it is similar to the underlying layer of V2:

L=xy under root sign

L is called the liquidity quantity, and the liquidity in the pool is the combination of the two Token asset quantities. Similarly, the product of the quantities of the two tokens is K, but because each Tick has different depths of liquidity, the equivalent formulas for different depths are no longer the same.

I won’t go into details about the mathematical principles. Below is a paper by Atis Elsts on the mathematical principles of V3. Interested friends can read it by themselves.

In Uniswap V2, there is still a standard 0.3% transaction fee, while in Uniswap V2V3 provides 3 different fee levels due to different granularities., are 0.05%, 0.3% and 1% respectively. at this timeLPs can focus their capital efficiency in the most frequently traded ranges to obtain maximum returns.。

In addition, V3 has once again optimized the oracle based on V2. It no longer stores only one price accumulation variable, but stores a set of variables, which can extend the service life of the data, reduce gas fees, and save costs.

Uniswap V4: Customizable DEX

Uniswap V4 is based on the centralized liquidity model of Uniswap V3,Allows anyone to deploy new centralized liquidity pools on Uniswap with custom functionality, thereby becoming an efficient andcustomizableDEX platform.

In V4, the core point isHooks contract, the vision is to allow anyone to make these trade-off decisions by introducing “hooks”。

For each pool, the creator can define a “Hooks contract” that executes logic at key points in the call’s lifecycle. These Hooks also manage the pool’s exchange fees and withdrawal fees charged to liquidity providers.

Hooks & Custom Pools

Hooks are a set of contracts developed by third parties or Uniswap officials. When creating a pool, the pool can choose to bind a hook. Then at a specific stage of the transaction, the pool will automatically call the hook contract bound to it. The contract is in Call key points in the life cycle to implement logic.

in other words,A hook is an externally deployed contract that executes some developer-defined logic at a specified point in the pool’s execution. These hooks allow integrators to create centralized liquidity pools with flexible and customizable execution. Hooks can modify pool parameters, or add new features and functionality.

Each Uniswap liquidity pool has a life cycle: During the life cycle of a liquidity pool, several things happen, including: the pool is created with a default fee tier, liquidity is added, removed, or readjusted, and users can also swap Tokens etc. In Uniswap v3, these lifecycle events are tightly coupled and executed in a very strict order.

But to create space for customizable liquidity in Uniswap V4. The Hooks contract creates a code introduction method for mining pool deployers to perform specified operations at key points in the mining pool life cycle, such as before and after swaps, or before and after LP position changes.

In short,Hooks are plugins for customizing how pools, swaps, fees and LP positions interact, through hooks contract,Developers can innovate on top of the liquidity and security of the Uniswap protocol, creating custom AMM pools through hooks integrated with v4 smart contracts.

Example functionality that can be implemented through hook contracts include:

  • Execution of large orders via TWAMM over a period of time;
  • An on-chain price limit order executed at a specified price;
  • Dynamic fees that change with volatility;
  • Internalized MEV allocation mechanism for liquidity providers;
  • Implement median, truncation, or other custom oracles.

The core logic of Uniswap V4 is the same as V3 and is not upgradeable. Since each mining pool is now defined by more than just tokens and fee tiers, it canVarious mining pools can be constructed from this. And while each pool can use its own hook smart contract, hooks are restricted to specific permissions determined when the pool is created.

There are also some architectural changes in V4, such as Flash Accounting (instantaneous account) that can significantly reduce gas fees. This feature is included in EIP-1153, which introduces “transient” storage, and will be implemented after the Cancun upgrade (Ethereum Cancun).

In addition, the V4 version also uses singleton mode (save all pool states in one contract), lightning accounting (ensures the solvency of the pool), restores support for native ETH, supports ERC-1155 tokens and adds governance mechanisms Wait for improvement.

UniswapX: Strengthening competition

UniswapX is a new permissionless, open source (GPL), auction-based protocol for trading across AMMs and other liquidity sources.

The protocol will improve exchange functionality in multiple areas, including:

  • Increase prices by pooling liquidity sources
  • No gas exchange
  • Prevent MEV (Maximum Extraction Value)
  • No fees for failed transactions
  • In the coming months, UniswapX will expand to gas-free cross-chain swaps.

Next-level aggregation next-generation aggregation

Background: On-chain transactions continue to innovate, leading to a proliferation of liquidity pools, and new fee tiers, L2 and more on-chain protocols will also disperse liquidity.

Solution: UniswapX aims to solve this problem through an open network that outsources routing complexity to third parties who need tocompeteCompeting to fill transactions using on-chain liquidity such as AMM pools or their own private inventories.

With UniswapX, traders will be able to use the Uniswap interface without worrying about whether they are getting the best price. Traders’ transactions will always be transparently recorded and settled on-chain. All orders are powered by the Uniswap Smart Order Router, which forces third parties to compete with Uniswap V1, V2, V3 and, upon launch, V4.

essentially,UniswapX strengthens the competition mechanism and optimizes the price slippage of each asset pool through third-party routing selection.。

In addition, UniswapX also launched new attempts:

No Gas Transaction, there is no charge for failure. The trader signs a unique off-chain order, which is then submitted on-chain by a third party who pays Gas on behalf of the trader. The third party includes the Gas fee into the transaction price, but can compete for the best price by executing multiple orders in batches. and reduce transaction costs.

MEV protection, returning the MEV originally obtained through arbitrage trading to traders at a better price. UniswapX helps users avoid more explicit forms of MEV withdrawal: orders executed using third-party private assets cannot be “sandwiched” and third parties are incentivized to use private transaction relays when routing orders to on-chain liquidity pools.

The upcoming UniswapX cross-chain version will combine swapping and bridging into one seamless operation. Using cross-chain UniswapX, swappers will be able to swap between chains in seconds and can look forward to their progress.

The main theme of Uniswap: iteration

The internal logic of Uniswap’s iteration from V1 to V4, as well as the launch of the UniswapX protocol, is the functional innovation of DEX (AMM).

V1 initially implemented AMM in the encryption field, V2 reduced ETH risk exposure and launched a price oracle that is more difficult to manipulate, V3 solved the problem of low capital efficiency through centralized liquidity, V4 implemented customizable DEX, and the UniswapX protocol was strengthened through the auction mechanism The competitiveness of third-party aggregators enables optimization of price slippage.

We can see that Uniswap is innovating itself every step of the way - reducing borrowing costs, optimizing user experience, strengthening competition awareness, and embracing emerging technologies. This iterative upgrade is the foundation for a good protocol to last forever.

Disclaimer:

  1. This article is reprinted from[见微知著杂谈]. All copyrights belong to the original author [Arrow杂谈]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

DeFi Evaluation Method ①: Uniswap Iterative Review

Intermediate1/7/2024, 5:42:07 PM
This article takes the development of Uniswap as an example to analyze the inspiration of the principles behind its iterations on DeFi design.

Recently I am doing a summary of the evaluation methods of the DeFi track. After studying some cases, Uniswap is a typical representative in terms of influence and iterative logic. This article conducts a comprehensive review of Uniswap.

The internal logic of Uniswap’s iteration from V1 to V4, as well as the launch of the UniswapX protocol, is functional innovation and mechanism optimization for DEX transactions.

V1 initially implemented AMM in the encryption field, V2 reduced ETH risk exposure and launched a price oracle that is more difficult to manipulate, V3 solved the problem of low capital efficiency through centralized liquidity, V4 implemented customizable DEX, and the UniswapX protocol was strengthened through the auction mechanism The competitiveness of third-party aggregators enables optimization of price slippage.

Uniswap development history

There is no need to go into details about Uniswap’s status and influence. According to Dune’s real-time data, Uniswap is still the DEX with the largest market share.

As a leading DEX, it has not been around for a long time, but it has been iterated many times. Let’s take a look at the development process:

In June 2017, Vitalik published the article On Path Independence;

In November 2018, Uniswap V1 was released: supporting transactions between ETH and ERC-20Token;

In March 2020, Uniswap V2 was released: supporting transactions between any two ERC-20 Token pairs;

In May 2021, Uniswap V3 was released: improving the utilization rate of LP funds and proposing the concept of aggregated liquidity;

In June 2023, Uniswap V4 was launched: Hooks contract customization was introduced to prevent value leakage;

In July 2023, Uniswap X was launched: aggregating on-chain and off-chain liquidity, MEV protection.

Uniswap V1: An attempt at automated market making

In 2017, Vitalik published an article “On Path Independence” on his personal webpage, in which the automated market maker (AMM) was introduced for the first time in the encryption field, which is a trading method different from CEX. Of course, this approach has long been discussed in non-crypto circles (such as traditional financial circles).

We know that in the stock market, futures market or existing CEX, most transactions are conducted in the Order Book (order book mode). Market makers (such as brokers and centralized exchanges) match buyers’ buy orders and sellers’ sell orders when the prices match, thereby completing transactions between buyers and sellers.

However, problems have been encountered in the case of decentralization. The reason is that in the decentralized environment of DEX (anyone can participate in creating the market), it is difficult to match transactions in the order book mode to provide corresponding liquidity, transaction rate and The experience is relatively poor, and without sufficient liquidity, it is difficult to match the operational effectiveness of CEX.

In this article by Vitalik, a novel concept is introduced to the encryption market:Automatic Market Maker. In this concept, asset pricing is done through pricing algorithms rather than through the traditional order book model.

In the AMM model, there is no need for market maker quotations or system matching, and traders can directly use the liquidity in the pool to realize asset exchange.

TokenA and TokenB form a constant product relationship:tokenA_balance(p) *tokenB_balance(p)=K (K remains unchanged)

This is a liquidity driven trading system, this model is calledConstant Product Market Maker (CPMM) . Under this approach, a path-independent market maker can be formed by defining any (monotonic) relationship between tokenA and tokenB and calculating its derivatives at any time to give a price.

Three participants: LP, traders, arbitrageBy

In the AMM’s market-making mechanism, there is no specific counterparty similar to the order book model. The actual value of the asset is determined by the mathematical formula of a constant product. To a certain extent, it can be compared to the counterparty being a smart contract, which can realize the asset’s Automated trading.

Someone needs to provide liquidity in a smart contract, and the liquidity provider is LP (Liquidity Provider). LP provides liquidity for transactions by injecting assets into the smart contracts in the pool, thereby obtaining transaction fee income.

After LP builds the initial liquidity pool, traders can exchange Tokens through the pool, and arbitrageurs will take the initiative to maintain asset prices consistent with market prices through price arbitrage between different markets.

In Uniswap V1 released in November 2018, all assets can be redeemed through ETH. For transactions between ETH and ERC-20Token, anyone can add tokens to trade with native ETH. ETH is essentially an asset trading intermediary.

What happens in a single pool if we want to trade??

Assume that one ETH is currently worth 100TokenA, and an ETH/TokenA pool consists of 10 ETH and 1000 TokenA.

At this time, the value of 10 ETH and 1,000 TokenA is the same as 1,000 US dollars, and the asset value ratio is 1:1.

k=10 *1000=10000, this product remains unchanged without adding more liquidity.

Now suppose I want to sell 5 ETH to the pool, then it should be:

y=10000/(10+5)=666.67, the number of ETH in the pool increased to 15, and the number of USDC at this time became 666.67, so I exchanged 5 ETH for 333.33 TokenA, and at this time the pool The price of a single ETH is 666.67/15=44.44, that is, one ETH is equal to 44.44 TokenA.

Of course, if the price in a single pool changes significantly from that of other trading markets, arbitrageurs will immediately swarm in until they eat up the price difference. After all, the AMM mechanism can only generate transaction prices, but cannot discover market prices, so the role of arbitrageurs is very important.

Impermanent losses, LP Token, transaction slippage

Impermanent losses occur when the price ratio of deposited tokens changes compared to when they were deposited into the pool. The greater the change, the greater the loss of impermanence.

Now, as LP, we will continue to give an example:

UniswapV1 core formula: x∗y=k

Now, as a liquidity provider, we continue to add 10 ETH and 1000 TokenA to the pool as the initial liquidity. At this time, 1 ETH is equal to 100 TokenA, and the constant product of the two asset quantities is 101000=10000( xy=10000,x=100y).

At this time, if the price of 1 ETH increases to 200 TokenA, we can convert: x*y=10000, x=200y, thus calculating x=7.071, y=1414.21.

At this time, the liquidity pool changed from the initial 10 ETH and 1000 TokenA to: 7.071 ETH and 1414.21 TokenA.

Found the problem?

At this time, if I redeem all the assets, I will receive 7.071 ETH and 1414.21 TokenA. The actual value calculated using TokenA is 7.071200+1414.21=2828.41. If calculated based on the initial 10 ETH and 1000 TokenA , the current price should be 10200+1000=3000TokenA.

The difference in this part of the income (3000-2828.41=171.59TokenA) isimpermanent loss。

Impermanent losses occur because under the automatic market maker mechanism of decentralized exchanges, liquidity providers adjust funds based on price fluctuations, resulting in principal losses and missed returns.

Since they act as both buyers and sellers, they are forced to increase the amount of assets they hold when prices fall and to decrease the amount of assets they hold when prices rise, resulting in losses.

Of course, you can also choose hedging and manage risks by opening short/long contracts on ETH.

In order to motivate users to act as LPs to provide liquidity and encourage them to bear price volatility,LP TokenIt came into being. This is a reward for liquidity providers, who can get a certain percentage of the handling fee for each transaction (UniswapV1, traders pay 0.3% in the transaction, which belongs to the liquidity provider). At the same time, it also serves as a certificate for LP to withdraw the liquidity added by itself.

Another concept isTrading slippage, friends who often do DEX trading will definitely be familiar with it. As a liquidity-driven trading system, AMM’s beautiful constant product equation is a smooth curve, and the price changes at all times according to the relationship between supply and demand.

If you trade a large number of Tokens at this time, slippage will occur, and there will be a certain difference between your expected price and the price you actually get from the pool. In other words, there will be a gap between the price you want and the transaction price.

Uniswap V2: Adaptation, Oracle, Lightningloan

Uniswap V1 only supports transactions between ERC-20/ETH trading pairs. In essence, it uses ETH as a transition currency intermediary to exchange between ERC-20 Tokens. Although the transaction path is simple, it creates ETH risk exposure for LP providers. Export, impermanent loss and slippage risks.

In Uniswap V2, it is still based on the “constant product market maker” mechanism, but the upgrade of V2 has brought efficiency improvements, including: supporting any two ERC-20 Token pairs for trading, which means that any ERC20 can be created - ERC20 pairs without the need to pair through the transition path of ETH.

I won’t go into details on this point. The upgrade of V2 includes many aspects. There are two more important points: improving the price.Oracle,accomplishflash loan。

Improvements to Price Oracle

In the process of Uniswap V1, the price calculated by dividing the reserve funds of the two assets in the pool is not safe if used as an on-chain price prediction because it can be easily manipulated.

One of the purposes of this V2 upgrade is to increase the cost and difficulty of price manipulation。

In V1, assuming that other contracts use the current ETH-DAI price to settle derivatives, an attacker who manipulates the measured price can buy ETH from the ETH-DAI pair, trigger the settlement of the derivative contract at an inflated price, and then ETH is sold back to the pair, bringing its trade back to its true price. In this case, transactions can even occur as atomic transactions, or with miners controlling the order of transactions within a block.

In V2, in order to determine the market price balance, the price is updated once per block, and the token exchange price is determined before the next block, that is, the token market price is based on the last transaction in the previous block.

In this upgrade, a new price prediction data is also provided:Time weighted average price TWAP. Accumulating the relative prices of two assets at the beginning of each block allows other contracts on Ethereum to estimate the time-weighted average price of two assets over any time interval.

More specifically, in Uniswap V2, the price is accumulated by tracking the cumulative sum of the price when someone interacts with the contract at the beginning of each block. Based on the block timestamp, each price is weighted by the amount of time since the previous block was updated. This means that the value of the accumulator at any given time (after being updated) should be the sum of the spot prices for every second in the history of the contract.

Users of the oracle can choose when to start and end this period, the cost for attackers to manipulate TWAP will be higher, and the price is relatively difficult to manipulate.

Realize flash loan

Flash loan is an absolute innovation compared to traditional finance. After all, real transactions cannot be rolled back like on the blockchain.

Flash Swaps flash loans were introduced in V2. Users are free to lend assets to the pool and use them elsewhere on the chain, only returning the assets and paying corresponding interest at the end of the transaction (payment in the same atomic transaction). If the money is not returned normally Then the transaction will be rolled back.

In fact, it allows anyone to quickly lend out any asset stored in the Uniswap pool. In V1, users are not allowed to receive and use the asset before paying for it. When using A asset to purchase B asset, the A asset needs to be sent to the contract before the B asset can be obtained.

There are some other updated points:Including Uniswap V2, which has adjusted the new contract framework, using a simple binary fixed-point format to encode and process prices (accuracy), update of protocol fees, and support meta transactions for the minted pool shares, etc.

Uniswap V3: Improvement of capital efficiency

Background: Uniswap V2 has liquidity issues. According to the introduction to the AMM mechanism above, we can see that at V1 and V2, the liquidity of the pool is actually distributed in the [0, +∞] area. In other words, any price is allowed in the V2 pool. transactions occur (refer to the inverse function smooth curve in AMM constant product).

This seems to be a good thing at first glance. The trading range is very large, but in fact, there is not such sufficient demand for trading pairs with different volatilities in their price ranges, which results in serious lack of liquidity except for some trading ranges. , low asset utilization.

As you can imagine, it is pointless and wasteful to provide liquidity at a price point so far away from the price range that the price may never reach that point.

concentrated liquidity

In this case, in order to improve financial liquidity, Uniswap V3 introduced the concept of concentrated liquidity. That is:

Liquidity providers (LPs) are free to choose to provide liquidity in a certain price range, this can provide better liquidity and operate within a high capital efficiency range. At the same time, in terms of application, it can also make different configurations for asset pools with different price volatility.

Every small price range in V3 can be understood as a V2 at work. During the transaction, the price will move smoothly along the curve. When the price reaches a certain section of V2, it reaches the interval point of the price interval of V3. At this time, the price point will slide to the next price interval. .

After understanding the above concept, we can get to know the new nouns——The core of V3 is Ticks。

Ticks, ticks, are the smallest incremental amounts by which a security can be traded. In V3, by dividing the price range of [0, +∞] into countless fine-grained Ticks, restrictions on the upper and lower bound endpoints of each range are implemented.

Liquidity is aggregated through granularity control. The entire price range in V3 is calibrated by discrete, evenly distributed Ticks. Each Tick has an index and corresponding price, and each Tick will have its own liquidity depth.

The mathematical principles of Uniswap V3 have changed, although it is similar to the underlying layer of V2:

L=xy under root sign

L is called the liquidity quantity, and the liquidity in the pool is the combination of the two Token asset quantities. Similarly, the product of the quantities of the two tokens is K, but because each Tick has different depths of liquidity, the equivalent formulas for different depths are no longer the same.

I won’t go into details about the mathematical principles. Below is a paper by Atis Elsts on the mathematical principles of V3. Interested friends can read it by themselves.

In Uniswap V2, there is still a standard 0.3% transaction fee, while in Uniswap V2V3 provides 3 different fee levels due to different granularities., are 0.05%, 0.3% and 1% respectively. at this timeLPs can focus their capital efficiency in the most frequently traded ranges to obtain maximum returns.。

In addition, V3 has once again optimized the oracle based on V2. It no longer stores only one price accumulation variable, but stores a set of variables, which can extend the service life of the data, reduce gas fees, and save costs.

Uniswap V4: Customizable DEX

Uniswap V4 is based on the centralized liquidity model of Uniswap V3,Allows anyone to deploy new centralized liquidity pools on Uniswap with custom functionality, thereby becoming an efficient andcustomizableDEX platform.

In V4, the core point isHooks contract, the vision is to allow anyone to make these trade-off decisions by introducing “hooks”。

For each pool, the creator can define a “Hooks contract” that executes logic at key points in the call’s lifecycle. These Hooks also manage the pool’s exchange fees and withdrawal fees charged to liquidity providers.

Hooks & Custom Pools

Hooks are a set of contracts developed by third parties or Uniswap officials. When creating a pool, the pool can choose to bind a hook. Then at a specific stage of the transaction, the pool will automatically call the hook contract bound to it. The contract is in Call key points in the life cycle to implement logic.

in other words,A hook is an externally deployed contract that executes some developer-defined logic at a specified point in the pool’s execution. These hooks allow integrators to create centralized liquidity pools with flexible and customizable execution. Hooks can modify pool parameters, or add new features and functionality.

Each Uniswap liquidity pool has a life cycle: During the life cycle of a liquidity pool, several things happen, including: the pool is created with a default fee tier, liquidity is added, removed, or readjusted, and users can also swap Tokens etc. In Uniswap v3, these lifecycle events are tightly coupled and executed in a very strict order.

But to create space for customizable liquidity in Uniswap V4. The Hooks contract creates a code introduction method for mining pool deployers to perform specified operations at key points in the mining pool life cycle, such as before and after swaps, or before and after LP position changes.

In short,Hooks are plugins for customizing how pools, swaps, fees and LP positions interact, through hooks contract,Developers can innovate on top of the liquidity and security of the Uniswap protocol, creating custom AMM pools through hooks integrated with v4 smart contracts.

Example functionality that can be implemented through hook contracts include:

  • Execution of large orders via TWAMM over a period of time;
  • An on-chain price limit order executed at a specified price;
  • Dynamic fees that change with volatility;
  • Internalized MEV allocation mechanism for liquidity providers;
  • Implement median, truncation, or other custom oracles.

The core logic of Uniswap V4 is the same as V3 and is not upgradeable. Since each mining pool is now defined by more than just tokens and fee tiers, it canVarious mining pools can be constructed from this. And while each pool can use its own hook smart contract, hooks are restricted to specific permissions determined when the pool is created.

There are also some architectural changes in V4, such as Flash Accounting (instantaneous account) that can significantly reduce gas fees. This feature is included in EIP-1153, which introduces “transient” storage, and will be implemented after the Cancun upgrade (Ethereum Cancun).

In addition, the V4 version also uses singleton mode (save all pool states in one contract), lightning accounting (ensures the solvency of the pool), restores support for native ETH, supports ERC-1155 tokens and adds governance mechanisms Wait for improvement.

UniswapX: Strengthening competition

UniswapX is a new permissionless, open source (GPL), auction-based protocol for trading across AMMs and other liquidity sources.

The protocol will improve exchange functionality in multiple areas, including:

  • Increase prices by pooling liquidity sources
  • No gas exchange
  • Prevent MEV (Maximum Extraction Value)
  • No fees for failed transactions
  • In the coming months, UniswapX will expand to gas-free cross-chain swaps.

Next-level aggregation next-generation aggregation

Background: On-chain transactions continue to innovate, leading to a proliferation of liquidity pools, and new fee tiers, L2 and more on-chain protocols will also disperse liquidity.

Solution: UniswapX aims to solve this problem through an open network that outsources routing complexity to third parties who need tocompeteCompeting to fill transactions using on-chain liquidity such as AMM pools or their own private inventories.

With UniswapX, traders will be able to use the Uniswap interface without worrying about whether they are getting the best price. Traders’ transactions will always be transparently recorded and settled on-chain. All orders are powered by the Uniswap Smart Order Router, which forces third parties to compete with Uniswap V1, V2, V3 and, upon launch, V4.

essentially,UniswapX strengthens the competition mechanism and optimizes the price slippage of each asset pool through third-party routing selection.。

In addition, UniswapX also launched new attempts:

No Gas Transaction, there is no charge for failure. The trader signs a unique off-chain order, which is then submitted on-chain by a third party who pays Gas on behalf of the trader. The third party includes the Gas fee into the transaction price, but can compete for the best price by executing multiple orders in batches. and reduce transaction costs.

MEV protection, returning the MEV originally obtained through arbitrage trading to traders at a better price. UniswapX helps users avoid more explicit forms of MEV withdrawal: orders executed using third-party private assets cannot be “sandwiched” and third parties are incentivized to use private transaction relays when routing orders to on-chain liquidity pools.

The upcoming UniswapX cross-chain version will combine swapping and bridging into one seamless operation. Using cross-chain UniswapX, swappers will be able to swap between chains in seconds and can look forward to their progress.

The main theme of Uniswap: iteration

The internal logic of Uniswap’s iteration from V1 to V4, as well as the launch of the UniswapX protocol, is the functional innovation of DEX (AMM).

V1 initially implemented AMM in the encryption field, V2 reduced ETH risk exposure and launched a price oracle that is more difficult to manipulate, V3 solved the problem of low capital efficiency through centralized liquidity, V4 implemented customizable DEX, and the UniswapX protocol was strengthened through the auction mechanism The competitiveness of third-party aggregators enables optimization of price slippage.

We can see that Uniswap is innovating itself every step of the way - reducing borrowing costs, optimizing user experience, strengthening competition awareness, and embracing emerging technologies. This iterative upgrade is the foundation for a good protocol to last forever.

Disclaimer:

  1. This article is reprinted from[见微知著杂谈]. All copyrights belong to the original author [Arrow杂谈]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.
Start Now
Sign up and get a
$100
Voucher!