DW #13 | Reinventing Finance: A Blueprint for Building the Ultimate DEX
Everything you need to know to build one: AMMs, Bribes, Impermanent Loss, Hooks, LPs and more
TOC
Introduction
AMMs in Depth
AMM Models
CPMM
CSMM
CMMM
Hybrid CFMM
Hybrid Order Book AMM
PMM
vAMM
TWAMM
CLMM
AMM Challenges
Liquidity
Impermanent Loss
Low Capital Efficiency
Transaction Speed
Slippage
Front Running
The DEX Trilemma
Building to Scale
Underlying Blockchain
Solving Impermanent Loss
Universal Liquidity
DEX Features
Price Oracles
Fees
Bribes
Rebates
Trading Incentives
Revenue Redistribution
Hooks
Protocol Owned Liquidity (POL)
Best Practices
1Inch Fusion
Velodrome vs. Solidly
GMX
Uniswap Pentalogy
Uniswap V1
Uniswap V2
Uniswap V3
UniswapX
Uniswap V4
Conclusion
References
1. Introduction
Going towards a greater adoption of DeFi, Decentralized exchanges (DEXs) are and will be at the forefront of revolutionizing the way digital assets are traded - without the need for intermediaries.
This research article delves into the technical details of decentralized exchanges, exploring their underlying mechanisms and frameworks. I examine their unique features, such as liquidity pools, order books, and automated market-making algorithms.
In this context, I also address challenges faced by DEXs, including scalability, front-running attacks, and impermanent loss. By understanding the technical foundations of DEXs and their potential for transformative impact, this article seeks to contribute to the ongoing evolution and adoption of decentralized exchanges with the ultimate goal of revolutionizing the finance industry.
2. AMMs in Depth
Automated market makers (AMMs) are a type of DEXs that use specific algorithms to make it easy for individual traders to buy and sell crypto assets. Instead of trading directly with other people as with a traditional order books, users trade directly through the AMM.
We could consider liquidity pools (LPs) as a core feature of any AMM. It is essentially a crowdsourced collection of crypto assets that the AMM uses to trade with people that are buying or selling. Adequate liquidity is one of the most important aspects in the operation of AMMs as without sufficient liquidity, AMMs can experience significant price fluctuations, resulting in capital inefficiency and impermanent loss.
a. AMM Models
Let’s now delve into the types of existing AMMs, explore their features and examine their benefits and drawbacks.
i. Constant Product Market Maker (CPMM)
Underlying equation behind CPMMs is the function
x * y = k
which similarly as above establishes a range of prices for two tokens according to the available liquidity of each token. When the supply of token X increases, the token supply of Y decreases, and vice-versa. This version become popularized by Bancor.
ii. Constant Sum Market Maker (CSMM)
This version is ideal for zero-price-impact trades but does not provide infinite liquidity. CSMMs follow the basic formula
x + y = k
This design allows participants to drain one of the reserves if the off-chain price between the tokens is not 1:1. Hence why CSMM is rarely used in practice.
iii. Constant Mean Market Maker (CMMM)
This particular model enables the creation of AMMs that can use more than two tokens and introduce weights away from the standard 50/50 distribution. For an LP with three assets, the equation would look like this:
(x * y * z)^(1/3) = k
This allows for variable exposure to different assets in the pool and enables swaps between any of the pool’s assets.
iv. Hybrid CFMMs
This group includes several combinations between different AMM models. For example, Curve AMMs combine CPMM and CSMM using an advanced formula to create denser pockets of liquidity that bring down price impact within a given range.
Hybrid CFMMs enable extremely low price impact trades by using an exchange rate curve that is mostly linear and becomes parabolic only once the liquidity pool is at its limits. Capital efficiency is higher and liquidity providers earn more fees.
v. Hybrid Order Book AMM
This particular AMM combines on-chain trading and risk engine with an off-chain sequencer and it was presented by Vertex Protocol. The on-chain trading and risk engine are controlled by smart contracts. The sequencer acts as a high-performance order book matching inbound orders with low latency.
vi. Proactive Market Maker (PMM)
A proactive market maker (PMM) mimics the human market-making behaviors of a traditional central limit order book. It further uses off-chain price feeds from oracles to increase the liquidity near the market price (DODO is an example of a DEX using this model).
vii. Virtual Automated Market Maker (vAMM)
vAMMs aim to minimize price impact and mitigate impermanent loss. They enable single token exposure through a synthetic asset. The underlying formula remains the CPMM one
x * y = k
but instead of relying on a liquidity pool, users deposit collateral to a smart contract.
Trading synthetic assets instead of the underlying allows users to efficiently access price movements. It is important to note that users with open positions in synthetic assets face the risk of collateral liquidation (Perpetual is an example of a protocol using this model).
viii. Time-Weighted Average Market Maker (TWAMM)
TWAMM was presented by the Paradigm team. It’s main advantage is that it helps traders to efficiently execute large orders. In classic AMMs with smaller pools large orders can be an issue due to slippage or sandwich attacks. Whereas, TWAMM essentially breaks orders into indefinitely many smaller chunks and executes them against embedded CPMM over time.
TWAMM provides an on-chain equivalent to the TWAP order in traditional finance. Uniswap V4 aims to incorporate this model (more on this later).
ix. Concentrated Liquidity Market Makers (CLMM)
A key upgrade CLMMs bring to the market is an increase in the capital efficiency of DEXs. CLMM protocols are particularly popular on Solana. Let’s see what is under the hood.
When LPs provide liquidity on a CLMM, they can select the price range where they would like their tokens allocated (similar to what order book does). This range is then divided into ticks with equally distributed liquidity.
Tokens provided on a CLMM are not spread out across a massive price range leading to an exponentially higher capital efficiency compared to first-generation AMMs. Deploying liquidity in a more efficient manner is an advantage for LPs, traders, and Web3 projects. LPs collect more fees earned with smaller token allocation, traders experience less slippage, and projects can more efficiently use their capital for growth.
b. AMM Challenges
We now know how the most common AMM models work, so let’s see what are the main challenges they need to solve in order to succeed.
i. Liquidity
Probably the major one. DEXs often face challenges in attracting sufficient liquidity and liquidity fragmentation across various DEXs can lead to higher slippage and limited trading options.
ii. Impermanent Loss
Impermanent loss (IL) is the difference in value over time between depositing tokens in an AMM versus simply holding those tokens in a wallet. This loss occurs when the market-wide price of tokens inside an AMM diverges in any direction. There were several solutions trying to solve this but without any solid traction so far.
iii. Low Capital Efficiency
Traditional AMM designs require large amounts of liquidity to achieve the same level of price impact as an order book-based exchange.
iv. Transaction Speed
The transaction throughput of most DEXs is limited by the underlying blockchain's scalability. Block confirmation times and network congestion can result in slower trade execution and higher gas fees.
v. Slippage
Slippage is the difference between the expected price of an order and the price when the order actually executes. It essentially depends on the volatility of the underlying asset as well as the liquidity deployed in pertaining LP.
vi. Front Running
A front-running is an attack where a malicious user observes a swap transaction after it is broadcast but before it is finalized and reorders transactions to benefit themselves.
3. The DEX Trilemma
Two most important success indicators for DEXs are Total Value Locked (TVL) and Volume, but these are not necessarily the best metrics.
TVL a lot of times includes idle capital - it just sits there doing nothing.
Volume on the other hand can be faked by wash trading, showing it far higher than the reality.
What should the main indicator be then? As suggested in the prior literature, Revenue or Fees collected seems to be the most accurate one. It is costly to manipulate it compared to the other two metric and it is essentially the revenue a DEX generates and it is essentially derived from TVL and volume.
4. Building to Scale
Very high-level, there should be three choices you need to make before going into deep into the math of AMMs. Which blockchain will your protocol be built upon. Secondly, are you trying to mitigate the impermanent loss, why not or why and how if yes, and lastly are you building an universal cross-chain compatible solution - meaning are you able to scale beyond your original chain, be it L1 or L2.
By having answers to these three question you should be able to solve or have a clear understanding on the challenges presented in the previous section.
a. Underlying Blockchain
Choosing the right underlying blockchain is important part of a long-term vision of the protocol. Key selection criteria should include transaction fees, throughput, user adoption, TVL and grants among others.
High transaction fees can deter users and slow user adoption particularly during high congestion periods, which usually happen during bull runs when the number of market participants is the highest. During the last bull run a single transaction on Uniswap have costed a few $100s making it unviable for smaller transactions. This was the mainer reason why DEXs built on “cheaper” chains (e.g. Pancakeswap and Sushiswap) got a lot of traction and TVL.
Following the success of GMX, Arbitrum recently became a really popular L2 for DEXs, but there are solid exchanges on practically every network. GMX launched on Arbitrum and Avalanche, Quickswap launched on Polygon, Velodrom on Optimism, Solidly initially on Fantom and so on. It is really up to the team strategy which chain to focus on primarily.
b. Solving Impermanent Loss
Impermanent loss is one of the biggest drawbacks for a non-stable liquidity pools
Liquidity providers can lose significant funds due to the imbalanced pools. There are a projects who are solving or tried to solve this issue in several different ways, some more successful others less. This time I won’t go into all the mathematical details behind the solutions, but let’s see what the market offers us.
i. Customized Pools
By separating the AMM curve logic and math from the core swapping functionality the solution developed by Balancer essentially pegs the token price to its actual weight or value. It also allows for the creation of pools with unequal amounts or allocations, meaning that the pools are no longer limited to two assets only.
This approach is very effective in case of token price fluctuation.
ii. Constant Price Pools
Another solution that takes its core idea from stablecoin LPs, presented with Bancor V2, enables the creation of AMMs with pegged liquidity reserves. The idea is to hold the relative value of tokens constant. This is achieved through oracles that adjust the weights and fees to reset the balance.
iii. Single-Sided Liquidity with Dynamic Weights
Halting unprofitable trades through oracles and dynamic concentrated liquidity is an approach developed by the team behind the GooseFX.
LPs get to benefit from dynamic concentrated liquidity provisioning to reduce the arbitraging that happens on their AMMs (since liquidity will be dynamically concentrated around an oracle-set price).
Additionally, an oracle will charge traders the worst price from the market price (from all the prices in other markets) and the price within the AMM - This acts as a backstop solution.
As with all the solutions, relying on the oracle has a few limitations as well such as front-running and centralization risk, which should be solvable over time.
iv. Delta-Neutral Strategies
From the novel approaches, it is worth pointing out Logarithm Finance. Their solution tackles impermanent loss by actively managed LP positions and creating delta-neutral strategies with short positions on composable decentralized derivative exchanges.
Such is done through the product called Nautilus Vault. It essentially connects the Uniswap V3 pool with the GMX DEX, allowing for balanced liquidity provision. Any IL risk from Uniswap is hence hedged with the short position through on-chain perpetual swaps on GMX. Such method only recently became viable with GMX derivatives being deployed on the same layers as AMMs.
The logic behind the Active management with Active hedging in Nautilus Vault works in two steps,
Step 1: Rebalance if one of these three conditions is met for any state T
:
Is current position out of bounds
Are we saved with current margin
Is leverage < Max value
Where p_lower
and p_upper
denote price range, and MB(p)
denotes margin balance as defined below:
Step 2: For each state T check hedge deviation and rehedge if met:
If you are interested in other strategies within the Nautilus Vault, make sure to check the full Nautilus Vault Documentation.
None of the solutions is optimal nor universal, and it greatly depends on the business model behind the DEX, the idea here is more to present you available solutions rather than advocate for a particular one.
c. Universal Liquidity
Firstly introduced by MUX, liquidity becomes chain agnostic (with certain limitations). Liquidity pools on trading protocols are often fragmented across different chains, resulting in inconsistent liquidity.
Universal liquidity addresses this issue by unifying liquidity across networks using a broker module which monitors the reserved liquidity. When a trader places an order, the broker calculates the available liquidity across all available networks and fills the order if it meets the position size requirement.
5. DEX Features
Let’s now take a look at some of the key features DEXs should consider. It is important to primarily consider the ones that are aligned with your strategy.
a. Price Oracles
You need proper pricing mechanism and you will most likely have to use an oracle for this purpose. Oracle essentially link blockchain with an off-chain database. The most popular options currently are Chainlink, Pyth and Stork.
b. Fees
To generate revenue, DEXs need to charge fees. Depending on the model you can apply fees to practically anything, swapping, LP minting, LP burning, liquidations, funding (perpetuals), market makers/market takers, withdrawals or deposits. Standard fees usually range from 0-1%.
Tip: Apply higher fees to the actions you want to minimize in the ecosystem and vice versa (e.g. higher fee for withdrawals, no fee for deposits)
c. Bribes
Bribes are another option for attracting liquidity and could be quite important to set a balanced DEX. There are two common types, voter bribes and gauge bribes.
The first one targets the pools with voter bribes attached and payouts usually come from the emission pool, while the latter is provided by the underlying LP project with the aim to incentivize liquidity and pay rewards in their native token (e.g. Curve, Solidly).
d. Rebates
Rebates are another alternative for increasing liquidity. It works as a reimbursement to market makers for the provided liquidity on the exchanges. While they are common across centralized exchanges such as Binance the are not uncommon among DEXs neither (dYdX for example offers 0.5bps rebate).
e. Trading Incentives
Trading incentives are particularly important in the early stage of the project. Why? Because they bring users, increase traction and help to initiate revenue generation.
Depending on the strategy, needed liquidity and risk profile of the LPs, different incentives are applicable to different pools.
What to focus on? You have a few options, Airdrops – reward users based on certain actions in the ecosystem. For example, executing a given number of swaps, providing a designated amount of liquidity to a given no of pairs or something similar. Retroactive airdrops are a preferred choice (e.g. Optimism Foundation) as users are required to be active participants before receiving any tokens. Vested airdrop is a preferred approach as you partially mitigate the sell pressure on the market.
Secondly, in the early stages your rewards and incentives will come from emissions as you are not yet generating revenue. How you structure this is important, you want to (highly) incentivize early adopters, so the emissions should be decreasing and eventually stopped and shifted to the revenue distribution once you start generating solid revenue or start getting reliable traction.
dYdX for example, distributes rewards based on their Q score, a metric computed based on market maker’s uptime, depth, and spread.
f. Loyalty Program
Similar as trading incentives, loyalty programs are targeted to attract new users and incentivize them to perform actions that are favourable for TVL/Volume/Revenue or any other KPI you find important. How Level finance or GMX did it is that for every 1$ traded you receive escrowed tokens that represent your share in a pool.
g. Revenue Redistribution
Revenue redistribution became a really effective and important incentive following the GMX success. It works in a circle, the higher the protocol revenue the higher the rewards paid out to the participants, the more users trade the more rewards are there for them, hence a strong incentive to stake or hold protocol’s native token.
It is important to note that a strong sell pressure will come eventually if you pay rewards in your native token. You can partially mitigate this by vesting or locking the paid out rewards, or as GMX did pay out rewards in a non-native token. This is particularly effective as it does not create any sell pressure, but it is not suitable for every protocol as you also need to charge fees in non-native tokens (GMX does this in ETH and AVAX).
h. Hooks
Hooks became popular with their introduction by the CoW Protocol and will be one of the key features within the upcoming Uniswap V4. They are essentially the contracts that run at various points of a pool action's lifecycle and can be executed before and/or after the order.
Pre-hooks can be used to define conditions or parameters for an order, for example executing the code necessary for validating an on-chain signature.
Post-hooks execute after a swap takes place and the receiver address receives the funds. They enable the funds to be used immediately.
Hooks can be used for variety of features, from staking, opening an LP position to just-in-time smart orders and bridging.
i. Protocol Owned Liquidity (POL)
Firstly introduced by Olympus Pro is now in use by numerous protocols targeting to attract liquidity and solve the mercenary capital problem. Adequate liquidity plays a critical role in trading protocols since larger pools can accommodate higher open interest. However, relying solely on liquidity providers can be expensive.
POL allows projects to deploy their own liquidity through a feature called Bonds or Bonding. Bonding essentially means that the protocol sells their tokens to the buyers at a discount, who provide another token in return. This token eventually forms part of the protocol’s treasury.
With the tokens received from the bonding process, the protocol utilizes these tokens by providing liquidity on DEXs while collecting the transaction fees.
6. Best Practices
a. 1inch Fusion
A new DEX standard proposed by the 1inch team implemented a way to execute swaps without spending gas or being front-run, which is essentially solving two of the AMM challenges we described earlier. The solution comes with the following features:
All market liquidity is aggregated in one place,
Maximizing trade efficiency,
Offers swapping without holding a native token,
MEV protection,
Minimizing/Removing gas fees.
In a nutshell it is a limit order with a variable exchange rate filled by a professional third party market maker called a resolver. An order's exchange rate decreases from the desired rate to the minimal return amount (Dutch auction) until it becomes profitable to fill the order. Multiple resolvers compete for the order to ensure it is filled.
Each order has an auction start timestamp (= order's signature timestamp + a waiting period). The waiting period is used as a compensations for different block generation speeds on different networks.
Before the auction starts, an order can be filled at the auction start rate (a max rate possible), and the rate gradually decreases over time. The order filling rate is a piecewise linear function that depends on multiple parameters, such as volume, gas costs, and similar.
b. Velodrome vs. Solidly
Velodrome Finance is an AMM that combines the features of Curve, Convex and Uniswap and acts as a main DEX on Optimism. Solidly on the other hand was initally launched by Andre Cronje on Fantom network, but later migrated to Ethereum.
Velodrome took a lot of features originally built by Solidly and added them its own flavour. One such feature is the alignment of protocol emissions based on generated fees which was the key innovation of Solidly. Through bribes it allows protocols and other stakeholders to become voters to direct future emissions from the pools they voted for. Velodrome has made certain improvements in allowing voters to fairly compensate LPs for impermanent loss.
In Solidly, bribes could be claimed before the emissions from that vote were committed. Velodrome adjusts this mechanisms in the way to allow voters to only vote once per each epoch.
Lastly, Velodrome shifted to a longer emission decay. It solves user incentive issues we touched in the previous chapters - there needs to be a balance between the volume of emissions and their duration to achieve maximum traction.
c. GMX
GMX is a perpetual DEX build on Arbitrum that became very popular when it outperformed the whole market in 2022. It was due to its brilliant dual-token model and its unique incentives and liquidity bootstrapping through their GLP token and an efficient revenue redistribution mechanisms (we will explore this in more details in the next research article on the DEX tokenomics).
It further introduced solid incentives and referrals that encouraged users to actually stake rather than sell their received tokens → Which eventually leads to the token value accrual. A major part in token price sustainability are the fees that are collected in ETH or AVAX and redistributed in the same currencies - meaning it does not effect the floating supply as such nor does it create any sell pressure in GMX’s native token.
But this is not all. The motor behind the exchange is the GLP multi-asset liquidity pool (it consists of stablecoins, ETH, BTC, and other altcoins) instead of the traditional order book or AMM model.
The protocol established a Floor Price Fund that helps ensure liquidity in the GLP pool and provides a reliable stream of ETH rewards. Contrary to most liquidity pools, GLP is not affected by the impermanent loss.
d. Uniswap Pentalogy
Original Uniswap was launched in 2018 and it was a first DEX to gain global adoption. While the original AMM idea was somewhat ground breaking in crypto, its native token UNI still lacks real utility other DEXs have (but this is the topic for another time). Let’s explore how Uniswap models evolved through time.
i. Uniswap V1
Uniswap V1 was one of the first automated market makers that used the CPMM model. We covered this in prior sections but to repeat, using a constant product market maker x*y=k
a range of prices for two tokens is established based on the corresponding liquidities of each token. When the supply of token x increases, the token supply of y must decrease, and vice-versa, to maintain the constant product k.
The main drawback of V1 was that users had to trade against the ETH, meaning there were multiple swaps where multiple transactions were needed.
ii. Uniswap V2
The new version of Uniswap introduced several key upgrades, addressing the limitations faced by Uniswap V1. The most upgrade was the introduction of arbitrary ERC20 pairs, allowing users to LP without going through ETH as in V1. It further incorporate the following AMM formula x*y=k⌃2.
With Uniswap V2 a new price oracle system was introduced which helped provide a more accurate pricing data as it eventually aggregated data from multiple sources, making it more resistant to manipulation.
Another innovative upgrade was the introduction of flash swaps, that allowed users to borrow tokens from liquidity pools instantaneously (users have to provide the same amount of another token or return the principle plus the fees).
iii. Uniswap V3
The third - groundbreaking version implemented a slightly different formula. Anyone can create a position to provide liquidity with a price between two ticks. Tick indexes are logarithmic in price, and specify the lower and upper prices at which that particuar position provides liquidity.
This setup allows liquidity providers to deploy custom amounts of liquidity within the selected ranges.
It further introduced a concentrated liquidity (another DEX that incorporated this was Kyberswap with Kyber Elastic), multiple fee tiers, increased capital efficiency and mitigate the downside risk.
iv. UniswapX
UniswapX is a new permissionless, Dutch auction-based protocol for trading across AMMs. It aggregates both on-chain and off-chain liquidity, internalizes MEV in the form of price improvement, offers gas-free swaps, and can be extended to support cross-chain trading.
Innovation lies in the outsourcing the complexity of routing to an open network of fillers. Swappers sign an off-chain order, which is submitted on-chain by fillers who eventually pay the gas fee - a gas-free swap for the swappers. Additionally, user don’t need to hold native tokens nor pay for the failed transactions.
UniswapX introduces Gas-free swapping with no cost for failed swaps
Outstanding MEV being one of the biggest challenges in crypto is solved via arbitrage and used for improved prices for the swappers.
Another huge feature that is planned for a release later this year is the cross-chain compatibility which should reduce the need for bridges and consequently the risk bridges pose. UniswapX is aimed to act more as a liquidity marketplace, rather than a traditional aggregator.
v. Uniswap V4
Version four of Uniswap is currently being built in public and is expected to be released later this year. It will introduce hooks - similar as discussed in the 1inch Fusion section above. Hooks will be used to customize how pools, swaps, fees and LP positions interact.
Uniswap V4 will allow pools that support dynamic fees, add on-chain limit orders, or act as a time-weighted average market maker (TWAMM by Paradigm presented in prior sections) to spread out large orders over time. Along with this customization, Uniswap v4's architecture reduces costs and ensures efficiency.
Compared to V3, it introduces a new singleton contract - a single smart contract that includes all the pools. The main benefit of doing so are the gas savings that are estimated to be 99% lower.
The singleton architecture further introduces a new flash accounting system. It essentially works with net balances only rather then with in and out transfers separately, leading to a more efficient and cheaper mechanism. This will be enabled through the introduction of the EIP-1153 token standard.
Both of the features above enabled Uniswap to bring back the native ETH that was removed with V2 - both WETH and ETH will be supported in V4.
7. Conclusion
I hope this article has shed some light on the existing AMMs and DEXs, their models, key features and challenges. If you are an investor or a crypto enthusiast this should help you understand the core of the DeFi space better and if you are a builder actually solving one of these challenges, my aim was to give you a solid overview of the options you have. In that case feel free to dig into more details behind the solutions in this article. Main references for a more tech-savvy people are listed below.
In the next article we will focus on tokenomics models behind the DEXs. Namely, how to set up an efficient token model that will drive traction and lead to long term sustainability of the protocol.
Stay salty! 〜