---
# System prepended metadata

title: 'Uniswap: a geometrical exposition'
tags: [general]

---

---
tags: general
---

# Uniswap: a geometrical exposition

Uniswap is a financial exchange which match bids and asks with a new class of investors, liquidity providers (LPs). Traders instantly find a counter-party by tapping into a liquidity pool pre-funded by LPs who accept to take the other side of the trades according to a fixed pricing rule based on a constant product formula. The platform charges a fee on trades redistributed to LPs based on their share of the pool. The smart contract based protocol is decentralized and permissionless. Anyone can swap tokens, add tokens to a pool, or list a token without asking permission or needing to trust a centralized authority.
<!-- In less than two years, the protocol has supported over $20bn transactions across 8,484 unique assets, and secured over $1bn liquidity, earning $56m fees in the process. -->

This post explains the protocol with graphics. A follow up post focuses on what investors are doing when they provide liquidity and what kind of risks they take.
The pricing rule

A distinctive aspect of the protocol is the pricing rule. Let us suppose that the platform allows the exchange of apples against pears (replace by any ERC20 tokens tradeable on the Ethereum blockchain). When a user wants to exchange one fruit against the other, the smart contract queries the number of pears $x$ and apples y available in the pool, computes the product $k = xy$ and offers to exchange any quantity $dx$ against $dy$ preserving the constraint $(x+dx) (y+dy) = k$, where $k$ is fixed within the trade frame.

If $(x,y,k)$ denotes the initial protocol’s state, the state transits after the trade, to $(x’,y’,k)$ with $x’ = x+dx$ and $y’ = y+dy$. The product $k$ only varies when fruits are added into or withdrawn from the pool by LPs, or when transaction fees paid by traders expand the pool. In the following, we abstract of, but have to keep in mind, transaction and network fees paid by traders to LPs and Ethereum miners respectively.

![The trader buys pears an sells apples](https://i.imgur.com/P9WjfWJ.png =400x330)


Graphically, if a trader is willing to trade the two fruits while the pool’s state is A = $(x,y,k)$, he may choose any quantity $(x’-x)$ and $(y’-y)$ satisfying $x’y’ = k$. If the trader buys (removes from the pool) $(x’-x)$ apples, he gives up (adds up to the pool) $(y’-y)$ pears. The funds move from A to A’ along the $xy = k$ curve, also called the bonding curve. Symmetrically, selling pears and buying apples would move the pool to the other direction but still along the bonding curve:

![The trader buys apples and sells pears
The exchange rate](https://i.imgur.com/PMTxipc.png =360x300)

Because the protocol does not quote prices explicitly, we need to define the relative price of a traded asset pair. The exchange rate indicates how many apples a trader can obtain in exchange of one pear, or the ratio $(y’-y)/(x’-x)$. It is the triangle’s height $(y’-y)$ divided by its base $(x’-x)$ or the absolute slope s of the purple line crossing A and A’:

![The exchange rate is the slope of the line crossing A and A’](https://i.imgur.com/kDtgE78.png =360x300)

For instance, if a trader buys $x-x’$ = 4 pears in exchange to $y’-y$ = 12 apples, the trade’s exchange rate is 12/4 = 3. The steeper the slope, the more expensive pears in terms of apples.

## The market price

The market price proposed by the protocol is the best exchange rate a trader can obtain by trading an arbitrarily small quantity. It abstracts from price slippage originating from non-trivial trade’s size (see further). Let’s see what the definition graphically means. When the quantity (x’-x) exchanged against (y’-y) approaches zero in previous figure, A’ is getting closer and closer to A. At the limit, A’ becomes visually indistinguishable from A. The exchange rate is still given by the slope of the line crossing A and A’, which is tangent to the bonding curve:

![The market price is the slope tangent to the curve](https://i.imgur.com/iIhFw9i.png =360x260)

The market price $p$ is the negative of the first derivative of $y = k/x$ computed in state A = $(x,y,k)$ and is just the ratio of the quantities of the two fruits available in the pool: $p = y/x$. The more pears in the pool, the lower its price. The equality $p = y/x$ is an elegant property of constant product curves.

![The price is the ratio of the two quantities of fruits](https://i.imgur.com/jTEeJfB.png =350x275)

The market price $p = y/x$ is the slope of the line crossing y and x. It parallels the line tangent to the bonding curve in A. The two lines always keep their parallelism when A is moving along the curve. Nice, isn’t it?

It is easy to recover the protocol’s price by dividing the quantity of apples held in the pool by the quantity of pears. A nice property of the constant product formula is that the protocol always exhibits a strictly positive price whatever the quantities available in the pool, as long as it starts with positive quantities. The trades cannot exhaust the stock of any of the two assets as its price is increasing sufficiently fast with trade’s size. The fact that the price strongly reacts to changes in available quantities has also some drawbacks, like price slippage and impermanent loss (see below and next post).

## Adherence to equilibrium price

The exchange takes as given the equilibrium price p determined by demand and supply across platforms at the whole market level. However, the equality y = px is not a constraint that the protocol tries to meet (the smart contract has no clue about what is the market price!), but a consequence of market forces and arbitrage. If the exchange rate deviates from the market price, arbitrageurs buy the cheapest asset from the pool and sell it in other exchanges at a premium. In doing so, arbitrageurs bring the exchange rate in the close neighborhood of the market price where arbitrages are no more profitable given trade costs and network fees.

Suppose the equilibrium price of pears drops. Arbitrageurs buys apples from the protocol, then sell the fruits against pears outside the platform and make a profit. In the figure below, the quantity of apples in the pool decreases by $(y-y’)$ and the quantity of pears increases by $(x’-x)$ so that the exchange rate aligns with the new equilibrium price: $p’ = y’/x’ < p = y/x$. The arbitrage process is fast. It is automated by bots and complete within a block time-frame.

![](https://i.imgur.com/pppwiIL.png =380x300)


## Change in market price

By driving the protocol’s exchange rate close enough to the equilibrium price, arbitrageurs make a profit at the expense of LPs, whose loss is called “impermanent loss” (see next post).

The fact that the exchange rate stays close to the equilibrium price means that the pool’s quantity ratio y/x is pinned down by the market. The cheaper pears compared to apples (the lower p), the larger the quantity of pears accumulated in the pool compared to the quantity of apples. By doing so, the protocol follows a counter-cyclical investment policy. It buys and accumulates the asset which price is down and “cashes out” by selling the asset which price is up. This strategy is profitable if the price tends to revert to its mean eventually. It is inefficient if the price is trending downward (upward) and never recovers (falls back). It is disastrous if it goes to zero, in which case the rotten fruit completely drives out the good one in the pool.


## Price slippage

The price slippage is the difference between the trade’s exchange rate and the market price. In absence of slippage, the trader would pay the market price regardless of the volume traded. In the graphic, the trader would exchange the smaller quantity of apples y* instead of y’ against x’-x pears:

![Price slippage](https://i.imgur.com/gfOtUh6.png =400x300)

The larger the trade, the further away A’ from A along the curve, and the more unfavorable the exchange rate. Price slippage is a component of transaction costs, which also include exchange trading fees and gas fees for using the Ethereum Network.

Price slippage can be minimized by splitting the trade in smaller quantities. Suppose the trader exchanges apples against a large quantity $(x-x’’)$ of pears. In the figure, the trade is divided in two trades of equal size $(x-x’)$ and $(x”-x’)$.

![The trade is equally split in two smaller trades](https://i.imgur.com/tBLJk05.png =400x300)

The first trade reduces the quantity of pears in the pool and moves the price of pears up, causing price slippage. The trader waits for the price being arbitraged down, and then executes the second trade at the same price than the first one. Overall, the trader pays two times $(y’-y)$, which is less than $(y’’-y)$ if the trade were executed at once.

## Pool’s market value

The market value of the assets held in the pool, owned by LPs, is the number of apples and the number of pears converted in apples at market price p: V = px+y. Since the protocol sticks to the constraint px = y, regardless of p, the pool is always invested 50:50 in the two fruits. This is a remarkable rule, illustrated in the figure:

![The pool is invested 50:50 in the two fruits](https://i.imgur.com/64TFGES.png =340x320)

Because the slope of the purple line crossing $y$ and $x$ is also the market price $p$, the vertical red line is both the number $y$ of apples and the value $px$ of pears in the pool.

The market value of the two assets can be expressed in terms of $p$ and $k$ from the two constraints $xy = k$ and $p = y/x$. We obtain $y = \sqrt{kp}$ and $x = \sqrt{k/p}$ and therefore $V = px+y = 2 \sqrt{kp}$. Outside the pool, the value of a portfolio composed of x pears and y apples would evolve linearly with the market price p. Instead, the pool’s market value is a function of its square root. This has fundamental implications for the return earned by LPs.

## Effects of a change in pool’s liquidity

When a LP adds liquidity to to the pool or withdraws from it, the operation should not alter the market price. First, because liquidity variations do not signal any change in the relative scarcity of the two assets. Second, exchange rate’s deviations from the market price offer a free lunch to arbitrageurs.

If the state of the protocol is $(x,y,k)$, any addition or withdrawal of liquidity is a fraction a of existing quantities such that the market price stays the same: $p = (y + ay)/(x + ax) = y/x$. The pool’s value expands by the the factor: $V’ = (1 + a)V$. The constant $k$ is updated to $k’ = (1+a)² k$. In the figure, given market price $p$, the pool shrinks or expands along the expansion path of the liquidity pool, which slope is $p = y/x$.

![A change in liquidity](https://i.imgur.com/QTbUpr4.png =360x290)

Because the expansion path’s slope is the negative of the $y-x$ diagonal’s slope (the two purple lines make a perfect cross inside the rectangle), moving the protocol’s state along the expansion path does not alter the market price.

For instance, the next figure shows the case of a liquidity addition, shifting the protocol from A to A’:

![Adding pears and apples to the fruits’ basket](https://i.imgur.com/qpZJeZn.png =390x330)

## Effects of a price change

Suppose now that the price of pears drops from $p$ to $p’$. The market value of pears held in the pool instantly decreases from $px$ to $p’x$. Then, rapidly, comes a composition effect as the exchange rate $y/x$ lags above the new equilibrium price $p’$. Arbitrageurs buy apples against pears at a discount, depleting the stock of apples and increasing the stock of pears in the pool. The process continues until the exchange rate realigns with the equilibrium price: $y’/x’ = p’$. The new protocol state is A’= $(x’,y’, k)$:

![The pool mix is changed, the exchange rate realigns with market price](https://i.imgur.com/Ngv5yBl.png =400x300)

The pool’s value becomes $V’ = 2 \sqrt{kp’}$. Now suppose that the investor did not provide liquidity and just held $x = \sqrt{k/p}$ pears and $y = \sqrt{pk}$ apples in his portfolio, the same quantities as the pool owns. After the price decrease, he would still be in A. The line crossing A, which absolute slope is $p’$, represents all combinations of the two fruits that the investor can obtain by trading pears against apples at market price $p’$. The line is above the one crossing A’ for all combinations. Assuming that the LP owns the entire pool (owning a fraction of it would not change the conclusion), the pool underperforms compared to the investor’s portfolio. In particular, the investor could “cash out” in apples and obtain the quantity $y’’$ compared to $y’$ if the liquidity pool were sold.

![More apples and pears outside the protocol](https://i.imgur.com/WmQ0G3w.png =380x320)

The pool also underperforms by a similar margin if the price increases. The pool’s state could as well start from A’’ instead of A and, after the price rise, moves to A’ with the same loss for the LPs. The holding investor benefits from a constant (or quasi-constant in case of price slippage) exchange rate along the portfolio line crossing A and A’’. To the contrary, the protocol automatically rebalances the pool at a substandard exchange rate due to adherence to the bonding curve.

The missing return can be evaluated by assuming that the investor initially creates a pool at market price $p$ with $x = \sqrt{k/p}$ pears and $y = \sqrt{pk}$ apples in proportion $y/x = p$. If the price varies to $p’$, the pool’s value becomes $V^p = 2 \sqrt{p’k}$ whereas the holding portfolio’s value changes to $V^h = y + p’x = (1+p’/p) \sqrt{pk}$. The loss ratio of providing liquidity relative to holding a portfolio is given by
$$
\dfrac{V^p}{V^h} = \dfrac{2 \sqrt{p’/p}}{1+p’/p}
$$

The market value of the pool and the portfolio are represented in function of the price ratio p’/p by assuming (without loss of generality) that both the investor and the protocol start with one apple and one pear and that the initial price is 1.
Pool’s and portfolio’s value in function of the price

![](https://i.imgur.com/UJjGLqI.png)

LPs face two risks compared to holding a balanced portfolio. They capture only a fraction of the gains if the price increases and they bear a disproportionate share of the loss if the price decreases. The table indicates the loss rate $V^p/V^h$ -1, which informs by how much LPs’ wealth is lower given various price variations.

![Loss rates in function of price variations](https://i.imgur.com/PGSy0rG.png)

The fees earned by the LPs during the period may compensate the missing return in the upside and the aggravated loss in the downside.

## Effects of a temporary price change

Next, assume that the price varies from $p$ to $p’$ and, after a while, goes back to $p$. The protocol returns to its initial state, and the pool’s value to its initial market value. Likewise, an investor holding a 50:50 portfolio outside the protocol would get the same market value back.

The fact that the two strategies yield the same result seems at first disturbing. In the pooling strategy, the protocol incurs arbitrage costs twice, a first time when the exchange rate is driven to $p’$ and a second time when it goes back to $p$. In the holding strategy, the investor avoids arbitrage costs altogether, yet ends up with the same final wealth. How is it possible?

The reason is that, contrary to the individual investor, the protocol rebalances the pool to maintain equal shares of apples and pears whatever the new market price. In doing so, it accumulates the fruit which price has decreased and decumulates the fruit which price has increased. This is a profitable strategy when the price reverts to it initial level. On the other hand, the protocol does not rebalance efficiently, giving away return to arbitragers. Overall, the operation is neutral compared to a holding strategy without rebalancing. We conclude that an individual investor who would rebalance, as the protocol does, but at a better exchange rate, would perform better:

![Profitability of rebalancing](https://i.imgur.com/UqfBGu5.png)

In the left-hand figure, after the price change, the protocol transits from A to A’. The investor now rebalances his portfolio from A to A’’. He holds more of the two fruits than the protocol and gets ready for the price reversal. In the right-hand figure, the price reverts to its initial level and the protocol to A. The investor is not anymore in A but in A’’ and outperforms the protocol by an increasing margin. He then could rebalance his portfolio once again from A’’ to A’’’, etc.

The superiority of the holding strategy in the left-hand figure comes from the fact that the investor rebalances along a straight line whereas the protocol performs the same operation along a curved line. Rebalancing costs are linear with the trade size in the first case and have a quadratic shape in the second case.

The excess return of the holding strategy with rebalancing compared to liquidity pooling can be computed by supposing (without loss of generality) that both the investor and the protocol start with one apple and one pear and that the initial price is 1. The pool’s and portfolio’s market values are plotted against the price ratio $p’/p$ which indicates by how much the price deviates from its initial value before returning to it:

![Pool’s and portfolio’s value with rebalancing](https://i.imgur.com/qbGRuhn.png)

The excess return is negligible for small variations but increases at an increasing pace for larger ones. If the price deviates by -18% or +22% before returning to its initial value, portfolio’s excess return is 1%. It increases to 5% if the price temporarily deviates by -36% or +56% and is up to 11% if it deviates by -50% or +200%.

Note that the ability to rebalance after a price change may be hampered by transaction costs (price slippage plus transaction and network fees). The investor may not rebalance for limited price changes for this reason. On the other hand, computed losses are valid for one rebalancing. Excess return should be compounded for a sequence of price variations. The loss is in this case expected to expand with time.

## Impermanent loss

A common view about the risk borne by LPs is that the loss from liquidity pooling is “impermanent”, i.e. vanishes when the price goes back to its initial value. However, the previous analysis has shown that even in this case, LPs forego a fraction of the return compared to holding and rebalancing a portfolio. When rebalancing is allowed, even mean reverting price fluctuations are costly for LPs. The relative loss incurred by LPs comes from the protocol relying on arbitrageurs to rebalance at unfavorable exchange rate.

One could argue that most investors are not willing to rebalance, or simply do not care. However, most of them do not hold a 50:50 portfolio neither, yet this strategy is commonly used as a benchmark to evaluate the risks associated with liquidity pooling. As a matter of fact, we do not need as a counterfactual a strategy that investors actually follows but one that is the closest to what the protocol performs. Since the protocol keeps a 50:50 share of the two assets, so should do the counterfactual strategy.

On the other hand, measuring quadratic rebalancing costs by computing the counterfactual return of a rebalanced portfolio is not immune from conventions. First, the portfolio should be rebalanced only after sufficiently large price variations to economize on transaction costs. Second, price slippage depends on the amount of capital rebalanced and network fees at the rebalancing date. A rule of thumb could be to rebalance the portfolio every time the price deviates by, say, more than 10%. Or to make rebalancing an infrequent occurrence by allowing a higher threshold. The higher the threshold, the more the rebalanced portfolio resembles the non-rebalanced one. At the limit, if the portfolio is never rebalanced, the computed loss of return is a lower bound of actual losses.

## Conclusion

Constant product matching markets offer an innovative way for exchanging assets by allowing users to trade against a liquidity pool funded by LPs. By automating trading and price setting with smart contracts, the protocol avoid middlemen and economizes on platform costs. This allows LPs to earn sizable trade fees. Its functioning demonstrates that an algorithm ignorant of market prices can still trade with knowledgeable counter-parties without spiraling into deficits. Trading under asymmetric information leads however the protocol to forego a non-trivial fraction of the return when prices are volatile, which negatively impact the profitability for LPs. The missing return, commonly known as impermanent loss, is actually permanent if the counterfactual portfolio rebalances as the protocol does. Since an individual investor can rebalance at a better exchange rate than the protocol, the return delivered to LP will always lag behind the rebalanced portfolio, even if the price reverts to its initial value. In practice, LPs must strike a delicate balance between giving away returns to arbitrageurs and accumulating fees to achieve a satisfactory return.

*first published September 2020*


<!--

This post is the first part of an intermediate level presentation of Uniswap and constant product market matching. The second post dives deeper into how the protocol handles price variations, and explains impermanent loss. Go to the end of the second post for non-technical readings. For the maths and technical details, see the working paper.