An analysis of Uniswap markets

Uniswap---and other constant product markets---appear to work well in practice despite their simplicity. In this paper, we give a simple formal analysis of constant product markets and their generalizations, showing that, under some common conditions, these markets must closely track the reference market price. We also show that Uniswap satisfies many other desirable properties and numerically demonstrate, via a large-scale agent-based simulation, that Uniswap is stable under a wide range of market conditions.


Introduction
Many different decentralized exchanges (DEXs) have been proposed using different market maker mechanisms, ranging from classic order-book mechanisms [WB17] to other, more complicated approaches with particular bonding curves [HBB17]. Yet, a simple but surprisingly effective market maker appears to be the constant product market maker used by Uniswap [ZCP18], likely the first and possibly the most popular implementation. These markets provide a simple approach for trading between pairs of coins in a decentralized fashion, and have, in recent years, become a popular (and practically useful) alternative to other types of DEXs.
Additionally, other protocols (such as Celo [KOR17]) have used the idea of constantproduct markets as a decentralized price oracle-a contract that can be queried to find the relative price between two coins of interest. These protocols make use the fact that, if the price indicated by the oracle differs from the true market price of the traded coins, an arbitrageur can always make a profit by trading with this oracle, implying that the price indicated by this oracle is likely close to the reference market price.
In this paper, we present optimal arbitrage actions and bounds under some simple reference market models for the Uniswap contract, showing that Uniswap must closely track the reference market price under common market conditions. We also show that a recent generalization of constant product markets, initially proposed in [MM19], has nearly identical theoretical properties and may be of future interest. Finally, we run a large-scale simulation of agents interacting with the Uniswap contract over a wide range of market parameters, suggesting that the system may be stable under a variety of market conditions.

Constant product markets
A constant product market [ZCP18] is a market for trading coins of type α for coins of type β (and vice versa). This market has reserves R α > 0 and R β > 0, constant product k = R α R β , and percentage fee (1 − γ). A transaction in this market, trading ∆ β > 0 coins β for ∆ α > 0 coins α, must satisfy (R α − ∆ α )(R β + γ∆ β ) = k. (1) After each transaction, the reserves are updated in the following way: R α → R α − ∆ α , R β → R β + ∆ β , and k → (R α − ∆ α )(R β + ∆ β ). We will always require that R α , R β > 0, such that any trade that results in a nonpositive reserve is never fulfilled (equivalently, we say that such a trade has infinite cost). The name 'constant product market' comes from the fact that, when the fee is zero (i.e., γ = 1), any trade ∆ β to ∆ α must change the reserves in such a way that the product R α R β remains equal to the constant k.
In this section, we derive bounds on the marginal price of the market relative to a reference market and show that this market has other desirable properties.

Optimal arbitrage in Uniswap
In the optimal arbitrage problem, we have two coins, α and β, which we can trade either with a reference market or a Uniswap contract. In this problem, we seek to maximize the profit made from trading, say, some amount of loaned coin, ∆ β of coin β to some amount ∆ α of coin α via the Uniswap market. We then trade back the received ∆ α for ∆ β and pay back the loan ∆ β to receive profit ∆ β − ∆ β .
If our profit is positive (that is, if ∆ β − ∆ β > 0), then we say that there is an arbitrage opportunity, since we have made money 'for free' (i.e., by only trading coins within different markets) without taking on any risk. The optimal arbitrage problem then asks: what is the maximum profit that can be made by this scheme?
In the infinitely liquid market case, i.e., in the case that ∆ β = m p ∆ α (where m p is the reference market price of coin α), we can phrase the optimal arbitrage problem as the following optimization problem: with optimization variables ∆ α ∈ R and ∆ β ∈ R, constrained to be nonnegative. Here, (1 − γ) is the Uniswap exchange fee, and the constraint is the definition of a constant product market (1). When written in this form, problem (2) is not obviously convex, though we show in appendix A that it can easily be written in a convex form and then derive an analytical form for the optimal trade amounts ∆ α and ∆ β .
No-arbitrage conditions. Assuming that the market satisfies the no-arbitrage condition (which often approximately holds in practice; see [BL07, §1.2]), we can show that the Uniswap market price deviates from the market price by at most a factor of γ.
The marginal price of coin α in Uniswap is defined as the price of an infinitesimally small trade. This price can be found by differentiating the constant-product market formula: where we have written m u = R β /R α for the Uniswap price of coin α without the fee. We can always make a nonzero profit if the Uniswap marginal price of α, γ −1 m u is smaller than the market marginal price m p , by performing a small enough trade. Assuming there is no arbitrage, this means we must have Similarly, by swapping α for β and combining the resulting statements we get the following bounds on the Uniswap market price, relative to the true market price, m p : assuming no-arbitrage conditions. This suggests that, in practice, the larger the trade fees are, the larger the gap between the true market price and the Uniswap market price may be. For example, in the case that the trade fee τ = 1 − γ is small, bound (3) is approximately equivalent to While we derived these conditions using a simple argument, we can also easily derive them by analyzing problem (2) and noting that its optimal value is nonzero if, and only if, there is an arbitrage opportunity. For more details, see appendix A.

Extensions of the optimal arbitrage problem
There are several natural extensions to the optimal problem (2), which retain most of its useful properties.
Risk models. There are many factors which could potentially cause an agent to fail to close an arbitrage opportunity, including noisy information, front-running [DGK + 19], and delay in trades-the latter of which is quite common in distributed platforms. In particular, it may not be desirable for an agent to perform a trade with the exact solution of problem (2).
In this case, we can add an additional term penalizing large trades: in other words, we can assign some 'cost of risk' which can be any convex function f : R 2 + → R which is nondecreasing in its second argument. This gives a problem of the form: It should be noted that problem (4) can be written in a convex way and is the problem we use to simulate arbitrageurs in our agent simulation (see §4.2 for more details). One example of a risk function f could be a model of the resulting changes in market price due to the arbitrage trade. A common (and simple) model for the marginal market price m : R + → R + after a trade of size 0 ≤ ∆ α ≤ η −1/ξ is that the resulting price is with any η ≥ 0, ξ > 0. The resulting risk function, f (∆ α ) = ∆α 0 (m p − m(t)) dt, is convex. See appendix A.1 for more details and extensions.
Additionally, in this model, unlike in problem (4), an arbitrageur is not guaranteed to reach the no-arbitrage condition in a single round if the penalty function does not reflect the true underlying market movement.

Other conditions
In this section, we show a few basic and useful properties which Uniswap (and other constantproduct markets) satisfy.
Increasing product constant. For every trade, the product constant k is nondecreasing (and strictly increasing if γ < 1). Let R t α > 0, R t β > 0, and k t > 0 be the reserve of α, β, and the constant product at trade t. If trade t + 1 sells ∆ β coins β for ∆ α coins α, we have (by definition, see (1)): where inequality always holds strictly except when γ = 1. So, if γ < 1, we have that k t < k t+1 , always.
No-depletion property. It turns out to be impossible to fully deplete Uniswap of all coins only by trading α and β, even if the attacker has an unbounded amount of coins. We can easily show that the total reserve is always bounded from below. This follows immediately from applying the arithmetic-geometric mean inequality [BV04, §3.1.9]: Since this is true and k is nondecreasing (and usually strictly increasing) after each trade, then the total number of coins in Uniswap can never decrease below the twice the square root of the initial product by only trading between coins α and β.
Increasing liquidity with increasing reserves. Intuitively, the larger the amount of reserves, the less any one trade will cost. The marginal cost change of Uniswap (the negative of the infinitesimal price change of the Uniswap market after an infinitesimal trade) can be computed by differentiating (1) twice and is given by where m u = R β /R α is the Uniswap price without fees. Note that (6) is strictly decreasing as R β increases (assuming m u , the Uniswap price, stays constant). We can similarly show this property directly by assuming that we have two markets, one with strictly larger reserves R β > R β , and both with price In this case, assuming we trade ∆ β coins with both markets, we can show that the markets will have a price gap of This price gap is always positive in the case that R β > R β and this construction gives essentially a more precise version of (6). The derivation can be found in appendix B.
Liquidity provider returns. In the no fee case (i.e., when γ = 1), we can easily compute the portfolio value of the Uniswap contract (and, correspondingly, any liquidity provider). Let R t α , R t β , and m t p ∈ R + be the reserves for coin α, coin β, and the market price of coin α, respectively, at each time t = 1, . . . , T .
In the no fee case, the no-arbitrage bounds (3) imply that, m t p = R t β /R t α , while the definition of a constant product market (1) implies that R t α R t β = k for all t. Combining both statements: We can use this expression to write a simple form for the relative return for Uniswap between time t − 1 to t, given by This implies that the total relative gain for a Uniswap contract is and the total portfolio value is Since δ t depends only on the relative ratios of R α and R β , the result holds even when liquidity providers add tokens or remove tokens from the reserves-although in practice, as suggested by (6), the price is likely to be less stable in the case of smaller reserves. See appendix C for further discussion.

Discussion
Because the arbitrage problem (2), and its risky variant, problem (4), are convex, we suspect that the no-arbitrage assumption is very likely to be met in practice. The convexity of this problem additionally implies that arbitrage can be efficiently performed even across several Uniswap markets (see appendix A for more details). As shown in (3), we analytically observe the effect that the Uniswap market fee has on the price of the market: the bounds guaranteed by the no-arbitrage assumption become looser. In other words, as the fee increases (or, equivalently, γ decreases), we expect the Uniswap market to deviate further from the price of a given reference market.
These properties, combined with results (5) and (7), suggest that constant product markets are likely to be robust in the the practical setting where the number of tokens in reserve is large and the number of trades is also large.

Constant mean markets
A constant mean market is a market which generalizes constant product markets. First introduced in [MM19], constant mean markets satisfy the following equation in the absence of fees: where R i are the reserves of coin i = 1, . . . , n, w ∈ R n + are the weights associated with each coin, and k ∈ R + is the constant product. In this case, the weights all satisfy w ≥ 0 with 1 T w = 1. In other words, in the absence of fees, constant product markets ensure that the product of its reserves stays constant, while constant mean markets ensure that the weighted geometric mean of the reserves, R i for i = 1, . . . , n, stays constant.
Similar to constant product markets, trading ∆ j amount of coin j for some amount Λ j of a distinct coin = j should always satisfy the equation, where (1 − γ j ) is the percentage fee associated with trading coin j. The corresponding reserves, R j and R are updated as in §2, as is the mean constant, k.
Note that constant product markets are a special case of a constant mean market where n = 2 and we have w 1 = w 2 = 1/2 and γ 1 = γ 2 , with the constant product k of (1) replaced with its square root.

Optimal arbitrage problem
We can write the optimal arbitrage problem for constant mean markets in the following way: where we will assume that Λ ii is constrained to be zero for notational convenience. 1 The variables in this optimization problem are the amount ∆ ∈ R n whose entries state how much of each coin to purchase from the external market, while i, jth entry of Λ ∈ R n×n states how much of coin i to trade for coin j.
Since the weighted geometric mean is a concave function that is increasing in all of its arguments [BV04, §3.1.5], it turns out that the equality constraint in problem (11) can be relaxed to an inequality constraint to get an equivalent, but convex, optimal arbitrage problem [BV04, §3.2.4]. See appendix D for more details.

Extensions and properties
Surprisingly, almost all conditions and properties (except the no-arbitrage condition of (3)) that hold for constant product markets also hold for constant mean markets in a similar form. We describe a few cases below.
Extensions. All of the same extensions given in section §2.2 hold for problem (11). More specifically, for any convex function f : R n 2 + × R n + → R, which is increasing in its first n 2 arguments and decreasing in the remaining n arguments, the following convex relaxation of (11) is an equivalent (but convex) problem with the additional penalty term, f : with the same variables, ∆ ∈ R n and Λ ∈ R n×n , as problem (11).
Properties. Additionally, all of the same properties given in §2.3, except the asymptotic result (7) and the expressions for Uniswap returns (8) and value (9), hold essentially in their exact form for constant mean markets: all instances will have an nondecreasing product constant and satisfy the corresponding no-depletion property. The notion of increasing liquidity with increasing reserves also holds and can be easily derived from [MM19, Out-Given-In].
No-arbitrage conditions. It is, in general, not clear that there exists a closed-form solution for the no-arbitrage conditions specified in §2.1. It is possible to give simple necessary (but not sufficient) conditions on each pair of coins found in a given constant-product market via a similar argument to the one in §2.1, but we expect the general conditions are more complicated.

Discussion
We present these results for constant mean markets as they carry over nearly immediately from those given in §2. Though we suspect that markets which satisfy the constant mean property, such as Balancer [MM19]-where the idea originated-may become more important in the near future, we focus on the specific case of Uniswap (and, more generally, constant product markets) as other protocols such as Celo [KOR17] heavily depend on the robustness of this particular market maker mechanism.

Agent-based simulation of Uniswap markets
While the properties presented in §2 lead us to believe that the Uniswap market is likely wellbehaved under most scenarios, it is hard to make stronger claims about the robustness of the Uniswap market mechanism without making assumptions that are unlikely to be realistic.
To verify this experimentally, we created an agent-based simulation by using a the Gauntlet DSL to specify how several types of agents interact with the current Uniswap contract 2 on a simulated Ethereum blockchain. The simulation environment interacts with the Uniswap contract deployed on a simulated blockchain via Python bindings. The environment allows for configuration of the network's initial conditions, including distributions of agent behaviors and agent-specific parameters.
The simulation is run for a pre-defined number of time steps. For each simulated time step, environment state variables are updated based on the state of the on-chain contracts. We additionally evaluate policies for adding new agents to the environment. We evaluate the utility of an action for a given agent, and execute agent actions that have positive utility by submitting the corresponding transaction to the blockchain.

Simulation markets
In the current simulation, we have two possible markets for agents to trade with: one is given by the Uniswap contract and the other is given by a simple market model with random noise.
Uniswap market. When interacting with the Uniswap contract, an agent has a few possible actions they can perform: the agent can either (a) trade coins α for β (and vice versa) subject to the constant product market equation (1), or (b) add or remove liquidity.
In the latter case, an agent is able to add, say, ∆ β amount of coin β to reserve R β and is required to also add R α ∆ β /R β of coin α to reserve R α . The agent is then awarded where R UNI is the total amount of outstanding UNI coins given by the contract. The agent can also similarly remove liquidity by burning ∆ UNI coins. The contract then gives the agent and burns the given ∆ UNI coins. This market mechanism allows the agents who purchase these UNI coins, often called liquidity providers, to earn a profit given by the exchange fee, assuming the market price stays constant. Additionally, it provides a mechanism for adding and removing to reserves, thus making the Uniswap market more liquid, as shown in section §2.3.
For the remainder of this section, we will assume the price of a UNI token is exactly given by the market prices of the equivalent amount of coins α and β that would be received by burning the token. Additionally, the Uniswap contract defines γ = .997, which is the value we use from here on out.
Reference market. The reference market follows a simple power law model where the price m p of some coin α, is updated in the following way: where κ ≥ 0 and ξ ≥ 0 are given in the problem data. While it is possible for an arbitrageur to solve the arbitrage problem exactly (as it is a special case of (4)), we choose a simpler risk model for the arbitrageur as the true market price model is not known in practice. We additionally update the market price every time step (after all agents have completed their actions) in the following way: Here X ∼ N (0, 1) is drawn from a normal distribution and µ, σ ∈ R represent the mean returns and volatility of the market when no trades are performed.

Simulation agents
There are three broad classes of agents used in this simulation: arbitrageurs (who attempt to profit from deviations between Uniswap and the market), liquidity providers (who hold portfolios of UNI coins and currencies α and β), and traders (who trade coins with the Uniswap market, subject to simple rules). We describe each type of agent in detail below.
Arbitrageurs. Arbitrageurs seek to maximize their profit by trading between the Uniswap market and a reference market. An arbitrageur agent solves an instance of problem (4) with a simple quadratic cost of risk model: and performs the necessary trades. Here, ρ α , ρ β ≥ 0 are parameters which control the penalty incurred for a trade. We use this model instead of the riskless case of problem (2), as live systems have noise during trades (e.g., network delays) such that opportunities found by exact minimization of the riskless problem (2) may not be easily executed or may close during the time it takes to perform the trade.
Additionally, we are able to model a wide variety of risk-taking behavior by arbitrageurs by, for example, increasing the parameters ρ α and ρ β to have an arbitrageur who is less prone to perform risky (large) trades, even with large arbitrage opportunities available.
Liquidity providers. There are two types of liquidity providers we model in this simulation.
The first are the initial liquidity providers, who begin the simulation by providing some amount of coins α, and β to the reserve and seek to gain profits by taking fees from Uniswap trades. We assume these liquidity providers will not withdraw their position until the end of the simulation.
The second are rational liquidity providers. These agents perform Markowitz portfolio optimization (see [BV04,§4.4.1]) on the three possible coins in the market: α, β, and the corresponding UNI coin minted from the Uniswap market. Each agent then solves the (convex) portfolio optimization problem, and makes the appropriate trades to rebalance their portfolio. In this problem, x ∈ R 3 is the vector containing the portfolio positions of α, β, and UNI respectively. The problem datâ µ ∈ R 3 is the vector of exponentially-weighted average returns for each of the three coins (with respect to the reference market),Σ ∈ S 3 + is the exponentially-weighted covariance of returns, and λ > 0 is the penalty incurred by the risk. Since (13) is not known to have a closed form solution, we set up and solve problem (13) using the CVXPY [AVDB18] modeling language and the ECOS solver [DCB13] in our simulation.
The rational liquidity providers simulate agents who seek to maximize profits by trading their positions in each coin and holding the respective coins to maximize their expected return on investment, based on observed historical averages.
Traders. The final agent we model is a trader. In this case, the trader seeks to trade some amount ∆ α of coin for some second amount ∆ β (or vice versa), so long as the price of trading ∆ α coins on Uniswap differs no more than a constant percentage off from the same trade in the reference market.
In a way, traders embody the 'demand for liquidity,' or the fact that trades on Uniswap might happen due to exogenous influences. In our case, a trader will draw ∆ α (or ∆ β ) from some probability distribution and check if performing this trade in the Uniswap market is at most some percentage more expensive than performing it in the reference market. If not-i.e., if the agent is able to trade with Uniswap for a reasonable price-then the agent makes the trade using the Uniswap contract. Otherwise, no trade is performed.

Results
The results of our simulations suggest that the theoretical results derived above hold in practice under a wide variety of market conditions. Arbitrage bounds. Figures 1 and 2 show that, even under the presence of outside noisesuch as random noise, or changes in reserves due to rational liquidity providers-the marginal Uniswap price stays within the predicted no-arbitrage bounds. In particular, figure 1 shows when the market has a small amount of noise and little drift, while figure 2 shows this when there is large negative drift with moderate noise. We find that these bounds hold in our simulations, even under large amounts of market noise and large drift rates, so long as the trades performed are not large.
Due to the discrete nature of the simulation, if a trader is the last agent to run at each time step, the no-arbitrage bounds could be broken as an arbitrageur may not have yet been able to perform arbitrage. While this is true (and is due to the nature of the simulation), the final result still clearly tracks the market price, as shown in figure 3.
Initial liquidity provider returns. In the simulation, we also record the utility of the initial liquidity providers, defined as the difference between the value of the respective UNI coin the agents hold, as defined in §4.1, and a portfolio composed of the coins α and β traded in for UNI at the start of the simulation.
As shown in figure 4, we find that in almost all of our simulations, initial liquidity providers end up having negative utility (using this definition), over most varying conditions. More specifically, we note that initial liquidity providers only have positive expected value when the mean market return is close to zero, as they earn revenue from all transaction fees while not falling behind an equivalent portfolio of the given pairs of coins. This approximately follows the result given in (8), except that liquidity providers earn fees in this case.

Conclusion
Though simple, constant product markets and their generalizations have very nice theoretical properties (such as fairly strict no-arbitrage bounds on the reference price) which appear to hold in practice. Our simulations confirm that this is the case under a wide range of different market parameters and conditions, implying that the use of constant product markets as price oracles is, at least at first glance, sound.
Additionally, we suspect that there is an even larger class of automated market maker mechanisms which satisfy the above properties, and it would be interesting to further explore its mathematical properties. We leave this possible generalization for future work.

A The Uniswap arbitrage problem is convex
We can easily show that this problem is convex by using (1) to solve for ∆ β , Note that ∆ β is then a convex function of ∆ α as x → 1/x is convex for x positive, and a convex function composed with an affine function is convex [BV04, §3.2.2]. The resulting (equivalent) problem, with variable ∆ α is then convex.
Since the problem is one-dimensional, the fact that problem (2) is convex is not immediately useful, but it can lead to several simple generalizations. For example, the optimal m-stage trading strategy with several interacting constant product markets can be efficiently evaluated in this case.
Optimality conditions. Note that a maximum of a concave function over an interval happens either at (a) the interior of an interval or (b) at its boundary. In the latter case, it is not hard to show that a maximum is attained at the point on the boundary closest to  Figure 4: Varying utilities for initial liquidity providers over varying market conditions. As before, µ is the mean market return and σ is the volatility. the unconstrained maximum. 3 Because of this, we only have to consider the unconstrained version of problem (14), over the interval [0, +∞).
In this case, the optimality conditions are the point for which the objective of (14) has zero derivative, which happens when By the statement above, then the optimal solution to (14) is where (x) + = max{x, 0} for x ∈ R. The optimal ∆ β can be easily derived using the ∆ α derived above and the constant product formula (1). Now, note that ∆ α is zero if, and only if where m u = R β /R α is the marginal Uniswap market price of α without fees.
Since the objective of (14) is zero whenever there is no arbitrage opportunity (and the objective is only zero at ∆ α = 0, by strict convexity), then the above implies there is no α → β arbitrage in the presence of an infinitely liquid market. Swapping α for β yields the same result derived via no-arbitrage in the general case:

A.1 Extensions to Uniswap arbitrage problem
In a similar vein to (14), we can add any penalty given by a convex function f : R 2 + → R which is nondecreasing in its second argument to the objective. This yields yet another convex optimization problem: with variables ∆ α ∈ R and ∆ β ∈ R. This problem is equivalent to problem (4) as the objective function is decreasing with respect to ∆ β , implying that the first inequality constraint is always tight at an optimal point. Additionally, problem (15) is also convex as it is maximizing a concave function, subject to convex constraints. [BV04, §4.2.1] Market models. One particularly useful example of such a function f is for modeling the market response of trading coin α for coin β. In particular, if the marginal market price m : R + → R + is some decreasing function of the total amount of coin ∆ α traded, satisfying m(0) = m p , then the slippage cost of trading ∆ α coin for ∆ β is given by, with f convex (as its derivative, −m, is increasing by definition). While several simple market models exist, the one we use in this paper is a special case of with ξ > 0 and η ≥ 0. This results in

B Derivation of price gap
By definition (1), the price of ∆ β can be written as Dividing the numerator and denominator by R β > 0 and using the fact that (1 + x) −1 = 1 − x + O(x 2 ) we get the (nearly final) result: Subtracting ∆ α from ∆ α and using the fact that R β < R β then yields the statement given in (7).

C Uniswap portfolio value under Brownian dynamics
Assume the trajectory of the market price m t p follows a geometric Brownian motion pro- where µ ∈ R is the drift, σ ∈ R + is the volatility, and W t is a standard Brownian motion [Øks13, §3]. Without loss of generality, let m 1 p = 1. The portfolio value then has expectation where we have used the fact that the nth moment of a log-normal random variable X is given by [Wal96] E [X n ] = e nµ+n 2 σ 2 /2 .
This argument shows one could replicate the time T payoff of a no-fee liquidity provider with less initial capital than that required in the constant product market itself, which, in turn, implies that the portfolio value at time T must grow at a rate of e T 8 σ 2 under the noarbitrage hypothesis. The choice of γ that gives this growth rate is the no-arbitrage fee. A simple replication of a volatility harvesting strategy can be used to show that some such γ exists under mild conditions on µ and σ [MTZ11, §11].

D The arbitrage problem in constant mean markets
The problem with variables ∆ ∈ R n and Λ ∈ R n×n and with weights w ≥ 0 and 1 T w = 1, is equivalent to problem (11) in that any optimal solution for problem (17) is optimal for problem (11). Clearly, if any optimal point of (17) has the first inequality constraint holding at equality, then this point is optimal for (11). Because the objective is decreasing in ∆ i for each i = 1, . . . , n and increasing in Λ ij for each i, j = 1, . . . , n, while the geometric mean function in the inequality constraint is decreasing in Λ ij and increasing in ∆ i , then the inequality constraint is always tight at equality at any optimal point.
Since the weighted geometric mean function is concave [BV04, §3.1.5], then problem (17) is a convex problem.
We also note that problem (11) is log-log convex [ADB19] with the obvious change of variables. While we do not explore this connection here, we suspect that this approach might provide a simple way of stating what class of functions can be used as an automated market maker mechanism such that the resulting no-arbitrage bounds are useful.