DeFi Automated Market Makers

Automated Market Makers (AMM) are decentralised exchanges that allow users to exchange assets according to pricing schemes that are derived from publicly stated sources, such as mathematical formulae and the exchange’s internal token liquidity pools.

The exchanges occur between trader and AMM, no 3rd party is involved or required, removing the need to find someone willing to partake in your swap.

AMMs depend on multiple factors:

• Liquidities in individual tokens and across the exchange as a whole

• Pricings between pairs of tokens

• Fees charged by the exchange to reimburse Liquidity Providers (LP) and any other relevant parties

Each exchange handles the calculation and management of these factors differently, resulting in different pros and cons, as well as financial opportunities.

• Liquidity invariants and price slippage

• Price oracles

• Impermanent loss

• Liquidity availability

Haroku has explored the underlying mathematical models of several major AMMs, as outlined in their white/yellow papers, technical documents and code bases. Together these AMMs have TVL in excess of $20 Billion, not including other platforms using the same underlying processes.

Invariant Based AMMs

UniSwap V2 & V3, Curve StableSwap V1 & V2 and Balance are using a similar mechanism to dynamically determine price changes due to varying supply and demand – an Invariant Function linking the liquidity of two tokens so that the liquidity change (or equivalently, price) in the “out token” are determined by countering the liquidity change in the “in token”.

Figure 1 shows the invariant curves for several different types of AMMs. As an exchange’s invariant more closely matches the linear “zero slippage” line it replicates its behaviour – reduced slippage near the liquidity balance point. However, unlike a zero-slippage fixed price model, which could run out of liquidity, the deviation from linear represents price slippage, modifying prices dynamically to make in-demand tokens more expensive and less-desired tokens cheaper (relatively).

Price slippage therefore represents an essential feature to adapt to new market conditions, but excessive slippage undermines the reliability of an exchange for large scale utilisation.

Figure 1 : Example Invariant Curves for Zero Slippage (Blue), UniSwap (Purple),low leverage CryptoSwap (Green), high leverage CryptoSwap (Red)

The mathematical structures of Balancer, StableSwap and CrytoPool can all be viewed as evolutions of UniSwap:

In each case a shortcoming of UniSwap, or an earlier approach, is addressed:

• Balancer Weights, as well as liquidity, impact pricing

• StableSwap Leverage for stable-swaps (1:1 valuations)

• CryptoPool Refinable leverage for swaps between any tokens, regardless of relative price

UniSwap’s simple approach does not allow for more elaborate swap configurations but the fact a UniSwap pool can be modelled entirely using algebra and formulae means numerical methods to fit swap amounts to an invariant curve are not required, resulting in lower gas fees. Balancer is sufficiently similar to UniSwap to also be mathematically tractable but lacks leverage functionality.

The more elaborate pools generate higher gas fees but can be configured to run with very low price slippage, even when the true liquidity is low, through their leverage parameters. UniSwap V3 introduced concentrated liquidity as a way to simultaneously give liquidity providers more control over their liquidity strategies and to reduce price slippages in specific price intervals, effectively acting like restricted leverage.

Unilateral Based AMMs

Bancor does not explicitly use an invariant based model, but the net result of its swap mechanism is to produce swaps equivalent to UniSwap and Balancer under the right change of notation.

Bancor mints and burns its own token when another token is deposited or withdrawn. Unlike a standard swap between two tokens, where the pool’s liquidity of one token goes up and in the other token down, Bancor increases its smart token supply when its reserves of a token increase via a deposit.

Since the pool’s price for each token in its reserves depend on the overall supply of the smart token depositing or withdrawing one token type alters all the prices of the other tokens within Bancor. It is only because for swaps that result in zero net change in the Bancor smart token the results are equivalent to UniSwap or Balancer behaviour.

Platypus departs completely from the Invariant-based approach, defining an entire unilateral formalism using a “slippage function” with specific, though quite general, properties. Through this unilateral approach Platypus avoids “liquidity fragmentation” by not having a pre-defined invariant or a set combination of token pools.

Prices are based on price oracles, adjusted using slippages calculated between two tokens at the instant of the swap, based on their actively held reserves (“assets”) and deposited liquidity (“liabilities”), which together define the token’s “health”. The price slippage, calculated from the slippage function, is designed to not only penalise swaps that reduce the overall health of the involved tokens but to reward swaps that improve their overall health. Due to this approach, it is necessary to explicitly add penalties for deposits and withdrawals in order to prevent arbitrage routes. As detailed below, the arbitrage protection in Platypus does not generally protect from arbitrage, it is only due to a fortunate coincidence of a high enough “haircut fee” that Platypus cannot be arbitraged at time of writing.

Main Design Aspects

• UniSwap V2

o Invariant-based, with simple formulae giving clear behaviour and lower gas fees

o Prices defined by liquidity with no “control parameters” for high levels of slippage

o High slippage opens possibilities for significant impermanent loss.

o Generates a time accumulator price oracle

• UniSwap V3

o Invariant-based, using the same invariant as UniSwap V2

o Allows concentrated liquidity for elaborate liquidity provider strategies

o Generates a log-space accumulator price oracle

• Balancer

o Invariant-based, generalising UniSwap model by adding in weights for each token

o Weights allow price setting for arbitrary liquidity

o More complicated, but solvable, formulae avoiding numerical methods and their high gas fees

• Curve V1: StableSwap

o Invariant- based, generalising UniSwap model by introducing leverage parameter to control slippage

o Complicated formulae requiring numerical methods and higher gas feesthan UniSwap

• Curve V2: CryptoPool

o Invariant-based, generalising StableSwap’s leverage with extra calibration parameters

o Pricing oracle inputs allow leverage to be focused at any price, not just 1:1 Stablecoins

o More complicated formulae requiring numerical methods, further increasing gas fees

• Bancor

o Semi-unilateral based exchange, using its own smart token as part of exchanges

o Uses constant reserve ratios between smart token and reserves, instead of token weights

o Produces very similar behaviour to Balancer, and thus UniSwap, by associated weights with constant reserve ratios and smart token supply with invariant curve

o Impermanent Loss protection implemented through fees and liquidity locking, not novel slippage models

• Platypus

o Truly unilateral exchange model, preventing liquidity fragmentation by dynamically linking token pools as and when swaps are performed.

o No direct leverage parameter akin to Invariant-based methods

o Entirely different mathematical approach to all other explored exchange models, with the potential to be generalised or modified in many ways

o Requires manifest arbitrage protection due to unique mathematical approach – currently incorrectly implemented

Further details on each of these exchanges are given in the main Haruko article DeFi Automated Market Makers, including mathematical derivations, numerical examples and explorations of the code base.

Major Findings

During the exploration of the mathematical underpinnings of the above exchanges, as well as implementation of exchange simulators, two major aspects were identified, the first in StableSwap and the second in Platypus.

Inaccurate Leverage in StableSwap

The Curve 3pool exchange displays prices and slippage inconsistent with its stated liquidity and leverage settings. On further investigation it was confirmed that 3pool is running with a leverage approximately 11% of what it should, specifically 1

9 leverage. This stems from two errors in the pool’s Vyper code.

Within the main pool file, a comment states the leverage parameter input to the system is not A, the parameter stated in the 3pool front page, but should be “A*N*(N-1)” (N is the number of tokens, 3 in this case), which is the code-based implementation of the expression AN(N − 1). The code then treats the value as if it were AN N−1 , multiplying it by N to give a quantity used throughout StableSwap, AN N (or ‘ANN’ as named in the code).

The first error is that the comment should read A*N**(N-1), not A*N*(N-1). As a result, the N-1 would be assumed to be a multiplicative factor, not an exponent. Secondly, the parameter being fed into the 3pool Vyper code is neither AN(N − 1) nor AN N−1 , but just A. Due to this, all places where AN N appears in 3pool only have a numerical value equal to AN. Since N is fixed (at 3) this is equivalent to under-leveraging the pool by a factor of N N−1 = 3 2 = 9.

This does not impact the security of 3pool but it does mean it runs with higher than expected slippage, resulting in higher fees and thus lower returns for any system built upon it. Unfortunately, the open- source nature of the platform means this issue appears in other exchanges that use the same code – several StableSwap based pools in the Curve Git repository show exactly the same A*N*(N-1) in the variable definition comment and treat the input as if it were AN N−1 , when the pool’s creator assumed the input was just A.

This illustrates the vital importance of code auditing and building robust tests, even duplicate but independent implementations. It should be noted Curve has been audited 3 times and given high evaluations each time.

Critical Arbitrage Vulnerability in Platypus

Platypus’s development team recognised Platypus’s slippage model leaves open the potential for arbitrage and explicitly include deposit and withdrawal penalties to try and prevent this.

Unfortunately, Platypus can be arbitraged even with this arbitrage “protection”.

The mathematical derivation of the deposit and withdrawal penalties makes several approximations, neglecting the effect of early price slippage on later swap volumes, cancels out terms that are not equal and, without mathematical justification, restricts the liquidity ranges the penalties apply to.

The net result is that the “zero haircut fee” implementation of Platypus can be arbitraged by arranging a sequence of swaps, deposits and withdrawals that incur zero penalties and generate net gain via reverse slippage.

Fortunately for Platypus the level of arbitrage possible diminishes as the fees increase. The StableSwap version of Platypus has a fee of 0.01% and this is sufficient to prevent arbitrage. However, if the fees were ever lower below 0.0067%, a reduction of one-third, arbitrage would be possible, with a maximum gain equal to all excess assets (assets left over once liabilities are deducted). Until the platform is migrated to a new smart contract with redesigned arbitrage protection there is always the possibility a governance change could lower fees and unwittingly open the liquidity to arbitrage.

A deep dive into the Platypus platform is performed in the Haruko article “Arbitrage Attacked in Platypus”, where the arbitrage attack is identified and explored, along with ways for Platypus to remove the critical vulnerability.

If you would like to download the paper, you can do so here.

Request your Haruko demo today

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.