Muttley’s Week 68: The Basics of DeFi - DEXs, AMMs, and LPs

Divine Dogs
8 min readJul 19, 2023

--

Hello Dogs! This time, we’ll dive into the specifics of what a DEx (Decentralized Exchange) is, how AMMs (Automated Market Makers) work, and what Liquidity Pools (LPs) are all about.

Before we proceed, let’s recap the fundamental difference between traditional finance and the embryonic, yet thriving, world of decentralized finance (DeFi). DeFi is not a single product but a collection of mechanisms that enable the decentralization of existing financial services and tools, as well as the creation of new ones. To achieve this decentralization, DeFi relies on Decentralized Applications (Dapps), which are a combination of smart contracts interacting directly with the Blockchain of the relevant ecosystem, along with a user interface.

Dapps serve various purposes, but let’s focus on services that resemble those of traditional financial institutions. For example, if you wanted to take out a loan, you’d need credit to apply at a bank and receive the desired funds. If you wanted to invest in a promising company, you’d have to analyze its metrics, stock values, open an account with a brokerage, and start trading. Now, consider how a traditional stock exchange operates: it uses an order book, allowing buyers and sellers to specify the prices at which they want to buy/sell a particular stock. A trade occurs when these prices converge. However, if that price convergence never happens, how could you execute your trade? To avoid such a scenario, traditional institutions, like brokers and banks, act as market makers, providing liquidity by placing buy and sell offers for a particular asset. The order book model, therefore, relies on the presence of a market maker to ensure liquidity for transactions. However, in the DeFi world, where decentralization is paramount, market makers as centralized entities no longer make sense.

Let’s explore the solution to this problem and how it leads to the creation of DExs, AMMs, and LPs.

The Solution: DExs, AMMs, and LPs

You might be wondering what exactly AMMs are, how LPs function, and if DExs have order books. Let’s address these questions and shed light on the mechanisms of the cryptoverse and how they work.

Liquidity Pools (LPs)

Think of a Liquidity Pool as a large pot containing pairs of tokens that operate based on specific rules provided by an algorithm. Let’s take the most popular DEx, UniSwap, as an example. If a farmer wants to provide liquidity to this market, they’d select a specific token pair and supply an equal value of each token. For instance, let’s assume the farmer wants to add liquidity to the ETH/USDC pool, where one Ether token is being traded at $1000. So, since 1 ETH = 1000 USDC in the market, for every token of ETH the farmer provides to the pool, they must also provide 1000 USDC tokens. Providing liquidity to an LP involves adding equal amounts of two tokens to the pool, at least in UniSwap v2.0, which we’ll use as a general example throughout the rest of the article. (Please note that each DEx may have specific rules and algorithms, so investors should be mindful of these differences, which are detailed in the respective DExs’ whitepapers. Additionally, UniSwap has launched its v3.0, which differs from v2.0 in some specific aspects, such as liquidity concentration, though v2.0 remains active and will continue as long as Ethereum exists.)

Representation of the LP mechanism

In essence, an LP represents this pool of coins with a fixed parity. This LP is what provides liquidity to the decentralized marketplaces (DExs). So, if, in a hypothetical situation, only one person is currently engaging in a trade, wanting to buy 1 ETH from this pool, they’d have to spend 1000 USDC tokens (although it’s not quite as straightforward, let’s follow this simplified reasoning). The question that arises here is, how do the Liquidity Pools of these DExs precisely know the value of 1 ETH compared to the dollar at any given moment? After all, AMMs, which are systems used by DExs to determine prices, do not have access to external information for setting the “global” dollar value of each token since they operate on-chain. The answer to this conundrum lies in a simple mathematical equation: [A]x[B]=K.

Graphical example of a constant product in AMMs

The Functioning of AMMs

Let’s explain this equation. Liquidity Pools in UniSwap v2.0 operate based on the constant product market maker concept. What does that mean? The quantity of tokens A in the LP, represented as [A], multiplied by the quantity of tokens B, or [B], always equals a constant value (K). This equation maintains the ETH/USDC price parity in our earlier example. If the ETH market globally rose to $2000, the trading flow in the pool would generate opportunities for arbitrage, a mechanism we’ll explain later. As a result, we’d have approximately 7.06 ETH tokens in the pool and 14120 USDC tokens, setting the price at $2000 for ETH (and the equation governing the pool would still be satisfied, as 7.06x14120~100,000). Besides this basic mechanism, there are other measures in place to prevent specific attacks during on-chain transactions.

One such attack is Front Running, which is common in traditional finance when insider trading occurs. In Blockchain, since transactions are publicly recorded and visible to everyone, any person can see upcoming transactions. Let’s illustrate this with an example to understand how front running can happen. Imagine a market where an LP contains 10 tokens A and 10 tokens B. If our farmer Kaleve wants to buy token B using 1 token A, the market’s state after the operation, excluding any fees for simplicity, will be 11 tokens A and 9.090909 tokens B.

Pay attention to this:

  • 10x10=100 and 11 x 9.090909~100. Hence, we’re still following the formula [A]x[B]=K, and Kaleve would receive 0.909091 tokens B while spending 1 token A. However, we know these operations are not instantaneous; there’s always a delay between the transaction and its validation/mining into a block, which is where the front-running attack occurs. Malicious agents, typically programmed bots, observe the intention of Kaleve’s transaction on the blockchain and the gas fee they’re willing to pay. They then immediately indicate their intention to buy token B using 1 token A but with a higher gas fee. Here’s what happens:
  1. The bot observes Kaleve’s transaction and jumps the queue (due to a higher gas fee), resulting in the state we previously mentioned, 11 tokens A and 9.090909 tokens B, with the bot receiving 0.909091 tokens B.
  2. After the bot’s transaction, Kaleve’s transaction is executed, and we’d have 12 tokens A and 8.33333 tokens B in the LP (again, 12x8.3333~100), with Kaleve receiving 0.757576 tokens B.
  3. Following Kaleve’s transaction, the bot would pay 0.757576 tokens B to the LP, receive 1 token A in return, and profit 0.151515 tokens B at Kaleve’s expense.

For the bot, the risk of executing this front-running attack is virtually zero. To prevent such occurrences, AMMs use protocols like Oracles, as mentioned in the previous article, highlighting the significance of projects like Chainlink.

Another example of Front Running in the cryptoverse, with Bob hurting Alice and profiting.

There are risks associated with trading tokens on DExs, using AMMs, and providing liquidity to LPs. One of them is the already mentioned front running, while another well-known risk is the Impermanent Loss, a concept unique to the cryptoverse. This loss involves arbitrage opportunities within LPs that some use to profit, as well as price adjustments via AMMs. We will delve into these and other risks in a future article, as they deserve careful consideration.

Conclusions

  1. AMMs: These are systems that use specific algorithms to automate trades within a DEx, creating a liquid market through Liquidity Pools (LPs), which are pools of paired tokens. AMMs have an equation governing price formation. For instance, in UniSwap and other constant product systems, [A]x[B]=K.
  2. DExs: These are online/on-chain “exchanges” that allow token trading through specific systems, including AMMs and LPs. Another system used by DExs is order books, with examples like Dex Lab, Raydium, and others. The order book mechanism of these DEXs generally places users’ assets Off-Chain but records the information On-chain for quick transactions. However, this kind of Order Books is feasible only on fast blockchains like Solana, Binance, and Avalanche. Both systems have their pros and cons, but DExs provide users with an environment of privacy, speed, access to promising tokens, and extreme decentralization.
  3. LPs: LPs represent the liquidity of DExs that use AMMs. LPs hold the tokens of users who decide to provide liquidity for a specific token pair. To do this, users must deposit equal amounts of the two tokens into the pool. Users who provide liquidity receive a special token called LP-Token, which serves as proof of their liquidity provision to the pool. LP-Token holders are also entitled to receive a portion of the transaction fees used by DEx users. Suppose Kaleve decides to provide liquidity to the ETH/USDC pool, making up 1% of the total liquidity. UniSwap, where Kaleve provides liquidity, distributes 0.3% of its transaction fees in ETH to all liquidity providers in that pool. Thus, Kaleve is entitled to 1% of that 0.3%, which might seem small, but considering that the average daily fees paid in the pool exceed $200,000, Kaleve could passively earn around $180 monthly. However, it’s essential to consider risk factors, and in the case of LPs, the risk of Impermanent Loss might outweigh that monthly gain.

In conclusion, this article aimed to explore some of the fundamental concepts of decentralized finance (DeFi). As crypto and DeFi continue to expand, there’s much more to cover, including more complex concepts like Impermanent Loss, CLMMs, Yield Farming, and Lend & Borrow, among others. These topics deserve their own in-depth discussions, and in future articles, we’ll explore them further, including possible strategies to maximize your gains using Defi protocols.

If you still have questions, don’t forget to join our Discord and ask. We can even use your questions to generate new articles. Until next time, fellow Dogs!

Be sure to follow us on Twitter too, for more educational content like this.

Discord: https://discord.gg/SPHJw9CfGf

Twitter: https://twitter.com/DivineDogsNFT

Written by: @Kaleve_

--

--