# Algorithm

## Constant Product Market Maker Model

Exchanges that want to decentralize and don't use a pending order book need to rely on an algorithm to automatically calculate the quantity and price of the underlying trade, and Uniswap uses an algorithm called Constant Product, which can be traced back to this article from Vitalik.

The formula is very simple: x *y = k. The two cryptocurrencies to be traded are X and Y, each with quantity x and y, and the product of the two quantities x* y is always equal to k, the value of k being determined by the liquidity of the first deposit.

Therefore, the amount of ∆y that can be obtained by purchasing Y with ∆x amount of X coins, or the amount of ∆x that needs to be paid in order to purchase ∆y, is calculated as follows: (x + ∆x)(y - ∆y) = k, and the price of the transaction is the ratio of the two coin amounts ∆x and ∆y.

The following equation expresses the new equilibrium quantities of ∆x and ∆y and the X Y coins after the transaction occurs by α = ∆x /x and β = ∆y /y.

## Chargeable to fees

Each transaction at Uniswap is charged a commission of ρ = 0.003 / 0.3% back to the liquidity provider, thus taking the commission into account in the formula.

It is advisable to start not with x'ρ and y'ρ, but with the values of ∆x and ∆y: the commission ρ = 0.3% means that 0.3% will be deducted from the payment, i.e. from ∆x. In the presence of a fee ∆x becomes (1-ρ)∆x if we make γ = 1-ρ. Thus, replacing ∆x in Figure 1 with γ∆x gives the following equation.

By the same token, since α in ∆y = ∆x /x, replacing ∆x with γ∆x gives ∆y in Figure 2 (multiplying γ by α where α is). And x' and y' can be deduced from ∆x and ∆y. However, multiplying x' and y' obtained in Figure 2 yields.

That is, when there is a fee that makes γ ! = 1 / ρ ! = 0, the value of x'ρ *y'ρ will actually be slightly different from xy = k: in fact γ = 0.997 / ρ = 0.003, so 1/γ-1 is 0.003. β = ∆y /y represents the proportion of the total amount of Y coins exchanged. Even with a maximum value of 1, the error is only 1* 0.003, so fee = 0.3% has very little effect on the value of k.

## Uniswap White Paper

If you want to learn more details about Uniswap, you can refer to the Uniswap white paper.

Last updated