Automated Market Makers(AMMs), or more accurately, Constant Function Market Makers(CFMMs), are described as permissionless marketplaces for the supply and demand of liquidity to meet directly with no ‘filtration systems’ otherwise referred to as, trade matching engines.
It's like being at a bazaar where all the sellers with similar commodities decide to pool their assets together and put a theoretically infallible algorithm in charge of it. When buyers come they simply interact with the algorithm, based on a set of rules in order for an exchange to be valid. Whenever a seller wants to close shop for the day, they receive a proportional percentage of the total value of sales made, based on their contribution. Thus, CFMMs eliminate the need for matching engines/systems and their troubles.
One of the first practical iterations of what decentralised finance could achieve, the CFMM space has exploded from "simple" xy = k type protocols, to "golearnsomeconvexoptimisationbro" type protocols, but it's for the best! This series (hopefully🤞) aims to provide a somewhat comprehensive education for market participants interested in learning more about CFMMs. Hope you enjoy reading this as much as I enjoyed researching and writing about it, cheers.
This piece is a condensation of various published research and formalisations/generalisations of related concepts. It (at least attempts to) introduces the basic concepts that enable basically any CFMM. I'll do my very best to provide the links to original works where possible. All mistakes are mine, liberties have been taken. Thank you.
GENERALISATION OF CFMM PARAMETERS
In the beginning, I likened Constant Function Market Makers to a bazaar with the "supply" side's assets put together and put under control of an algorithm. The suppliers of assets are known as "liquidity providers" or simply LPs, the takers/buyers of assets are referred to as traders and can be informed (arbitrageurs) or otherwise. The algorithm that links the asset taker to the limited pool of supply is referred to as a "trading function". The trading function makes use of another algorithm called the “pricing function” or invariant to determine the prices at which exchanges should occur.
Thus, a Constant Function Market Maker may be defined as a decentralised factory of smart contracts, that holds at least two assets and specifies a trading function which allows users to contribute assets to the contract(s), in order to enable trades between other users and the contract(s), based on the prices of contributed assets determined by their evolving quantities.
The evolution of a CFMM's state over time can be modelled with state space transition functions of the generalised form:
where “a” is any action permitted by the CFMM which modifies any of its parameters and “S” and “S’” are, respectively, the initial and final states of the CFMM due to “a”.
The present state, S, of a CFMM, can be represented as shown:
Where:
The common actions which lead to state transitions in a CFMM are adjusting liquidity provisions via deposits or withdrawals(i.e. when new bazaar sellers join or old ones leave) and trading (i.e. when a valid exchange occurs between a buyer and the algorithm). Both actions are governed by the following constraints
During pure liquidity provision or withdrawal, the prices of assets in a CFMM must remain constant in the form:
During trades, informed or uninformed, the value of the trading function must remain constant.
As with almost every other rule, there are exceptions:
a. Asset prices can vary during liquidity provision, if assets are added or removed disproportionately from the existing defined reserve ratio. For example, if the reserve ratio for a CFMM is set to 50:50, but if an LP deposits his assets in any other arbitrary ratio, then it isn't purely a liquidity provision. This is because arbitrages are incentivised in order for the pool to be rebalanced to the proper reserve ratio.
b. The value of the trading function can vary after trades in the presence of a nonzero fee structured CFMM. This is because the fees charged on trades are used to expand the pool.
Price impact function (g):
this is a unique function used to represent market price changes in response to executed trades. g(0) is used to represent the marginal price of the asset before a trade. g connects a CFMM's marginal price before a trade to its marginal price after the trade is executed; and g(-∆y) is used to represent the marginal price after a trade buying a quantity, ∆y of the traded asset Y, from the CFMM is performed.
According to Angeris et al¹; two assumptions can be made concerning the price impact function
a. Its continuity: g is regarded as a continuous function, implying that changes in the size of the trade, no matter how small, will result in changes in the price impact of the trade.
b. Its non-decrement: g is assumed to be a non-decreasing function, so that larger trade sizes will always lead to higher marginal prices.
Two bounds exist on the price impact function plane of a CFMM:
µ-stability: for any given value of the price impact function, g, trades will always have a proportional impact on the CFMM's price. This feature enables market manipulation, amongst other things. It is counteracted by the introduction of an upper bound, in the form of a nonnegative constant μ.
Thus, g is said to be μ-stable when trades have a proportional impact on the market price, bounded by ∆μ, where ∆ is the trade's size.
Mathematically, if:
then g is μ-stable for all positive values of ∆.
(The LHS of the inequality represents the first derivative of the price impact function wrt a given trade size, which is a measure of the function's sensitivity to changes in trade sizes).
Also:
Where:
p_∆ is the price due to g(-∆), i.e. the price of the CFMM after a trade of size ∆ has been executed.
Summarily, a μ-stable CFMM has only mild reactions to trades regardless of their size, and price impact changes smoothly in proportion to trade sizes¹.
κ-liquidity: the liquidity depth of a CFMM (or any other market) plays a significant role in its reaction to trades of large sizes. Commonly, in CFMMs, the price of an asset is directly tied to the quantity of the asset contained in its reserves, such that large trades will often cause mispricing of assets, which, in turn, leads to volatility and instability of CFMM prices as arbitrageurs race to capture the discount. This problem is counteracted by the introduction of a nonnegative, constant lower bound, κ.
If g is κ-liquid, then the price impact after a trade of size ∆ is at least κ∆ i.e.,
Where, again, p∆ is the price due to g(-∆)
Summarily, a κ-liquid CFMM ensures that the slippage of a trade is proportionally defined compared to the trade's size. κ can also be regarded as a measure of a CFMM's curvature.
In practical iterations, the bounds κ and μ may only hold for a certain interval of trade sizes. That is, CFMMs can be both μ-stable and κ-liquid during some trades yet experience huge price impacts and erratic pricing on trades outside an often definable bound.
Thus, it is possible for g, the price impact function, to be both μ-stable and κ-liquid with κ ≤ μ, causing it to be mildly sensitive to trading activity, while having an upper bound on the slippage a trade can induce.1
Trading function (ψ):
this function keeps track of the CFMM's state, processing a proposed trade in tandem with the CFMM's existing reserves as inputs, and outputs a scalar value which represents the marginal price of the proposed trade while making sure the invariant (a simplification of the trading function) is kept constant. It is responsible for determining whether trades on a CFMM are accepted or not. The trading function is always assumed to be a concave, increasing, and twice continuously differentiable function in formal literature.2
Its concavity ensures that the produced trading sets are always convex and closed, while its increment ensures that the images produced by the function are in the domain of real, positive numbers so that input trades cannot be negative.
Generally, proposed trades are accepted when they satisfy the equality:
i.e. for trades to be valid, the value of the CFMM's reserves must be kept fairly constant. This is obvious since a trader shouldn't be able to provide less value than they extract during a simple asset exchange.
The two major forms utilised are:
- The linear trading function: which is formally represented as
with simplified and practical form
where the left hand side represents the tender/numeraire asset's value discounted by a fee, and the right hand side represents the value of the traded asset received by the trader.
The linear trading function is utilised famously in constant sum market makers (CSMMs) such as the original mStable.3
- The geometric mean trading function: more accurately, the weighted geometric mean square function. it is formally represented as
ie
where "r_i" is the reserve of asset i, and "wi" is the weight associated with asset i.
the weight is usually a hyperparameter, hard coded and only adjustable via governance. the weights of assets on a CFMM will always sum up to unity.
geometric mean CFMMs with weight, w = 1/n, where n = 2, are referred to as constant product market makers (CPMMs) a famous example being Uniswap4.
Marginal price (m):
a vector of prices which can be obtained for an arbitarily small trade at some specific reserve values. It is not necessarily an exchange rate, since trades rarely ever occur at that price, it is more of a measure of the rate at which the reported price of an asset changes on a CFMM as its reserves fluctuate. It is used to represent the sensitivity of an asset's price to variations in its reserve quantities.
It is specifically defined as the first order taylor approximation of the trading function of a CFMM, denoted simply as
where the left hand side is the value of the tender basket based on marginal price(s) and discounted by the fee, and the right hand side is the value of the received basket based on the marginal price as well.
it is important to note that, as stated earlier, ∆_y is the unique solution (output) to
for any given ∆_x
That is to say, the quantity of asset a trader receives on completion of a trade is a unique solution to the trading function of the CFMM, considering the reserve and tendered asset quantities.
where
Trading Sets, Path Deficiency and the Reachable Reserve Set:
the trading set of a CFMM is simply the set of all feasible trades at some fixed reserve value. It can also be defined as a set of alternatives to a feasible trade, wherein there exists at least one strictly better trade in terms of either cost or payoff. it is a convex, closed set.
Path deficiency is an inherent property of CFMMs that ensures that trading through a pool makes its reachable reserve set at state S to be just marginally different from its reachable reserve set at state S'. In plain English, path deficiency ensures that the reserves of a pool are bounded from below, during and after any set of feasible trades has been performed such that a pool's reserves aren't totally depleted. It achieves this by ensuring the value of the input trade is almost always greater than the value of the output trade.
As a general rule, no single feasible trade should be able to deplete the reserves of a CFMM. to achieve this, the total reserves have a minimum bound referred to as the reachable reserve set. the reachable reserve set R(S) of a CFMM can be diminutively defined as the subset of its reserves which can be exhausted by a feasible trade as the pool transitions from an original state to a later state. It is a representation of the possible reserve combinations achievable by single trades, at some specified reserve value and ensures that the reserves remain above a certain threshold.
Summarily, in path-deficient CFMMs, a trade chosen from the trading set should always decrease the reachable reserve set, hence keeping the CFMM stable.5
Reported Price (p):
formally defined as the slope of the supporting hyperplane of the trading set, scaled by the numeraire asset. This is the actual price advertised to a trader by a CFMM for a trade [∆_x - ∆_y]. Since multiple supporting hyperplanes exist at any given point for a CFMM, there are multiple valid prices for an asset at any given set of reserves. However, only one is displayed to a trader based on the CFMM's designer's choice of price vector.
Price Vector:
this is a hyperparameter in the form of a vector responsible for assigning prices to tokens in a CFMM in terms of some measuring currency. it is defined as the gradient vector responsible for indicating the direction of steepest increase in the value function.
the value function is essentially the value of reserves of a CFMM. it is obtained by summing the products of token quantities and their corresponding exchange rates.
Fee rate (f):
in practical iterations, CFMMs charge users a fee per trade. This fee is expressed as a percentage tax charged on either the output or, more commonly, input basket of a trade routed through a CFMM.
To include the fees explicitly, the traded coin (ie asset sold to the CFMM) is multiplied by f, where; 0 ≤ f ≤ 1.
The fee margin price is related to the feeless margin price via
where the proportionality factor depends on the fee percentage and the quantity of the traded coin. so that;
The fee is often a constant value predetermined by protocol designers and adjustable only via governance procedures.
fees and volumes:-
it shouldn't be new information that the fee structure of a CFMM is one of its selling points for traders and arbitrageurs. However, most zero-fee CFMMs forget that without the LP, neither agent would be trading on them. the LP takes on directional risk when they deposit their asset(s) so that the other agents can take even more directional bets. Thus, the more capital the LP is willing to put up, the better it is for everyone in the system, except probably themselves.
intuitively, it makes sense that a race to the bottom ensues as CFMMs try to keep their fees as low as possible in order to attract as much trade volume as possible. However, this isn't the case practically as has been formalised in research.6 It is shown that a Nash equilibrium exists where pools gain nothing by changing their fee structure, ie trade volumes do not increase but LPs may be disincentivised.
assuming we have two CFMM pools, A and B, which offer an asset pair X-Y for trading. if pool A is "larger" than it's competitor B, it might be expected that the latter should charge higher fees in order to keep its LPs incentivised. However, it is proven that the larger pool should always be allowed charge a higher fee, primarily due to its market power. In the smaller pool with lesser fees, the fees earned per trade per LP is shown to be higher, hence pool B LPs have relatively better payoff. This causes liquidity to flow from pool A to pool B as LPs seek to maximise payoff, till an equilibrium is reached where both pools have equal or near-equal values.
When pools A and B are the same size, the Nash equilibrium is almost nonexistent as traders are incentivised to trade on the marketplace with the lower fee structure. hence, when competition is fierce, a race to the bottom is imminent but hardly ever occurs in practical iterations due to concepts such as fee dynamism, pool splitting and liquidity mining.
Slippage aka loss rate (L):
the slippage is the difference between the reported/advertised price and the price at which the trade actually occurs. It is the premium on the output basket of a trade, informed or otherwise, due to the adherence of a CFMM to its pricing function. It is often expressed as an adjustable value on DEXs so that traders can customise their slippage to get their trades accepted quicker by the cfmm, often with accentuated costs.
Slippage threshold is a customisable hyperparameter which agents can use to specify how much devaluation (in percentage) they are willing to accept on the output basket of a trade, due to slippage.
Impermanent/Divergence loss aka quadratic rebalancing costs:
this is the loss in value of reserves held in a CFMM when compared to holding an equivalent value of reserves outside the pool.
AGENT ACTIONS & PROFITABILITY
This section will be considerably shorter than the previous to prevent stressing the readers. However, all important and deserving topics will still be treated in-depth, so make sure to subscribe in order to join this adventure into the murky waters of CFMMs.
There are three types of agents that interact with CFMMs;
Liquidity Providers aka LPs
Traders
Arbitrageurs (aka informed traders)
Liquidity Providers:-
parties who contribute their assets to the reserves of a CFMM, or liquidity pool, in order to enable trades, in return for a share of fees earned from said trades. Protocols commonly maintain records of LP weights, often represented as a fungible token, which shows the fraction of a pool's value which any one liquidity provider has claim to so that accumulated losses or gains due to informed trades or pool value volatility are distributed pro rata.
Liquidity Provision: Liquidity is essentially the "supply" side of a functional CFMM. Liquidity providers (LPs) provide their assets for use by other interested parties who are, in most cases, taxed for their actions. These LPs are traditionally rewarded with a pro rata share of generated fees but, depending on protocol designs there are opportunities for hypothecation of the "LP token" which represents an LP's weight in a pool.
LP Profitability: A Liquidity Providers' portfolio value is tentatively defined as the value of the assets an LP has locked in a CFMM pool. This value is a constantly changing one as it is subject to trades, both uninformed and informed, till whenever the LP decides to "withdraw liquidity".
In most cases, traditional liquidity provision is simply a "get-poor quick" scheme, as the portfolio value is subject to quadratic rebalancing costs (commonly referred to as impermanent loss) which arise due to
a. the curvature of a CFMM,
b. the price processes of the assets being supplied, or simply price level independence, and
c. the interactions of other agents with the CFMM.
An established model of this phenomena is that, providing liquidity for mean-reverting, low volatility assets gives better returns on low curvature CFMMs(as shown in 2).
Uninformed trades and LP returns on low curvature CFMMs-
considering a trader who wants to buy some amount of the traded asset on our μ-stable CFMM. Assuming their proposed trade is accepted, this purchase causes slippage in the reported price, whose extent is dependent on the trade's size. This slippage imposes an opportunity cost on the LP's portfolio value, as it attracts arbitrageurs who seek to rebalance the pool and harvest the premium.
The core assumption under which LP Profitability is usually studied is that all trades are informed which implies the existence of an external, more liquid marketplace which enables arbitrage when price dissonance is very obvious. In such cases, the pool (and consequently liquidity providers) will lose money each time a trade is routed through it because the arbitrageur extracts the more valuable asset and leaves the less valuable one in the pool.
There are numerous benchmarks for LP profitability not limited to
a. LP holdings vs unbalanced portfolio (otherwise known as the “50:50 hodl strategy”)
b. LP holdings vs. all-in portfolio
c. LP holdings vs Arbitrageur profits
Traders:-
parties that attempt to trade some given quantity of assets they own for a quantity of any other asset(s) they want in any number of ways, such as token-token swaps, token-basket swaps or basket-basket swaps. Generally, for any number of nonnegative quantities of an asset a trader offers a CFMM, the CFMM pays the trader their desired asset(s) of supposedly equal monetary value while keeping the offered asset on the condition that the pricing function traditionally known as the scoring rule is kept constant.
Arbitrageurs:-
assets in most cases can be traded across a plethora of marketplaces with varying liquidity depths and pricing methods. This commonly results in differences in prices of the same asset across marketplaces. When said differences are more obviously pronounced, arbitrageurs trade between two or more marketplaces in order to return prices to a mean. Hence, given that an infinitely liquid reference market exists, which displays more accurate prices than our CFMM pools, the arbitrageur is able to borrow any quantity of an asset X bounded by the given pool's reachable reserve set, and trade it on either market for a guaranteed profit, on the condition that the loan is repaid.
Arbitrageur Profitability: arbitrageurs have a non-trivial advantage over other participants, especially LPs. infact, according to a study by Wang et al7; 99.7% of atomic arbitrage trades ended up profitable. They are participants who are able to adjust discrepancies in price of the traded asset, between our CFMM and a reference market, by buying at a discount and selling at a premium between markets, or any other number of complex strategies.
Results obtained in various studies and formal literature shows that their profitability is influenced by
a. the curvature of the CFMM
b. the fee structure of the CFMM, and
c. the premium between marketplaces.
Generally, the value of the input/forward trade must be less than the value of the output/backwards trade to ensure profitability.
Path deficiency and Arbitrageur Payoff:-
generally, in path deficient CFMMs, arbitrageur payoff is easier to determine and is obtained by- maximising the value of assets traded, subject to the CFMM's reachable reserve set. hence, path deficiency guarantees that the optimal strategy for an arbitrageur is to solve the optimisation problem described and execute the resulting trade.
CONCLUSION
This is essentially a soft intro to AMM math with as little math as possible to prevent confusion. A lot of concepts are generalised, often leading to misrepresentations, i'm sorry for those. In the following articles I'll try my best to be as precise as possible with definitions as we treat these concepts one after another. Thank you very much for your time!
PS: shout-out to Polymer/Centurion for helping me all through the production of this article. Subscribe to his page too, he's a much better writer!
also tyvm to @staringispolite and @functi0nzer0 for their assistances with definitions.
https://arxiv.org/abs/2012.08040
https://arxiv.org/abs/2107.12484
check out 1 and 4 too
https://docs.mstable.org/
v1: https://hackmd.io/C-DvwDSfSxuh-Gd4WKE_ig
v2: https://uniswap.org/whitepaper.pdf
https://theodiamandis.com/pdfs/slides/cfmm-geometry-talk.pdf
https://arxiv.org/pdf/2003.10001
https://arxiv.org/abs/2105.13510
https://arxiv.org/abs/2105.02784
Brilliant