AMMs deep-dive

https://defining.substack.com/p/deep-dive-1-amms?utm_source=twitter&s=r

Emiri, Apr 2022

This deep-dive is a handbook that will cover all the different types of AMMs that currently exist in the DeFi ecosystem.

2021 was the year of the L1 trade. From SOLUNAVAX at the beginning of the year to FOAN towards the end of the year (shoutout white wolf), every L1 caught a bid. Something even a blind person could see is that whenever a new L1 caught a bid, there would be a massive rotation of capital into that ecosystem. Everytime that happened, the native DEX always performed the best.

DEXs are a cornerstone piece of any DeFi ecosystem. Majority of the liquidity within a DeFi ecosystem will flow through its native DEX. As you may know, DEXs use something called an Automated Market Maker (AMM) to facilitate smooth on-chain trading. The innovation in the AMM space over the last 3 years has been rampant. Everyone is trying to make the next AMM that is faster, more capital efficient, more gas-optimized, and better for Liquidity Providers (LPs). I was doing some research and wanted an organized list of all the different types of AMMs out there, but the information was very fragmented. So I said fuck it, and decided to make my own handbook that dives into all the different types of AMMs that are currently out there. I will only be covering the AMMs that are truly unique from one another, I will not be covering forks because I’ll probably have kids by the time I finish writing. Why AMMs?

If you have only interacted with CEXs or are from TradFi then the concept of an AMM might be new to you. All centralized exchanges use something called a Centralized Limit Order Book or CLOB for short. A CLOB simply matches bids and asks according to price and time priority. Users can make 2 types of orders here, a limit order & a market order. This works well for centralized exchanges, so why do we need AMMs for DEXs?

The first problem is gas fees. Most of us have probably lost mini-fortunes in gas fees. Using a CLOB on-chain would probably cost the equivalent of a small countries GDP in gas fees. Constantly adjusting orders and placing orders would simply not be possible because you will get charged gas fees on every single transaction.

Another problem is frontrunning. The transparent nature of the blockchain becomes a problem for CLOBs. It is not a problem for market orders since AMMs only allow market orders, the problem is for limit orders. Suppose a large trader has a limit order set for a specific market, their orders will be streamed to every market participant and will most certainly be frontrun. It becomes extremely difficult to execute trades the way you want. In centralized exchanges, these orders are mostly obfuscated for the end market participant which makes frontrunning difficult.

In comes AMMs.

What are AMMs?

If you already know how AMMs work, then skip this section

To facilitate gas-efficient trading on-chain, AMMs use something called liquidity pools. A liquidity pool is basically a smart contract that holds the tokens of a trading pair in a certain ratio. To get liquidity into these pools you have users called liquidity providers or LPs. Suppose the trading pair is ETH/USDC. LPs are incentivized to provide equal amounts of liquidity to this pool (usually 50/50) and in return they get an LP token. This LP token represents their position in the liquidity pool and it entitles them to receive a portion of the trading fees generated from the pool. When LPs want to take their liquidity out, they simply burn the LP token. Every time a swap is facilitated by a liquidity pool, there will be a price adjustment which is determined by a deterministic pricing algorithm. This is the Automated Market Maker. Now traders can directly buy and sell from these different liquidity pools through market orders making an on-chain trading experience feasible.

As time has gone on, different issues were encountered with AMMs which drove devs to make their own versions of this model. This deep-dive will look at all the different variations that exist.

This will be the order of this guide, so you can skip go to the AMMs you want to read about

1. Uniswap

2. Curve Finance

3. Balancer

4. Bancor

5. Crocswap

6. Muffin

7. Pendle

8. Primitive

9. Cowswap

10. Osmosis

11. Dopex

12. YieldSpace

13. Sudoswap


1) Uniswap

Uniswap has been live since November 2018. Since it’s been live, it has gone through 3 stages of evolution. From V1 to V3, the team has always tried to bring innovative solutions to make the user experience better. Uniswap V1:

The first version of Uniswap established the general structure of how it will work. They have basic liquidity pools where each pool is its own smart contract. Only two tokens can be swapped in these pools, and when LPs provide liquidity they have to do so in a 50/50 ratio. So if the pair is ETH/DAI, they have to provide both tokens in equal proportions. For doing so, the LPs on Uniswap receive rewards, there is a standard 0.30% trading fee collected by Uniswap across all pools which are proportionally redistributed to LPs. The AMM model used by Uniswap is called the “Constant Product Market Maker”. This follows the infamous x*y=K formula. This formula basically means that the product of the quantities of the two tokens in a pool must always remain constant. At the time of release, Uniswap was one of a kind. But they had one major issue with V1. It only supported ERC-20/ETH pairs. Uniswap V2:

On May 2020, Uniswap introduced V2. The main feature was the introduction of pools that supported ERC-20/ERC-20 pairs. This opened up plenty of more opportunities for traders. They no longer had to trade with everything paired to ETH, they could trade directly with their stablecoins for example. Another benefit is that LPs didn’t have to use their ETH to provide liquidity which would expose them to impermanent loss. This change sent Uniswaps growth parabolic, especially since it was at the time of DeFi summer. This was so successful that it made Uniswap the most forked protocol for a couple of months.

While ERC-20/ERC-20 swaps was one of the main features, there were other notable features. The first one was on-chain price feeds through the use of price oracles. Price oracles constantly feed the smart contract information about the price of a certain asset. The oracles were made to be resistant to price manipulation and fulfilled the purpose of improving the user experience. The other feature was flash swaps, it allows a user to receive the output tokens from the contract before giving the input tokens. While it may seem counter-intuitive to give tokens before they’ve been paid for, Ethereum transaction are atomic so if the user does not pay the input token amount by the end of the transaction, the transaction will get rolled back. Flash swaps are good for capital free arbitrage or instant leverage.

While the Uniswap team could’ve been satisfied with their success so far, they wanted to take it a step further to improve the user experience.

Uniswap V3:

V3 came a year after V2 with the main focus being on capital-efficiency. This is done through concentrated liquidity & multiple fee tiers. Previously, when LPs would provide liquidity to a pool it would be in the 0 to infinity price range. Their liquidity would be distributed evenly across the price curve. This is not efficient because all the liquidity does not get used. Take the example of a USDC/DAI pair. This pair would mostly trade within the $0.99 to $1.1 price range. With liquidity being distributed evenly across the curve, majority of it is not being used. The same can applied for any other token pairs.

Hence, they introduced concentrated liquidity. With this LPs can pick a range within which they would like to provide liquidity and can keep adjusting their position based on market conditions. For our above example most LPs would keep their range as $0.99 to $1.1. But for an ETH/DAI pair for example, some LPs may choose a $2k to $3k range while others may choose a $2.8k to $3.2k. The tighter the range made by the LP and the longer price trades within their range, the more fees they accumulate as rewards. So LPs are incentivized to actively manage their positions to keep the Uniswap AMM very capital-efficient.

2) Curve Finance

Curve is a DeFi powerhouse, it’s such an integral part of DeFi that a literal war has been fought over it. Let’s look at why.

We all know the tremendous success stablecoins have seen, this led to the creation of hundreds of different stablecoins (shameless self-promo, if you want to learn more about stablecoins check this). With so many stablecoins arises the demand for a place to easily swap between them. Curve facilitates this with low slippage, and low fee stableswaps. The magic of Curve is in the structural design of it’s exchange. They created multiple types of pools which is used to create interesting incentive games when combined with governance.

The Plain pools are like any other liquidity pool, they facilitate swaps between ERC-20 tokens. Some pools have more than 2 tokens in them, the most popular being the tripool (DAI/USDC/USDT). In the lending pools, the underlying tokens are lent out to different protocols such as Compound or Yearn and a wrapped version of the token can be traded in the lending pools. Suppose the token is DAI, if it’s cDAI then it’s on compound but if it’s yDAI then it’s on Yearn. This way you can earn lending interest as well as trading fees. The metapool is a way for LPs of the plain pools mentioned above to earn additional trading fees by depositing LP tokens into the metapool. In the metapool, stablecoins are paired against base pool LP tokens. Suppose you are a LP for the tripool. You receive the LP token 3CRV. You can now deposit this 3CRV token into the GUSD metapool. People can trade this, but LPs get the new LP token gusd3CRV which can be put in gauges to earn additional rewards. Factory pools were made in collaboration with Yearn, it is basically a permissionless way for anyone to create their own metapool. This can be an individual or a protocol but it is most often a protocol.

The Gauges responsible for giving LPs their CRV rewards. The gauges monitor the activity and usage by LPs and automatically assign a portion of the CRV inflation to be directed to LPs. Through this they can lock their CRV for the infamous veCRV to get more governance control.

Curve has now launched a V2 of their protocol. V2 involves the launch of crypto pools. A new way to trade non-pegged assets with low risk. The whitepaper is extremely complex but I’ll try and simplify it. They basically use concentrated liquidity just like Uni V3, but for this AMM rather than concentrating liquidity around price = 1 like they do for stableswaps, it is concentrated around current price. The additional feature is their internal oracle which is used to automatically adjust the range where liquidity is provided rather than having users do it manually like they do on Uni V3.

3) Balancer

The team at Balancer saw the constant product market making formula of having two assets in a pool at a fixed ratio as problem. There was no customizability and lack of options. Hence, Balancer created smart pools. The Balancer smart pools use the constant mean formula. This allows the creation of liquidity pools with upto 8 tokens with no fixed ratios and varying weights allocated to each tokens. This opens up options for both traders and liquidity providers because there is more customizability. This customizability also means that there is third player in the Balancer AMM, not only traders and LPs. They are the controllers. They are responsible for managing the pool. This typically involves just rebalancing the weights depending on market demand and volatility. An added benefit is that it very easy to create your own pool. Anybody can do it. Just go to “pool management” tab and plug in your wallet, provide the liquidity and you’re good to go. This is good for individuals if there is no pool up to their liking or if they see an opportunity to create pool that will be demanded by others. Projects can also use this feature to attract liquidity.

4) Bancor

Bancor is an OG DeFi protocol, they created the first ever AMM. Their AMM is called omnipool. Unlike other AMMs where you can create a pool with any token, Bancor’s omnipools require all tokens to be paired against their native token BNT. The problem with traditional AMMs is fragmented liquidity, some pairs will have deeper liquidity than other pools which makes the trading experience worse. This is because there is no common denominator. For example, a random token (Token ABC for example) will have deeper liquidity when paired against ETH, and weaker liquidity when it’s paired against USDT or USDC. To combat this liquidity issue, Bancor decided to have a common denominator in the form of BNT. Now users have a central liquidity pool to trade from which gives every token equally good liquidity thereby making the overall trading experience much smoother.

However, Bancor saw 2 key problems with its AMM design, involuntary token exposure and impermanent loss. Hence, they created Bancor v2.1

Bancor v2.1 allows single sided exposure and provides impermanent loss insurance. For single sided exposure, Bancor allows LPs to provide only one token rather than forcing them to provide both. The LPs will have 100% exposure only to the token which they have provided to the pool and will accrue fees and rewards based on that. Impermanent loss insurance works like this, if a user deposits $100k of a token into a pool, Bancor matches it with a $100k deposit of BNT. Now both the user and the protocol are accruing fees and rewards. Once the user withdraws liquidity both the user and Bancors LP token gets burned at the same time. The protocol checks to see if the user has suffered any impermanent loss and accordingly distributes the accumulated fees from their LP position to the user.

5) Crocswap

Crocswap is some big brain stuff, it took me a lot of time to wrap my head around this one but I finally got it.

It’s an Ethereum-based AMM where the entire DEX is run on one single smart contract. Typically, DEXs are run by having a separate smart contract for each liquidity pool, but by running the entire DEX on one contract you will see major gas & tax savings since tokens aren’t always being reshuffled between contracts. Within this smart contract, there are multiple lightweight data structures which represent individual liquidity pools. This opens up the doors to smoothly conduct many different multi-pool operations.

Crocswap also makes significant improvements for LPs. They have a dual-liquidity model. Classical liquidity (or ambient liquidity) of Uniswap v2 and concentrated liquidity of Uniswap v3 both co-exist in Crocswap. Combined with this, LPs provide liquidity through range orders. Basically, there is a pre-determined price grid where LPs can place orders. As price hits the different ticks, liquidity is added or removed depending on the nature of the order at that tick. This LP model has two key benefits, the first is that it makes the ambient liquidity LP tokens fungible, and the second is that the LPs position automatically compounds rewards rather than having to manually collect rewards. All in all, Crocswap combines the best features of multiple different AMM variations, and puts it into a sleek, cheap, & efficient one contract exchange design.

6) Muffin

Muffin (formerly Deliswap) focuses on two key features for their AMM. Concentrated liquidity & multiple fee tier pools.

We already know what concentrated liquidity is, it’s the same mechanism used by UniV3 and Curve V2. An issue that other AMMs have is fee-tiers. Some AMMs like Uniswap have a fixed fee tier at 0.30% while other AMMs offer 1 or 2 fee-tiers per pool. If you want more fee-tiers then you have to make a new pool of the same token which fragments liquidity. Muffin wants to offer LPs more granular control over where they provide liquidity to generate the most fees rather than having liquidity distributed evenly across all fee-tiers. Hence, they created the “multiple fee-tiers per pool” model. Within one pool, there can be up to 6 fee-tiers. Each fee-tier will act like its own inner-pool which will have its own liquidity and price. Depending on the state of the market, LPs can choose what price range and fee-tier they would like to provide liquidity in. This creation of more choice makes the system more capital-efficient and generates more rewards for LPs.

7) Pendle

Pendle unlocks the full potential of yield-bearing assets with its AMM. It allows for the creation of limitless yield-trading strategies. It is currently available on Ethereum and Avalanche and is built on top off first degree protocols such as Aave, Compound, Redacted cartel, Benqi, and Trader Joe. Users can bring their yield-bearing assets and deposit them into pendle. They get two tokens in return, an OT and a YT. OT or ownership token represents ownership of the underlying asset while YT or yield token represents the entitlement to the yield of that asset. Users can trade the OTs on exchanges like Sushiswap or Trader Joe, and they can trade YTs on Pendle’s AMM. YTs have a time-decay, this is because people buying YTs are buying rights to the yield and currently there isn’t a way to force buyers to make consistent payments on-chain to keep the rights to the yield. As the YT gets closer to expiry, its value decreases. Once expired, the OTs can be used to redeem the underlying assets. Let’s look at the Pendle AMM where the YTs are traded. This is basically similar to a tradfi options market but for yield, so the AMM made to facilitate such activities on-chain is very complex. I will do my best to simplify it here, but if you want the technical explanation with all the math, graphs, and formulas then check this.

The ultimate aim of the AMM is to minimize time-dependent impermanent loss that arises from using tokens with a time-decay. To do this, they use a formula similar to Uniswaps x*y=k but they just add an additional account for weight and time. So the pool starts off with a curve similar to uniswaps, but as time passes the curve shifts in such a way to ensure that the price of the YT keeps falling as time passes. The curve shifting is governed by a time-decay pricing model which is similar to the options pricing model in tradfi.

8) Primitive

Primitive is a spot & derivative token exchange with the key innovations coming from the derivative token side. For the spot exchange, they use the concentrated liquidity method. When it comes to derivatives, they use a variation on AMMs called Replicating Market Maker (RMM). RMM is a way to make the on-chain derivative trading experience more user-friendly and more efficient. The Primitive team saw two problems, current on-chain derivatives depend solely on oracles. Oracles present security risks and can be a central point of failure. The other issue is that LPs get a LP token to represent their share in the pool which is essentially a derivative, while there are trading markets for these LP tokens, none of these derivative are inherently financially useful. Using the RMM, you can create or offer any type of derivative payoff products. I’ll go over some examples outlined by the team to give you some clarity. In lending markets like Fuse these LP tokens can be shorted which expands the derivative payoff range for call & put options, for liquidity strategy protocol like Ribbon and Charm you can create a basket of LP tokens to create any type of novel DeFi product, lastly you can also create binary options by being able to sell the rights to one side of the LP token. 9) Cowswap

Cowswap is built on top off the CoW protocol. To understand Cowswap lets understand CoW protocol first.

There are 2 key features that make the CoW protocol unique, batch auctions & Coincidence of Wants (Hence the name CoW). Batch auctions are when orders are placed off-chain after which they are aggregated into batches to eventually be settled on-chain. The benefit of batch auctions is that it simplifies the Coincidence of Wants (CoWs). CoWs are when two parties hold an item that the other wants, they can exchange them directly without the need for any type of intermediary. Similarly, when two traders hold an asset that the other wants they can exchange them easily through batch auctions. This means that CoW protocol doesn’t need direct access to on-chain liquidity which gives them significant MEV protection.

Built on top of this is the DEX Cowswap. It acts as a meta DEX aggregator or a DEX aggregator of DEX aggregators because it gives users the best price and cheapest execution across all AMMs and aggregators on Ethereum. To do this it doesn’t use any existing AMM or constant function market maker model, it replaces these mechanisms with a new party called “solvers”. The solvers are incentivized to submit the most optimal settlement solution for a designated batch. The solvers are incentivized to compete against each other to find the most optimized solution. The winning solver is then appropriately rewarded with tokens. Anyone can become a solver after fulfilling some of the minor prerequisites.

10) Osmosis

Osmosis is an AMM native to the Cosmos ecosystem. For those of you who aren’t familiar with Cosmos, they follow a hub and zone architecture where each zone is an application specific blockchain. Osmosis is one of these Zones which lives in an interoperable Cosmos ecosystem. So It’s an L1 AMM with IBC built-in which means it is interoperable with every other zone in the Cosmos ecosystem. The main feature of Osmosis is customizability.

Other AMMs have most things hard-coded. They either have a “constant product” or “constant sum” or “constant mean” or any other type of formula, the bonding curves are pre-determined, the fee structures and tiers are also pre-determined. Osmosis essentially gives users the tools to create their own AMM pool with maximum customizability. People can set their own parameters for bonding curves, have two token pools or multi-weighted asset pools, they can use any of the already established AMM formulas or make their own one. For LPing the rewards are decided through governance, when coupled with customizability this creates different strategic incentive games.

With this customizability for liquidity pools, there needs to be some form of governance for decision making. So in Osmosis, the LP tokens received don’t only accrue rewards but they also represent the share of decision-making power a LP has for that specific pool. The longer a LP is locked into a pool the more rewards and governance power they get.

Essentially, with this customizability, Osmosis creates an “AMM as a serviced infrastructure” model. With the complexity of new types of assets in DeFi, you need options in terms of finding the optimal AMM for each type of asset while not requiring people to take on the massive task of building their own AMM.

11) Dopex

Dopex is a very ambitious protocol. Their aim is to create a crypto options protocol that runs entirely on-chain.

At the heart of Dopex is their Single Staking Options Vault (SSOVs). These SSOVs allow users to deposit their assets in the contract, the protocol then sells these assets as call options to buyers while the depositor earns rewards for locking up their assets. Other than SSOVs Dopex also has multiple other types of pools to allow users to trade options. They have pools including Options pools and volume pools. Underlying this architecture is the Dopex AMM.

Before we get into the AMM, you need to know what a volatility smile is. A volatility smile is a result of plotting the strike price and implied volatility of a group of options onto a graph. When implied volatility is plotted at each strike price, the graph forms a smiley face. With that established let’s get into the AMM.

The Dopex AMM uses a black-scholes pricing model. This pricing formula gives traders a theoretical price of an option by using option volatility as an input. Using option volatility helps understand how the price of an asset will move in the future. So Dopex uses chainlink adapters to get information on implied volatility and asset prices, this information is used with the black-scholes pricing formula to determine the volatility smile. This gives users accurate option prices on-chain while taking into account real market risk and behavior.

12) YieldSpace

The Yield Protocol created the concept of fyTokens. These fyTokens are synthetic tokens that have a certain maturity date. Once this maturity date is reached, the fyToken holder can redeem the original asset or target asset at its original price. Before maturity the price will be free-floating. Suppose the target asset is DAI, then the fyToken will be fyDAI which will be free-floating until maturity when it can be redeemed for 1 DAI. For those familiar with tradfi, it is similar to a zero-coupon bond. It is a debt security instrument where traders can buy the bond at a significant discount and then redeem it for its face-value or par value at maturity. The difference between purchase price and par value is the profit. While existing AMM formulas can be used to trade tokens with price maturity, they are by no means optimal. Using Uniswaps constant product formula would lead to higher price-impact and fees for traders when close to maturity making it capital-inefficient. Using the constant sum formula doesn’t allow for price-discovery at all which will discourage trading. Hence, the YieldSpace AMM uses something called the “constant power sum formula”.

X^1-t + Y^1-t = k

X represent the reserves of the target token, Y represents the reserves of the fyToken, and t represents the time to maturity. This formula is basically a combination of the constant product and constant sum formula making it optimal for trading tokens with maturity dates. When t=1 the formula acts like a constant product formula and when t=0 it acts like a constant sum formula.

This is done to ensure that the marginal interest rate of the fyToken that is offered by the pool is equal to the ratio of the fyToken and original token reserves in the pool. Suppose the reserves in the pool are 110 fyDAI and 100 DAI the marginal interest rate offered will be 10%. So the allocation of fyToken to the pool changes according to the current interest rate offered by the fyToken. If interest rate rises then fyToken allocation rises and if interest rate falls then fyToken allocation falls.

13) Sudoswap

I saved Sudoswap for last because this is the most unique AMM. It’s an AMM for NFTs. Rather than using off-chain orderbooks, Sudo uses on-chain liquidity pools to allow low slippage swaps for NFTs. There are 3 main types of pools that users will interact with. There is a buy-only pool, a sell-only pool, and a both pool. Each pool is a separate contract managed by a single address. A buy-only pool will always have ETH and will be ready to give a quote to buy the NFT, a sell-only pool will always contain NFT and will always be ready to give a quote to sell the NFT for ETH, and in both pool, you have both a whole number NFTs and ETH, users can the either buy from that pool which increase the amount of ETH in the pool, or sell which decreases the amount of ETH in the pool. This means that each NFT will have multiple pools for it.

From the LP side, they can better control of price ranges because the quotes that each pool gives is determined by a bonding curve. The bonding curve that each pool uses is determined and stated when the pool is created. There are three types of bonding curves currently used. A constant bonding curve means that the pool is always quoting the same price, a linear bonding curve means that the price quoted by the pool increases/decrease linearly with buys/sells, and the exponential curve works by increasing/decreasing price by a certain percentage depending on the buys/sells.

The main benefits of the Sudo AMM is that the market becomes more liquid, users get an instant quote on their NFTs rather than waiting for a bid and then settling by simply accepting the best offer on Opensea. It is also a good decentralized alternative. Platforms like Opensea are basically web2 platforms, they have all the control. We have seen them randomly blacklist accounts and prevent the selling of certain NFTs as they please. A problem with Sudoswap is that it is not as gas efficient as the current marketplaces. Even though the team has done all that they can to minimize gas expenditure, it will take a lot of work to reach to the point of being competitive with other NFT marketplaces from that aspect.

Personal Thoughts

Now that all the different types of AMMs are in one place, what I’ve noticed is that most of the innovation after Uniswap comes from improving the experience from the LP side. Liquidity is everything in DeFi, without it a product is pretty much rendered useless. Hence, making the experience easier and more profitable for LPs has a direct effect on the success of a protocol. It also helps improve capital efficiency which is a major o[point of focus for all new AMMs.

From the traders perspective, the mechanisms are pretty much figured out. Most DeFi users are very familiar with the swap experience. The main thing is for the UI to keep improving. It should be as easy as possible for traders to navigate and execute on these platforms. Something that should be added to improve the trading experience on DEXs is limit orders. As I outlined earlier, it is tough to do because of frontrunning but if a team can figure out a way to do it or a variation of it, they will be very successful.

Most of the AMMs mentioned here haven’t been launched as yet which is why AMMs like Uniswap still remain dominant, but when they launch it will be interesting to see whether the improvements for the user will be significant enough to take them away from an experience they are already familiar with.

That is all for this Deep-dive into AMMs.

If you enjoyed reading and are feeling generous then please consider donating to 0x43A5D9C141125Cd67B9268ef28C7c6a9dC15F3c9

Subscribe to the substack and follow the medium

Follow me on twitter.

Last updated