Introduction to UniswapV2

1. What is uniswap

Official document

What is Uniswap? Let's look at the first sentence of the official document:

Uniswap is an automated liquidity protocol powered by a constant product formula and implemented in a system of non-upgradeable smart contracts on the Ethereum blockchain.

Let's split this sentence and take a look at its key points. First, it is an automatic liquidity agreement; second, it is based on a constant product algorithm. Then, it is implemented through non-upgradable smart contracts; finally, it is on the Ethereum blockchain.

Generally speaking, we can think of Uniswap as a decentralized digital currency exchange (DEX) on Ethereum, or as a type of Defi.

Let's talk about these concepts a little bit:

  • Constant product algorithm: simply considered X * Y = K, where K(product) remains unchanged, so called constant multiplication algorithm, the function is a sigmoidal curve.

  • Automatic liquidity agreements are generally called automatic market making. In the above formula, the ratio of X/Y is generally called price. When X changes, according to the product unchanged, Y also changes, so X/Y, that is, the price changes, so it is called automatic market making. Here, the corresponding X and Y can be provided at the same time according to the ratio of X and Y. This operation is called increasing (providing) liquidity. Although the K value after increasing liquidity has changed from before, it remains unchanged in subsequent transactions. Correspondingly, there are also operations to reduce liquidity. The general formula for transactions X and Y is similar to:

    (X + X0) * (Y - Y0) = K. The formula is expressed as providing (x0 quantity) X to obtain (y0 quantity) Y.

  • Cannot be upgraded. Upgradability means there is a risk of evil. Unupgradable means that the code is the law, and everything is open, transparent and unchangeable.

  • Ethereum blockchain. It runs on Ethereum in the public chain. At present, most Defi or DEX are running on Ethereum, and a few are running on other public chains.

Uniswap and Bancor are the basis of various Defi currently in a mess, and most DEXs are also modified or copied from their basis.

As a rising star, Uniswap has left its predecessors far behind. At present, Uniswap is already V2 version. Compared with V1 version, many changes and optimizations have been made.

2. Some core content of Uniswap

This section is mainly derived from official documents.

  1. Uniswap's trading pair is any ERC20 trading pair. Increasing liquidity (providing the corresponding two ERC20 coins) will get liquidity tokens. You can also use liquidity tokens to redeem your ERC20 tokens at any time. Increasing liquidity will reduce the price slippage during trading.

  2. Uniswap uses a constant product to make the market automatically, so the ratio (price) at the time of execution of large-value transactions and small-value transactions will become exponentially worse. Of course, this is the design.

  3. Due to the existence of arbitrage, Uniswap price always tends to the settlement price.

  4. When trading, Uniswap charges a 3% handling fee and pays it to all liquidity providers. This essentially makes the constant product Klarger.

  5. Uniswap ecological participants are divided into three categories: liquidity providers, traders, and developers.

    • Liquidity providers are divided into four categories: passive, professional, token project parties and DeFi innovators.
    • Traders are also divided into several categories: speculators, arbitrageurs, Dapp users, smart contracts. (The difference between arbitrageurs and speculators is that arbitrageurs use the price difference of different platforms to make profits, and speculators make profits by trading tokens).
    • Developers. It can also be divided into the following categories:
      1. The open source feature makes it possible for other projects to use Uniswap functions. You can find Uniswap functions on the main Defi projects.
      2. The wallet integrates transaction tokens and liquidity supply functions.
      3. DEX (Decentralized Exchange) can pull Uniswap's liquidity, thereby separating liquidity and trading. For these projects, Uniswap is the largest single source of decentralized liquidity.
      4. Smart contract developers can use Uniswap's full set of functions to develop new Defi tools and verify some experimental ideas.
  6. Uniswap V2's smart contract system consists of two parts: the core contract, which provides basic security guarantees for all transaction pairs on Uniswap. Peripheral contracts are used to interact with the core contract for user convenience, but they are not part of the core contract.

  7. The core contract consists of a singleton factoryand multiple trading pairs pairs. factoryUsed to create and index pairs. The core contract is designed to be short, small and concise, which reduces the complexity and is less error-prone, but it is relatively unfriendly to users sometimes. In fact, it is not recommended to directly interact with the core contract, but to interact with the peripheral contract.

  8. factoryThe contract saves the enabled pairsbytecode. Its main job is to create a unique smart contract for a unique trading pair. It also controls the switch of the development team's recruitment fee collection.

  9. pairsTrading pairs mainly provide two functions: one is to provide automatic market making and to track the token balance in the trading pool; the other is to expose relevant data to the outside as a decentralized price oracle.

  10. Peripheral contracts are a collection of contracts that are designed to support interactions with core contracts in specific areas.

  11. Library contract. The library in Uniswap V2 provides a large number of convenient tools for obtaining data and prices.

  12. Router routing contract. The contract used to interact with the front-end is used to achieve transaction and liquidity management. It also natively supports multi-pair transactions, treats ETH as a first-class citizen, and provides support for metadata transactions when liquidity is removed.

  13. The transaction method of sending tokens in advance. Generally, if tokens are transferred through a third-party contract, authorization is required to operate. Uniswap V2 uses a different design. It does not use authorization, but needs to send tokens to the trading pair before trading. During the transaction, the contract will check the currently saved token balance and the actual token balance of the contract, and use the difference between the two as the number of input tokens. Therefore, when calling any method that requires tokens in a trading pair, the corresponding amount of tokens must be sent to the trading pair (except for the exception of Flash Swaps, which is borrowed and repaid).

  14. WETH. Uniswap V2 does not support ETH/ERC20 trading pairs, so WETH simulation must be used. Users can ignore the details and simply use peripheral contracts to package and unpackage ETH.

  15. Minimum liquidity. In order to eliminate the cutoff effect and increase the theoretical minimum tick of liquidity supply, the trading pair burns the initial minimum liquidity. It only occurs during the first time liquidity is provided. For most trading pairs, this value is negligible and can be ignored.

Three, some new features of UniswapV2

The content of this section is mainly derived from the white paper of UniswapV2.

UniswapV2 is a new realization based on the constant product algorithm. Compared with V1, it has the following new features:

  • Any ERC20/ERC20 trading pair can be created, while V1 can only create ETH/ERC20 trading pairs. In this way, the token can be processed uniformly within the transaction pair, and no longer distinguish between eth and erc20. In order to support the ERC20/ERC20 trading pair, ETH has become WETH accordingly.

  • Enhanced the oracle function, reducing the risk of price manipulation in the same block in UniswapV1. The specific method is: sell a large amount of certain asset A at the beginning of a block to affect the price, and perform other operations on other contracts (non-uniswap transactions against contracts) based on this greatly fluctuating price in the middle of the block, and at the end of the block Buying the same amount of asset A again brings the price back to normal levels. UniswapV2 has carried out price accumulation to facilitate third parties to use the average price of a certain range, which greatly increases the difficulty of such manipulation and makes price manipulation without real benefits. Because the average value is used, the average value of a certain interval of A/B and B/A is no longer a reciprocal relationship, so the V2 version provides these two prices.

  • UQ112.112 data format is used to improve the accuracy of price calculation. At the same time, uint112 is used to store the number of assets in the trading pair. At the same time, 32 bits are used to save the creation time of the current block. Although it will overflow after 100 years, a corresponding processing mechanism is made.

  • Flash Swaps. The transaction is owed first, so that it can be arbitrage at zero cost. Assume that there is an A/B trading pair in UniswapV2, and other DEXs also have an A/B trading pair. Here we can owe A first, get B from Uniswap, then use B to get A0 from other DEX, and then return Uniswap's A, so that A0-A is our arbitrage. We don't need any tokens, just pay gas (handling fee) to realize the empty glove white wolf. Of course, other DEXs can also arbitrage Uniswap at zero cost, as long as there is enough price difference between the same trading pairs.

  • Development team fees. UniswapV2 has a switch that can control whether to divide 1/6 of the 0.3% transaction fee, which is 0.05% of the total fee, to the development team. In order to avoid affecting transaction fees, this fee will only be calculated when increasing/decreasing liquidity.

  • Additional issuance of liquidity tokens (pool shares) supports metadata transactions.

  • UniswapV2 is written in Solidity instead of Vyper.

  • Contract reconstruction. UniswapV2 minimizes the trading pair contract, only retaining the exchange function and the function of protecting the liquidity provider, while also saving the latest quantity of each asset. Other functions are put in the external routing contract. In V2, the trader must send the corresponding asset (token) to the trading pair contract before calling the exchange function, and the trading pair contract does not matter how the asset is sent.

    • Adjust transaction fees. In the V1 version, only the number of payments is reduced before performing the constant product, such as:, (x1 - 0:003 * xin)) * y1 >= x0 * y0while in the V2 version, due to the existence of Flash Swaps, the formula is adjusted to (x1 - 0:003 * xin) * (y1 - 0:003 * yin) >= x0 * y0.
    • sync() and skim(). sync() is used to synchronize the number of assets cached in the contract to the current value of the contract, to tighten assets, and is mainly used to deal with situations where the ratio is unreasonable and there is no liquidity provider to regress. skim() is used to handle the situation where the amount of a certain asset in the contract is greater than the maximum value of uint112 (see UQ112.112 format description). It allows the user to propose the difference between the current asset value of the contract and the maximum value of uint112.
  • Deal with non-standard and infrequently used tokens. The standard ERC20 token contract needs to return a boolean value to indicate success after the token is transferred. But not all tokens do this, and some do not provide a return value. In the V1 version, the transfer of tokens with no return value is failed by default and the entire transaction will be reset. UniswapV2 regards a token transfer without a return value as a successful transfer. In addition, the V1 version, it is assumed token transfer will not trigger the re-entry of the transaction, but this assumption is supported by ERC777the hooksnumber of tokens ERC20 broken. In order to support this token, the V2 version adds an anti-reentry function to all public functions that change state variables lock. It also prevents the reentry of user-defined callbacks in Flash Swaps.

  • Liquidity initialization support. When re-providing liquidity for a trading pair that already has liquidity, it is easy to calculate the new liquidity based on the current ratio. But when liquidity is provided for the first time, the denominator of this ratio is 0 and no longer applies. What to do at this time? In the V1 version, the initial liquidity value is directly equal to the ETH value provided during initialization. This approach has its rationality and its drawbacks, that is, it relies too much on the initial liquidity ratio (the ratio is arbitrary), and there is no mechanism to ensure that this ratio is consistent with the real price. In the V2 version, the trading pair is ERC20/ERC20, which means that there is no ETH. Therefore, the initialization of liquidity uses the following formula:
    S minted = X deposited ⋅ Y deposited S_{minted} = \sqrt{X_{deposited} \cdot Y_{deposited}}Sminted=XdepositedYdeposited
    The above formula ensures that the share of the liquidity pool will never be lower than the geometric average of the reserves in the pool. But this will also cause the value to increase over time. In order to reduce this effect, UniswapV2 burns the initial fluidity of 1e-15, which is 1000 times the minimum fluidity (1e-18). This is trivial for any trading pair, but it greatly increases the cost of attackers who use this influence to profit.

  • Pack ETH. The interface for trading the native currency ETH on Ethereum is different from the interface for trading ERC20. Therefore, many other protocols do not support ETH, but instead support an alternative to WETH (a token that wraps ETH). UniswapV1 is an exception because its trading pair directly contains ETH. Because V2 is any ERC20 trading pair, supporting native ETH will complicate things and increase risks. Therefore, ETH is not supported in V2, and users must change to WETH before using the trading pair. In fact, UniswapV2 automatically converts the ETH provided by the user into WETH internally.

  • Deterministic transaction pair address. Regardless of V1 or V2, all trading pairs are created by a single factory. In V1, the createoperation code is used, and the created transaction is affected by the order in which the transaction is created. In V2, a new opcode is used create2, and the address it generates is deterministic, which means that the transaction pair address can be calculated off-chain without having to check on-chain status.

  • The maximum number of tokens. In order to efficiently implement the oracle function, UniswapV2 uses uint112 to save the number of tokens, that is, it only supports a maximum of 2^112-1 tokens. This value is also sufficient for a coin with a precision of 18, which is approximately 5192296858534828 (5.19e15), which is 5.19 petaflops. If the record value in the contract exceeds this value, the transaction will report an error. As mentioned earlier, anyone can use the skim() function to recover and remove excess assets in the liquidity pool.

Four, terminology

The content of this section comes from Uniswap official documents.

  • Automatic makert maker (automatic market making). It is essentially a smart contract on Ethereum, which saves some assets, and users trade assets according to the price automatically calculated by a specific algorithm.
  • Constant Product Formula (constant product formula). The automatic market making algorithm used by Uniswap is similar X * Y = K.
  • ERC20. ERC20 token is a stackable homogenous token on Ethereum. Uniswap supports all standard ERC20 implementations.
  • Factory. A smart contract, which is used to deploy a unique (specific) smart contract for each ERC20 transaction pair.
  • Pair. Trading pair, a smart contract deployed by Factory to trade two ERC20 tokens.
  • Pool. A pool of liquidity of all liquidity providers in a trading pair.
  • Liquidity Provider/LP. Liquidity providers refer to those who pledge two ERC20 tokens in matching amounts to a trading pair's liquidity pool. The liquidity provider bears the risk of price loss, as compensation, can obtain the corresponding share of the handling fee.
  • Mid Price. The median price at which players buy and sell tokens at a given moment. In Uniswap, it is the ratio of the number of two tokens in the trading pair.
  • Price impact. The difference between Mid-price and the actual execution price of the transaction.
  • Slippage. Slippage. In a trading pair, the amount of movement between the price when a certain transaction is submitted and the price after the transaction is executed.
  • Core. The necessary core contract for Uniswap. Upgrading to the new version of the core contract requires liquidity migration.
  • Periphery. Peripheral contracts. An external contract that is useful for Uniswap, but not necessary for Uniswap. There is no need to migrate liquidity when deploying new peripheral contracts.
  • Flash Swap. A kind of spend first before paying for the transaction.
  • Invariant. Immutability. Refers to the constant product algorithm that Kdoes not change during trading.

Guess you like

Origin blog.csdn.net/weixin_39430411/article/details/108665694