![]()
Let’s dip our toes into the basics of liquidity pools and AMM (automated market making).
🏊What are Liquidity Pools?
💰Where are Liquidity Pools Used?
🦄 Creating a Liquidity Pool
🙅🏽♂️ Risks with Liquidity Pools — Impermanent Loss
📈 Pricing with Liquidity Pools — Price Feed Oracles
📚Hooked More Resources on Liquidity Pools
Liquidity pools are a collection of assets locked into a smart contract. This collection of assets provides decentralized financial (DeFi) products capital to execute transactions like derivatives, lending, and trading efficiently. In other words, they are the goods needed on the other side to make the transaction happen.
DeFi products want to continuously provide these products, so they need to preserve their liquidity pool over time. Liquidity pools maintain long-term liquidity using an algorithm that utilizes supply and demand principles. It will adjust the asset price depending on the supply of the token.
Liquidity pool instances are powered by a smart contract, AMM (automated market makers). An AMM is a smart contract with algorithms (constant product) that adjust the price to maintain the supply of a token.
What’s the difference between liquidity pools, AMM, and the constant product algorithm?
It can be confusing how liquidity pools and AMM are often used interchangeably, and AMM and constant product algorithms are used interchangeably.
Liquidity pools are a concept of locking tokens into a smart contract to provide liquidity for a pair or set of assets.
AMM is the smart contract that’s created for liquidity pools. Inside the AMM smart contract, there is an algorithm or set of algorithms used to set the price of the tokens.
Constant Product Algorithms are the most popular algorithm used in AMM smart contracts.
In one of the most popular liquidity providers, Uniswap, the algorithm is called Constant Product. The algorithm(s) vary depending on the protocol, and the constant product mostly pertains to Uniswap.
Who can create a Liquidity Pool?
Anyone can become a liquidity provider (LP) for a pool by depositing an equivalent value of each underlying token in return for pool tokens. These tokens track pro-rata LP (liquidity pool) shares of the total reserves and can be redeemed for the underlying assets at any time.
Liquidity pools are used across many products in the DeFi space, like derivatives, lending, and decentralized exchanges.
Derivatives
https://www.investopedia.com/terms/d/derivative.asp
To cater to common derivative instruments like options, futures, and perpetual futures, crypto derivative platforms require liquidity locked in for a future date.
If the platform doesn’t have the promised funds on the set future date, it will default on its contract. Platforms that offer perpetual contracts must be consistently liquid because the future date is unknown.
With derivatives, there is a concept called liquidation event. With derivatives, any losses from the trade need to be funded from the margin. If the price moves against the trader’s open position, unrealized losses erode the margin provided by the trader. The trader’s position must be liquidated when these losses become equal to the margin.
Long story short, derivative platforms need to be prepared to liquidate their customers at a moment’s notice.
New to trading? Try crypto trading bots or copy trading on best crypto exchanges
More on Crypto Derivatives can be found here:
Lending
In lending protocols like Compound, that’s not peer-to-peer lending; funds are borrowed against liquidity pools. Lenders who lend their funds to the lending protocol create a single-asset liquidity pool.
In this single-asset liquidity pool, the funds deposited for lending becomes a fungible resource, and ERC20 tokens (“cTokens with Compound”) that represent the deposited funds are issued to the depositor. Depositors can redeem these cTokens at any time for their underlying tokens. As interest accrues over time, the depositor can redeem cTokens at an exchange rate relative to the supplied assets.
Source: https://coinsutra.com/liquidity-pools-guide/
Decentralized Exchanges
In decentralized exchange protocols like Uniswap, that’s not peer-to-peer trading; funds are traded against liquidity pools. When a liquidity provider creates a liquidity pool with a pair of tokens, they create a dual asset liquidity pool.
A dual asset liquidity pool maintains a 50/50 ratio of the pair of tokens. Traders constantly need a way to liquidate their assets, and liquidity pools in DEXs ensure the asset will remain liquid by setting the price using AMM (automated market-making algorithms), which influences the supply.
This post will focus more on liquidity pools created for DEXs like Uniswap, and we will dive into details on AMM.
Source: https://coinsutra.com/liquidity-pools-guide/
Note: There are liquidity pools for decentralized exchanges that can support liquidity pools of a maximum of 8 tokens like Balancer
To understand how Liquidity Pools are created, we will use the 50:50 dual liquidity pool often used by Uniswap. In 50:50 dual liquidity pools, each asset’s total value is equivalent to the other.
Liquidity pools are like mini stores. Let’s say we have a store that doesn’t accept fiat cash; instead, you must buy apples for grapes and vice versa.
This store has 2 Apples and 8 Grapes, so we’re contributing 10 fruits. Each apple is equivalent to 4 grapes, and each grape equals 1/4th an apple.
Notice that each asset’s total value should be equivalent to each other, the 2 apples are equal to 8 grapes, and 8 grapes are equivalent to 2 apples. This is a key feature in 50:50 dual pools.
Below is an illustration of our liquidity pool.
To create this liquidity pool, we need to create a smart contract and deploy that smart contract to a blockchain network. To create and deploy the liquidity pool contract, we use platforms like Uniswap or Balancer, which also act as DEXs (decentralized exchanges). These platforms require us to connect our wallets and fill out a form about our liquidity pool. Once that’s completed, the platform generates the smart contract and deploys it.
The article and video below break down how to create a liquidity pool on a platform like Uniswap:
Managing Supply & Demand in the Liquidity Pool
The goal is to keep this “store” liquidity pool useful for as long as possible, so we need to constantly adjust the price to maintain a sufficient supply of assets. We accomplish this with the constant product formula.
Constant Product Formula
The constant product formula uses the supply of both assets (apples and grapes) to preserve the constant supply.
Uniswap, one of the most popular liquidity pools and decentralized exchanges, uses the formula constant products.
x * y = kx = token x quantity, y = token y quantity, k = constant quantity
The formula states that trades must not change the product (k) of a pair’s reserve balances (x and y). Because k must remain unchanged, it is often referred to as invariant or constant.
Defining our k, Constant/Invariant
Our liquidity pool has 2 apples and 8 grapes, so using the formula above, the constant product would be 16.
2 Apples * 8 Grapes = 16 = k
16 is our golden number, our constant, and we must maintain this constant throughout.
Change in Supply & Price
Chef Alice wants to start creating her wine and needs four grapes.
How many apples would 4 grapes cost?
With liquidity pools, the price is determined by the amount that will be purchased. If Alice wanted to buy 1 grape or 5 grapes, the price per grape would be different because the price adjusts with the supply & demand of the asset. It’s like surge pricing or how stocks are priced, they adjust in price throughout the day depending on different factors.
Right now, we have 8 grapes in total, and Alice wants 4 grapes for her wine, which would leave us with 4 grapes after her purchase.
What are the remaining Grapes After Purchasing 4 Grapes? 4 Grapes
8 Total Grapes – 4 Grapes Taken = 4 Grapes Remaining
After this order, we would have just 4 grapes left, if Chef Alice takes any more grapes, we’re out of business! So we need to increase 📈 the price of grapes.
To increase the price of grapes, we go back to our constant defined earlier, which is 16. Remember the 1st rule of liquidity pools, we must always maintain our constant, that’s defined by x * y = k. To maintain our constant, we must figure out how many apples to fulfill Chef Alice’s order of 4 grapes.
How Many Apples Does the Pool Need for 4 Grapes? 4 Apples
16 / 4 Grapes Remaining After Order = 4 Apples Required in Pool
If we have 4 grapes and 4 apples, we would be able to maintain our constant of 16.
Would the New Supply Maintain the Constant, K? Yes
4 Grapes * 4 Apples = 16, our constant is preserved
How many Apples would 4 Grapes Cost? 2 Apples
4 Apples required – 2 Apples in Pool = 2 Apples Required for 4 Grapes
The calculation above can be simplified to the formula below
x = apple supply, y = grape supply, px = amount of x purchased, py = amount of y purchasedIf x is being purchased
((x * y)/(x – px)) – yIf y is being purchased
((x * y)/(y – py)) – x
So for our pool with 2 apples and 8 grapes, where Chef Alice is purchasing 4 grapes, the cost of 4 grapes would be 2 apples.
((2 apples * 8 grapes)/(8 grapes – 4 grapes purchased)) – 2 apples= 2 grapes
The price of the grapes is significantly much higher because this formula is ratio oriented. If there are more apples and grapes in the pool, the price of each asset won’t fluctuate as much. Let’s say we had 200 apples and 200 grapes. If chef Alice took 2 apples, the price of the 2 apples would only be 2 grapes.
200 Apples * 200 Grapes = 40000 is the constant200 Apples – 2 Apples for Alice’s recipe = 198 remaining Apples40000 / 198 Apples remaining = 202 Grapes are needed in the pool202 Grapes needed in the pool – 200 Grapes in the pool = 2 Grapes is the price for 2 Apples
We can also use our formula to determine how many apples it would cost the 2 grapes.
((200 * 200)/(200 – 2) – 200 = ~2 Grapes is the cost for the 2 Apples
Slippage
The increased quantity also provides a lower slippage, a difference between the executed and expected prices. If someone leaked Alice’s wine recipe and everyone in town wanted to start buying grapes to try out her recipe, the price of grapes would fluctuate depending on how large the quantity is. High liquidity prevents slippage, so if the quantity is significantly larger than the orders coming in, the price wouldn’t fluctuate as much and will be more predictable.
Note: This is a very simplified run through of the Constant Product formula, to get into the details checkout Uniswap’s whitepaper:
Click to access whitepaper-v3.pdf
Impermanent loss is the biggest risk of being a liquidity provider (LP). Impermanent loss can be monitored, but it’s only a loss until you withdraw funds from your liquidity pool.
Impermanent Loss is the loss LP faces for putting their tokens into a liquidity pool instead of holding them.
When does Impermanent Loss Occur?
Impermanent loss occurs when the two tokens you added to the liquidity pool stray further away from their counterpart’s original price.
Think of the two tokens in the pool as friends; they always need to succeed and fail together. One can’t succeed while the other stays stagnant, and one can’t succeed, and the other fails.
If the price of the tokens is drifting off from each other, you’ll have a greater chance of experiencing impermanent loss.
If the price of the tokens moves in the same direction, you have less chance of experiencing impermanent loss.
Note: Depending on the fees collected for each trade, the liquidity mining options, and the degree to which the assets price moves, the impermanent loss may or not be significant or even be considered a loss.
Impermanent Loss in our Grape & Apple Liquidity Pool
Refresher on Current Liquidity Pool State
Before getting into impermanent loss, let’s refresh ourselves on the current state of our liquidity pool. After Chef Alice purchased 4 grapes, we now have 4 apples and 4 grapes in our liquidity pool, and we are still maintaining our k (constant) 16.
The “Others” Contributing to Our Liquidity Pool
Other people want to contribute to our liquidity pool and add their grape and apple tokens. They add 4 more apple tokens and 4 more grape tokens.
With the additional 4 apples and 4 grape contributions, the grape and apple liquidity pool have 8 apples and 8 grapes. Since your contributions account for 50% of the pool, you will get LP Tokens representing a 50% share.
Current Price of Apples
Using the calculation we used in the above section, “Managing Supply & Demand in the Liquidity Pool,” we can use the same calculations to determine the price of one Apple in our pool.
If x is being purchased
((x * y)/(x – px)) – yIf y is being purchased
((x * y)/(y – py)) – x(8 apples * 8 grapes) / (8 apples – 1 apple purchase) – 8 grapes = 1.14 grapes is the cost
Or we can break down the calculations accordingly:
With the additional 4 grapes and 4 apples, what is our constant? 64
8 apples * 8 grapes = 64 = kAfter one apple is purchased, how many apples remain in the pool? 7
8 Apples in Pool – 1 Apple = 7 Apples RemainingHow many grapes would we need in the pool after selling 1 apple? 9.14
64 / 7 remaining Apples= ~9.14 grapes needed in poolDoes 9.14 grapes and 7 apples help us maintain our constant? Yes
9.14 grapes needed * 7 remaining apples = ~64How many grapes would an apple cost? 1.14 grapes
9.14 grapes needed in pool – 8 grapes in pool = 1.14 grapes
The Price Hike
Chef Alice decides to share her famous apple pie recipe, so now everyone and their mother wants to make her famous apple pie. This brings up the demand for apples, causing the price of each apple to increase from 1.14 grapes to 3 grapes, bringing a price increase of 60%.
While the price of apples increased by 60%, the price of grapes stayed the same, making this situation a likely case of impermanent loss.
The Arbitrage Moment
While most exchanges increased the price of apples from 1.14 to 3 grapes, your liquidity pool still has apples at 1.14 grapes. Now your apples are a discount compared to the price at most exchanges. Chef Bob sees this arbitrage opportunity and buys 2 apples from your pool for 1.14 grapes each and sells it to another in exchange for 3 grapes each, making a profit of 1.86 grapes for each apple and a total profit of 3.72 grapes.
Bob spent 2.28 grapes for 2 apples
2 apples * 1.14 grapes ea. in your pool = 2.28 grapes for 2 apples from your poolBob made 6 grapes for selling 2 apples
2 apples * 3 grapes ea. in other exchange = 6 grapes for 2 apples in other exchangeBob made a profit of 3.72 grapes in arbitrage
6 grapes from exchange – 2.28 grapes from your pool = 3.72 grapes in profits
People like chef Bob will continue to buy apples from your pool until the global price matches your liquidity pool price. If the price is the same or slightly less, it wouldn’t make sense with the trading fees to go through this effort of buying from one exchange and selling to another.
Calculating Impermanent Loss
The formula below will help you calculate the impermanent loss.
We determine the number of assets we will withdraw from the pool using the formula below. We will measure the value of x against y, if we were to measure ETH against the dollar, then ETH would be x, and y would be the dollar.
Assets you will you withdraw, y is the asset you measure value with
√(k/r) * lp share = x
√(k*r) * lp share = y
Since we’re using a 50:50 pool, the value of both assets should be equivalent. So can calculate the value of asset y and multiply it by 2.
In a 50:50 pool the value of x and y should equal each other
x * r = yLP Value -> Total value of assets withdrawn
(√(k*r) * lp share) * 2 = lp value
Impermanent loss is the difference between the liquidity pool value of assets and the value of assets if they were just held (hodl), often this value is calculated as a percentage of difference.
Hodl Value -> Total value of assets initally put in with today’s new price
(x * r) + y = hodl valueImpermanent Loss
(lp value – hodl value / hodl value) * 100
Knowing all of this, we can summarize the formula for impermanent loss as the formula below:
Let’s apply this to our scenario; if you were F12 on your browser and run the javascript formula below in your console, you would get the impermanent loss calculation.
Math.abs(((Math.sqrt(64 * 3) * .50 * 2) – (4 * 3 + 4))/(4 * 3 + 4) * 100)
Below we’ll go through how we got each value and break down the calculation.
How many grapes and apples are left after the arbitrage process?
Ratio of Apples to Grapes (1 APL = 3 GRP), Ratio is y price in x
r is 3 = 3/1How many apples are remaining after arbitrage? 4.62 apples
x = √(64/3) = 4.618802153517006How many grapes are remaining after arbitrage? 13.86 grapes
y = √(64 * 3) = 13.856406460551018
How much do you get when you withdraw 50% from the pool?
You get 2.31 apples and 6.93 grapes when you withdraw
4.62 apples in pool * 0.5 = 2.31 apples is your share13.86 grapes in pool * 0.5 = 6.93 grapes in your share
In your initial deposit, you put in 4 apples and 4 grapes and leave with 1.69 fewer apples and 2.93 more grapes. So if you were to measure everything in grapes, are you walking away with more grapes?
Are we following the 50:50 balance? Yes
2.31 apples * 3 grapes = 6.93 grapes
6.93 grapes from the value of apples = 6.93 grapesHow many total grapes did you withdraw? 13.86 grapes
6.93 grapes from Apples + 6.93 grapes in your share = 13.86 grapesWhat if you just held your assets, how many grapes would you have today? 16 grapes
(4 apples * 3 grapes) + 4 grapes = 16 grapesWhat is the difference if you held vs liquidity pool? 2.14 grapes
16 grapes if you held – 13.86 grapes from liquidity pool = 2.14 grapesWhat is the impermanent loss? 13.38%
(2.14 grapes difference / 16 grapes if held) * 100 = 13.38%
Using the formula, you can start to see a pattern that can be illustrated in the graph below. The graph shows that the loss increases steeply as the price change increases. If the price change is 2x, then there is a ~6% loss, 3x, then there is a ~12.5%; and if the price change is 5x, then there is a ~25% loss.
Check out Eric Eric Falkenstein substack on calculating impermanent loss for a deeper dive into the formula.
There are a lot of calculations here, but luckily there is a tool to help you manage your impermanent loss, APY.vision (https://app.apy.vision/).
Screenshot of my ORW (Orwell) and wETH LP Pool Analytics from APY.vision
Note: This is an overly simplified example that excludes several market conditions below are different factors that affect impermanent loss. All these calculations exclude trading fees earned from each trade.
More on impermanent loss:
The by-product of liquidity pools is pricing oracles. Liquidity pools serving as pricing oracles offer access to historical price and liquidity data that enable other DeFi products.
A little bit about Oracles…
Oracles are data feeds that bring data from off the blockchain (off-chain) data sources and puts it on the blockchain (on-chain) for smart contracts to use.
Types of Pricing Oracles
Even though they all do the same job, they all come in different flavors and vary on the frequency data is extracted, the direction data flows, and the way the data is added to the smart contract. There are different price feed oracle design patterns, immediate read, publish-subscribe, and request response.
Below are a few of the popular implementations of price-feed oracles.
Risks
Price feeds come with several risks if they aren’t implemented correctly, the biggest being price manipulation. The biggest instance was the Harvest Finance exploit, resulting in a $33 million collective loss.
Check out Open Zeppelin’s write-up on price feeds:
Comparison of Uniswap v1, v2, and v3
TWAP Oracles vs. Chainlink Price Feeds: A Comparative Analysis
How to Retrieve Price Data in Smart Contracts
Uniswap Github
Balancer Github
Curve Github
Deribit Education Liquidation
Uniswap: A Good Deal for Liquidity Providers
Why are you miscalculating your impermanent loss and how to stop doing it
Impermanent Loss Calculator
What is Imperment Loss
Learn Crypto Trading, Yield Farms, Income strategies and more at CrytoAnswers
https://nov.link/cryptoanswers
Comments are closed.