135 subscribers
join
Rating
Login
Logout

Liquidity Pool Mechanics

Crypto Education

Table of Contents

If you’re not familiar with liquidity Automated Market Makers already, read this first! Then come back here for a deeper dive.

Providing liquidity is one of the most common - and most lucrative - ways to earn in DeFi. But, the learning curve can be steep for new users. Not to mention, it comes with some unique risks that you need to understand.

Let’s take a look at liquidity pools, how they work, and how to use them for yourself.

What is a Liquidity Pool?

Imagine this: you swap BTC for ETH on a DEX. You choose the amount, click sell, and in a short period of time, your BTC is gone and ETH is in your wallet.

In order for that swap to happen, someone else needs to want to make the other side of the trade. That is, they want to swap the exact same amount at the exact same price at the exact same time. Sounds unlikely, right?

It is. In order for DEXes to work for users, they need a constant supply of liquidity. That is, there needs to be enough activity on the exchange to complete the trades users want to make, when they want to make them. Even the most active, popular exchanges do not have enough orders to complete every single trade with a live buyer and seller. Instead, they need an alternative solution to provide constant liquidity.

That’s where liquidity pools come in. Effectively, the liquidity pool is a big pile of crypto, locked in a smart contract, that is used to complete trades. Let’s return to our BTC-for-ETH example. If the exchange has no open orders for the other side of the swap (ETH-for-BTC), we can simply make the trade with a pool of BTC and ETH. Our BTC goes into the pool, then ETH goes out and into our wallet. Because liquidity pools enable constant liquidity, helping to make decentralized exchanges a better option for more obscure assets and asset pairs.

Liquidity pools exist in contrast to order books: live ledgers of buyers and sellers for every asset pair on the exchange. On-chain order books are used in crypto as well, which we wrote about here.

Where does all the crypto in the liquidity pool come from? Other users. These liquidity providers (LPs) put pairs of cryptocurrencies into the pool in equal amounts. In turn, they receive rewards for their contribution. This is one of the most common ways to earn passive income in DeFi. The rewards often take the form of a portion of the trading fees for transactions which use the pool, as well as liquidity tokens: other tokens which can be traded and reinvested as well.

Liquidity pools are a big reason why decentralized exchanges are considered safer, more private, and trustless compared to centralized exchanges. Pools are held in public smart contracts. Furthermore, you do not need to trust the exchange to process your transaction through hot wallets whose private keys are unknown to you.

How Liquidity Pools Work

The precise mechanics of liquidity pools can be challenging to understand, particularly around pricing. Pontem’s support team often gets questions like “Why did my swap execute at such a bad price?” or “Why is the price on Liquidswap different from Coinbase?”

Fortunately, this can all be understood with some simple math.

The Constant Product Formula

A liquidity pool is typically made up of two digital assets, which form a trading pair. (Pools with more than three or more assets do exist, but we won’t focus on those here.) Returning to our example, the liquidity pool for swaps between Bitcoin and Ethereum would contain both of those cryptocurrencies.

In order to process swaps autonomously, the pool needs to carefully regulate the price of the two relative to each other. To do that, a mathematical formula is coded into the pool’s smart contract. This is called the Constant Product Formula:

X*Y=K

where X is the amount of one asset in the trading pair, Y is the amount of the other, and K is a constant.

Every swap increases the amount of one token in the pool and decreases the reserve of the other, while the value K remains constant. But how do we use this equation to get the swap price?

Let’s write a formula to show how the reserves would change with each swap. The user adds some X to the pool (we’ll call this amount ΔX) and receives some Y in return. (ΔY). That ΔY value is the swap price: the amount of token Y the pool outputs when we input a certain amount of X.

Since K remains constant, we get:

(X+ΔX)*(Y-ΔY)=K

Replacing K with X*Y, we get:

(X+ΔX)*(Y-ΔY)=X*Y

We can now solve for ΔY. (Remember, ΔY is the swap price we’re looking for!)

ΔY=(Y*ΔX)/(X+ΔX)

Let’s look at an example.

Starting Liquidity And Price

Alice is creating a pool for USDT (a US dollar stablecoin) and a new token called TOKEN. He deposits 100 USDT and 400 TOKEN to start. The initial K value is determined when the pool is created based on the initial deposit amounts. Therefore:

K=400*100=40,000

The starting price will be 4 TOKEN for 1 USDT. When starting a new pool, equal values of each token in the pair are added to ensure an accurate price at launch.

How To Calculate Swap Price

Now, Bob wants to swap 10 USDT for TOKEN. So, how many TOKEN will he receive? (Remember, K will stay at 40,000.) Let’s use our formula ΔY=(Y*ΔX)/(X+ΔX), with X for USDT and Y for TOKEN.

ΔY = the amount of TOKEN received

ΔX = the 10 USDT added

Y = the 400 TOKEN in the pool

X = the 100 USDT in the pool

ΔY = (Y*ΔX)/(X+ΔX)

ΔY = (400*10)/(100+10)

ΔY = (4000)/(110)

ΔY = 36.3636

Bob gets  36.36 TOKEN for 10 USDT. Simplified, 1 USDT buys 3.636 TOKEN.

Now here’s the tricky part:

When Bob enters his swap, he will see the current swap price before the swap (4 TOKEN : 1 USDT). But,  the swap will be completed at the price we just calculated, which reflects the change in the pool reserves. So Bob expects 4 TOKEN per 1 USDT, but gets 3.636. That’s a roughly 10% price impact, which is very significant. This change in price between the quote and the filled order is called slippage.

Why did that happen? Well, Bob’s trade was quite large compared to the size of the pool. His 10 USDT are 10% of the liquid USDT. While there will always be some price effect from making a swap in the pool, this is far less noticeable with larger pools. Much of the time, the slippage will be negligible or even too small to notice.

This price effect can actually be a good thing. High slippage discourages people from making swaps that are too big relative to the size of the pool. Otherwise, large swaps would unbalance the pool and render it useless.

When Does K Change?

The value K remains constant only within the time span of a single swap. K changes constantly as the pool rebalances with new amounts of each side of the pair. So, the Constant Product Formula is really only constant for calculating the slippage of one transaction. Every time liquidity is added or removed from a pool, the calculation changes for the next transaction.

Let’s look at the situations which cause K to change:

  1. Swapping Fees

Most DEXes charge users a fee for swapping on their platform, typically around 0.15-0.30 %. (This does not include gas fee charged by the blockchain). These fees are the reward for the liquidity providers who deposit funds in the pool, incentivizing to lock up their crypto and make swaps possible for others.

Collected fees are added to the pool balance until a liquidity provider claims them. Whenever a fee is charged, the protocol treats it as a liquidity event, and K changes just a tiny bit.

Calculating how K changes from these tiny amounts is too complex to cover here. If you’re curious, check out the Uniswap documentation for the exact formulas; fees in uncorrelated pools on Liquidswap work the same way.

Credit: Uniswap
  1. Adding Liquidity

When liquidity providers add to the pool, the reserve of both tokens has to increase. Otherwise, the exchange rate would be inconsistent, making the DEX unusable. So, liquidity providers need to add equivalent amounts of both tokens.

For example, suppose there are 400 TOKEN and 100 USDT in our pool.

K = 400*100 = 40,000

The exchange rate is 1 TOKEN  for 4 USDT. If you want to deposit 100 TOKEN, you’ll also need to add the equivalent amount of 400 USDT. The new K value will be:

K=(400+100)*(100+25)=500*125=62,500

If you add 100 TOKEN, raising the reserve to 500 TOKEN total, you now own 20% of the liquidity pool. This means you earn 20% of the trading fees. As liquid is added and removed, your share of the overall reserves will change, as will your share of the fees.

A Real-Life Example From Liquidswap

Once you understand how the formula affects price, you can see how liquidity conditions affect trading. Compare these three APT-USDT pools on Liquidswap:

They all offer USDT bridged using different protocols: LayerZero, Wormhole, and Celer. The LayerZero USDT pool is the most liquid, with over $30,000 USDT. A 10 APT swap will move the price by 0.38%, which is acceptable.

The Wormhole USDT-APT pool has much less liquidity with only $3,700 USDC. Swapping 10 APT will result in 3% slippage. Plus, the exchange rate is already worse in this pool: 11.2 USDT for 1 APT in the Wormhole pool, versus 11.58 USDT in the LayerZero pool.

Finally, the least liquid of the three is the Celer USDT pool, with just 6 USDT in reserves.

Here, the current price is just 0.57 USDT for 1 APT, and swapping 10 APT will move the price by a whopping 94.39%. In these cases, Liquidswap will give you a warning.

Sadly, we’ve had Liquidswap customers reach out for help after losing money swapping in low-liquidity pools. There’s unfortunately nothing we can do in these situations, as it’s just how Automated Market Makers function. Remember to alway use caution, operate according to your risk tolerance, and do your research!

Price Differences on Decentralized vs. Centralized Exchanges

Let’s say that TOKEN is also listed on a centralized exchange, where it trades for 0.25 USDT. But when we execute our previous example, the price on our DEX  increased to 0.275 USDT. Now what?

Such a discrepancy creates an arbitrage opportunity. Arbitrage means taking advantage of a difference in price in two different places: buy something where it’s cheap, sell it where it’s expensive, and pocket the difference. Liquidity pools use arbitrage to balance themselves and return to equilibrium.

In our example, traders will buy TOKEN on the centralized exchange for 0.25 USDT, then sell it on the DEX for 0.275 USDT. This gives them a .0275 profit on each token, or just under 10% (before gas and trading fees). These TOKEN-for-USDT swaps will increase the TOKEN reserves in the liquidity pool and diminish the reserve of USDT. Traders will continue doing this until the arbitrage opportunity is over, meaning the DEX price matches the centralized exchange.

The same effect will happen if the pool is created with a starting price that’s different from the overall market. For example, if he deposits just 300 TOKEN and 100 USDT, the pool’s initial TOKEN price will be 100/300=0.333 USDT. Arbitrageurs will quickly notice, buy TOKEN at 0.25 USDT elsewhere, and sell it into the pool for a profit.

Arbitrage traders (and their bots) can’t watch every pool on every DEX. If a certain trading pair is unpopular (such as Celer USDT-APT from our previous example) and reserves are low, the price can remain detached from the external market for a long time.

Correlated Pools

While the Constant Product Formula works well for most pools, stablecoins pose a challenge because of high slippage. Stablecoins should always trade 1:1 with each other and their fiat peg. (Read here for a detailed explanation of stablecoins.) If there’s too much slippage, the stablecoin won’t be stable! That’s why liquidity pools are not a great fit for stablecoin-to-stablecoin swaps.

The same goes for correlated pairs like BTC/WBTC and ETH/WETH. The exchange rate should be extremely consistent. As a solution, Solidly (a DEX on Fantom built by Andre Cronje) introduced an alternative pricing formula:

X3Y + Y3X = K

Liquidswap adopted the same formula for swaps between correlated assets because it minimizes slippage, even with large transactions. (For complete technical details on how this works, read the Docs.)

For example, let’s make a pool with 100 USDT and 100 USDC. Both of these stablecoins are pegged to the US dollar, so the exchange rate should be a perfect 1:1. Then, Alice swaps 30 USDT for USDC:

Let’s see what happens if the pool uses the Constant Product Formula:

ΔUSDC=(USDC*ΔUSDT)/(USDT+ΔUSDT)

ΔUSDC=(100*30)/(100+30)=3000/130=23.077.

Alice will get just 23.077 USDC in return for her 30 USDT. In other words, she lost $7. This just won’t work for stablecoin trading.

Now let’s see what happens if we use X3Y + Y3X = K

K=(100^3)*100 + 100*(100^3) = 100,000,000 + 100,000,000 = 200,000,000 (200 million)

((100 USDT+30 USDT)3 * ΔUSDC) + ((100 USDT+30 USDT) * ΔUSDC3)=200,000,000

2,197,000*(ΔUSDC)+130*(ΔUSDC3) = 200,000,000

To simplify the equation, let’s write it down as 130ΔUSDC3 + 2,197,000ΔUSDC - 200,000,000=0.

For the rest, dust off your algebra or use an online calculator.

The real solution is 70.39332, meaning 70.39 USDC will be left in the pool after the swap. Therefore, Alice received (100-70.39)=29.60 USDC. So, 40 cents were lost to slippage.

There’s still some price impact because the swap was so large relative to the pool balance (almost 30%), but it’s still far better than with the Constant Product Formula.

Plus, swap fees in correlated pools on Liquidswap is just 0.04%.

Liquidity Pool Risks

We’ve already examined the danger of swapping in low-liquidity pools, but there are other risks, too.

Impermanent Loss

The other main way liquidity pools can be risky is impermanent loss. Impermanent loss occurs when the price ratio of the combined assets fluctuates, as they do in any uncorrelated pool. Remember, the assets you deposit in the pool have value of their own which changes. If you deposit an asset at a certain price, then the price decreases, you can incur a loss if you withdraw your deposit before the pool has corrected itself. Make no mistake: if you do withdraw under these conditions, the loss is, in fact, permanent.

The loss is called impermanent because it is not realized until you withdraw your funds. If you wait to withdraw until the exchange rate is in your favor, there can be no loss.

Tips to Stay Safe in Liquidity Pools

Here are a few simple tips to avoid losing money in liquidity pools.

  1. Never use a pool with low liquidity.

As we’ve learned, small pools are prone to bad exchange rates and huge slippage. Always swap in large, active pools.

In this screenshot, you can see two pools for the same assets. One has just $23 in reserves, while one has $1 million. Which one would you choose?

The USDC Wormhole - WETH Wormhole pool has only $23 in reserves - clearly not a pool to swap into! Conversely, the USDC Wormhole - APT liquidity pool has over $1 million locked in it, meaning you can make larger trades without much price impact.

If you must use a pool with low liquidity, do not execute a large trade. Either your order will simply not execute because of your slippage settings, or you will end up paying a lot of money for barely anything.

2. Set your slippage tolerance

The very real example we used in this article is a great example for why you should always set your slippage tolerance. Most DEXes allow you to set a maximum percentage of slippage, and will prevent your order from executing if it would be exceeded. This simple step will help you avoid incredibly costly mistakes.

On Liquidswap, maximum slippage is set to 0.50% by default, meaning that a swap will be prevented if the execution price differs from the quote by more than 0.50% in either direction.

You can change the slippage in the settings, but be careful. Setting it too low increases the risk of failure, and you can’t recover the gas fee if that happens.

  1. Turn on Frontrunning Protection

Simply click on the little red lock next to the gear on Liquidswap to turn on Front Running Protection. This protects your transaction from bots which scrape the blockchain mempool for arbitrage opportunities. (Learn more about how frontrunning protection works here.) Note that this great feature is available only for Pontem Wallet users.

Understanding how DeFi liquidity pools work is the difference between successful swapping and losing money. Follow Pontem on Twitter, Discord, and Telegram for more tips, and stay tuned for some exciting announcements coming soon!

About Pontem

Pontem Network is a product studio building foundational dApps for Aptos. Other Pontem products include:

  • Lumio: an Optimistic Layer 2 for Move and Ethereum
  • Liquidswap: the leading Aptos DEX
  • Move Playground: a browser Move code editor
  • ByteBabel: the Solidity-to-Move bytecode translator

Install our wallet and try DEX

Related posts

liquidity-pool-mechanics
6436d5c79176d82be3cebcec
amb-liquidity-pool-mechanics