What is Uniswap? I knew Uniswap was an important component of the whole DeFi story.
I just didn’t realize how important it was until I started digging deeper.
Uniswap is the Original Gangster of decentralized apps and its story is the story of DeFi.
If you want to understand DeFi then you need to understand Uniswap well.
The whole crypto space is so young that it reminds me of early pioneers settling in new lands.
There are no degrees, no family businesses, and no established ways of doing things: it is purely people building and experimenting.
The story of Uniswap is that of one of these early pioneers hacking away at a new digital frontier.
1/9. How the Uniswap exchange came about
When Hayden Adams graduated with a degree in mechanical engineering from Stony Brook University in New York he did not know how to write a single line of code.
After graduation, he got himself a job in computational fluid dynamics at Siemens but soon became bored.
According to Hayden’s interview on Bankless: “It sounds futuristic but it’s actually not that exciting… it uses science established by Newton hundreds of years ago”. Good fortune had him get laid off.
While twiddling his thumbs wondering what to do next a friend reached out to him convincing him to look into Ethereum.
Without knowing much about coding Hayden started dabbling in Solidity, the coding language used on Ethereum.
While a little apprehensive to start with, his friend goaded him on by telling him that it was so early that in a year’s time, he would be the world’s expert in Solidity.
And so it was.
By the way, if you don’t know what Ethereum is you need to understand it first before reading this article. If you like you can read my simple explanation: What is Ethereum on elementalcrypto.com.
Hayden soon became enamored with the whole concept behind Ethereum.
There was something exciting about programs holding money and no one controlling it.
After starting to get a grasp of how to code, Hayden thought it would be good to find a project to work on.
Hayden discovers his project
His curiosity was sparked when he came upon a Reddit post and blog post by Vitalik Buterin about how exchanges might be automated.
At the time there was a decentralized exchange called EtherDelta. Without a finance background, Hayden found it too complex to use. It also did not encompass the underlying properties that ETH espoused.
Hayden felt a decentralized exchange should be:
- Censorship resistant: No one can stop it
- Decentralized: No one can control it
- Permissionless: Anyone can use it
- Secure: Anyone can verify transactions
Motivated by the above principles, Hayden decided he would build the exchange that Vitalik envisioned.
He proceeded to develop his knowledge in building web interfaces and continued expanding his understanding of smart contracts.
His exchange would embody the values of DeFi and would be simple to use. In late 2017, he launched a proof of concept which you can see below.
Uniswap first launch
In the spring of 2018, he met with Vitalik at a conference.
After taking a quick look at the code, Vitalik recommended some fixes. In addition, he encouraged Hayden to apply for an Ethereum Foundation grant.
Up until then, Hayden had been financing his living expenses through a timely investment in ETH which had in the meantime appreciated in price.
After applying to Ethereum’s foundation and other entities for grants he managed to raise $100K.
He used this money to fund smart contract audits, hire a contractor to build the site, write the whitepaper, and other basics.
In 2018 Hayden launched the first version of the Uniswap exchange.
At the time DeFi was not a thing and ETH was dying a quick death during the market crash.
Most of his acquaintances from traditional finance did not think Hayden’s decentralized exchange would work.
But soon after launching, people started pouring their money into Uniswap.
True believers and early liquidity providers just put their money where their mouth was.
They weren’t there to speculate but to support the vision of a decentralized exchange.
Soon after, Maker DAO, the largest lending and borrowing platform at the time, moved their liquidity over and after that the rest is history.
The Uniswap exchange today does more volume in trades than Coinbase.
You can find Hayden’s description of those early days in more detail here.
So what is it that is so special about Uniswap and how does it work?
Hey! If you are enjoying this so far, drop your email below to learn about a new coin every week.
2/9. What is Uniswap exchange?
Uniswap is a decentralized exchange that uses an automated market maker to automate trades without a central intermediary.
No, I didn’t think so.
To understand the above sentence let’s first understand how a traditional exchange works:
3/9. How traditional exchanges work
An exchange is simply a marketplace with buyers shopping and sellers displaying their goods.
Imagine you are in that Monty Python’s Life of Brian open-air bazaar:
“How much for the beard?”
“Right, there you are”
“What? Wait a minute…We’re supposed to haggle!!!”
In a market place buyers and sellers will quote each other different prices. What each person is willing to pay is different.
If you have found yourself in any open-air bazaar in the Middle East or anywhere in Asia you will surely have haggled for something.
You might argue that this does not apply to you. That you live in a “developed” economy where prices are fixed.
For instance, in a supermarket, you might argue that products have price labels and that it would be ridiculous to haggle.
I’ll wager if you order a large enough quantity you will be able to haggle with the shop manager. I actually did this a few months ago when relatives were visiting from abroad. They loved the olives in a local outlet and wanted to buy 15 kg. I called the supermarket and secured a 10% discount.
Also, while the price label on the product is fixed today it won’t necessarily remain so over time.
With inflation rife nowadays you may have noticed that you are getting priced out of some products.
You may no longer be willing to buy them because they have become too expensive.
Maybe you won’t go for the premium imported Canadian organic maple syrup this time and go for a lower grade one or replace it with cheaper local honey instead.
Each person has their own price curve which reflects how much they are willing to pay for a given quantity of a product.
Such price curves are also known as demand curves.
I hope you will agree with me by now that market prices for goods are not static.
They fluctuate depending on what price buyers are willing to buy at and what price sellers are willing to sell at.
A price is agreed upon when the price the seller is asking matches the price that a buyer is offering or bidding.
There is also something else I want to tell you about demand curves.
Aggregate demand curves
If we merged everyone’s demand curves together we would get a super-mega-aggregate demand curve.
For example, say I merge everyone’s demand curves for Organic Maple syrup in the city of Palermo (random example).
Demand might look like this
At a price of $40 per bottle, only the richest people in the city are willing to buy.
At this price, only 50 liters are sold in aggregate in a particular week.
If the price drops to $6 then demand increases to 300 liters.
Notice that the relationship is not linear. We will come back to this later.
What kind of products do you find on an exchange?
An exchange may offer all sorts of products.
To name a few these might be metals such as gold and copper, commodities such as wheat and rice, stocks such as APPL, TSLA, and currencies such as Dollars, BTC, and ETH.
Buyers and sellers come to this marketplace to exchange their goods and place their orders specifying the price that they are willing to buy or sell at.
The order book lists everyone’s bid and ask prices.
Here is the order book on Binance:
In the order book above you can see that there is someone willing to sell at 34531.66 and someone willing to buy at 34521.65
When one of them budges (or someone else comes in instead) the seller’s ask price and buyer’s bid price will match and a trade will be made at that price.
The last trade happened at 34,522.00 (in red). The exchange takes a cut on either side.
The ingredients you need for all this to work are
- A central intermediary such as Binance runs the exchange and the order book to match buyers with sellers. They own the database and make the technology work.
- Market makers
What on earth is a market maker?
When we looked at the Binance order book we saw that it has a lot of depth.
There were many people willing to buy and sell at varying prices.
But what is there wasn’t this depth?
You might come in wanting to buy the latest token you heard about.
Say you want to buy 100 MadToken.
What if there is no one with 100 MadToken offering to make a trade at exactly the same time that you place your order?
The market is illiquid.
As a result, your experience on this exchange doesn’t feel great as it does not get fulfilled as fast as you are used to on your other sleek trading apps.
In order to counteract this issue of low liquidity, exchanges commission market makers to come and place buy and sell offers, also known as bid-ask offers, across various price points.
These are companies whose sole purpose is to ensure there is enough liquidity in the market i.e. they make the market (exist).
Why would they do such a benevolent act of kindness?
Market makers get a fee called a spread for providing liquidity.
The fee is the difference between the buy and sell price.
For example, say the going price of ETH is $100.
A market maker may offer to buy ETH from you (bid) for $100 and sell (ask) ETH at $100.05.
Thus they make a nice spread of 5 cents.
If they are providing loads of liquidity in terms of ETH and covering many transactions on the largest exchanges they could be making hundreds of thousands per day.
I found this article useful in understanding market makers.
4/9. How uniswap v2 works
First I am going to first you through Uniswap v2 before taking it a notch up and covering v3.
So, let’s see how Uniswap v2 works:
A decentralized exchange like Uniswap does not use an order book.
Rather it resembles a barter economy.
Imagine a caveman.
Let’s call him Ethan.
Ethan has apples and wants to buy cereal.
Here he is:
In the modern age, Ethan could have sold his apples at the local market and then used that cash to buy cereal at the supermarket.
With a barter economy, Ethan would need to find someone who had cereal to exchange.
People quickly decided that this was too much of a hassle and went on to use money rather than bartering as a means to progress civilization.
Now, let’s imagine a new-age bartering system.
Imagine some lovely people (LPs) coming along.
They have both apples and cereal but they are not hungry. These lovely people are just keeping these apples and cereal for a rainy day.
They place their products in a basket.
Here they are:
Anyone who wants can come along and take some cereal and leave some apples.
The Lovely People don’t care about the mix. They only care about the total value of their products in the basket being the same.
They do this in return for a fee.
This way anyone who wants can come and exchange one item for another without needing to find someone with the exact opposing view to theirs at the exact same time.
Now, let’s bring this example into the cutting-edge mechanics of a decentralized exchange and how Uniswap uses this logic.
Say modern-day Ethan wants to exchange ETH for BTC on Uniswap.
LPs have kindly provided a basket of ETH and BTC in equal value to Uniswap.
Over thousands of years, the original meaning of LPs (Lovely People) was replaced with Liquidity Providers. I still think they are all lovely.
Now you can place your ETH into the basket and take out the equivalent amount of BTC. You pay a 0.3% fee to the LPs who provided the pool of ETH and BTC.
But what is the appropriate amount of BTC to withdraw? How is the exchange rate determined?
Uniswap’s magic formula.
Pay attention because we are going to introduce some math.
Uniswap does not pull the exchange rate from other exchanges.
That would make it dependent on other exchanges.
Whatever it does it needs to be able to do so autonomously. So it follows a formula.
Let’s understand the formula through an example.
The example is similar to one I read about in Duke University’s course about DeFi. In there, they have a tutorial on Uniswap.
Uniswap formula example
Assume 1 BTC = 1 ETH.
And let’s say an LP has kindly put some BTC and ETH into a liquidity pool on Uniswap.
LPs always need to provide 50% of the value of one coin and 50% of the other. So they put up 4 BTC and 4 ETH
Now I am going to make a up nonsense number called k where k = 4 BTC * 4 ETH = 16.
The rule is, whatever happens to my basket, k should always remain constant.
Ethan visits Uniswap and gives his 1 ETH to the pool.
How much BTC can he remove?
Come you can do this! Remember k needs to be constant.
[new amount of BTC] * [new amount of ETH] = 16
[new amount of BTC] * [4+1 ] = 16
[new amount of BTC] = 16/5 = 3.2
Since we started with 4 BTC and we are left with 3.2 BTC, this means Ethan got 4-3.2 = 0.8 BTC.
So Ethan put one ETH in and got 0.8 BTC out.
Hang on a sec! The rate was 1 BTC = 1 ETH.
“What the fungus? This looks like a pretty crappy algorithm. Hear hear! It’s a scam, I say!”
In this example, the pool is pretty illiquid. What if we scaled it up? Say 1000x
Let’s re-run the numbers:
We have 1,000 ETH and 1,000 BTC in the liquidity pool. Hence k = 1,000,000.
Ethan drops his ETH into the pool.
Let’s calculate the BTC that he is due.
[new amount of BTC] * [new amount of ETH] = 1,000,000
[new amount of BTC] * [1000+1] = 1,000,000
[new amount of BTC] = 1,000,000/1001 = 999.000999
So Ethan gets 1000-999.000999 = 0.999001 BTC.
Not too shabby as one famous YouTuber says! (Those who know, know.)
Now scale the numbers up to millions and you get a pretty good exchange rate.
In this example, I have assumed an exchange rate of 1 BTC = 1 ETH to keep things simple.
Wanna use real numbers? huh? Do you wanna? Wanna do it? Come on let’s do it!!!
A real-life example of a Uniswap trade
The price of ETH today, the 8th of April 2022 is $3,223.
Let’s say you want to sell 1 ETH on Uniswap in exchange for USDC.
USDC is a stablecoin where 1 USDC = 1 USD.
Say the liquidity pool for USDC / ETH is about $400Mn.
This means that the pool contains 200Mn USDC and $200Mn in ETH = $200Mn / $3,223=62,054 ETH
So k= 200M*62,054=12,410,797,393,733 (trust me)
Let’s calculate how much you pay
[new amount of USDC] * [new amount of ETH] = 12,410,797,393,733
[new amount of USDC] * [62,054+1] = 12,410,797,393,733
[new amount of USDC] = 12,410,797,393,733 / 62,055 = 199,996,777.1
So you would get 200Mn-199,996,777.1 = 3,223 USDC after which 0.3% would be deducted as a fee to liquidity providers for offering their assets like that.
Now the algorithm looks pretty neat.
You sold an ETH on Uniswap and got the going rate.
Why does the x * y = k formula work?
I was really trying to get my head around this one.
How did Vitalik come up with this formula?
To set the record straight he didn’t.
The person credited with the formula is Alan Lu, another important name in the crypto universe.
Also, note that Uniswap was not the first to come up with the Automated Market Maker model. The origin of AMMs was Bancor. They had been building local community currencies in Israel and wanted to ensure liquidity which led to the discovery of the AMM design.
Let’s plot the x * y = k formula to see what it looks like.
To plot this on an axis let’s plot
y = k / x
Here is what we get:
Whoa whoa whoa! Wait a minute! We’ve seen a graph like this before.
Uniswap’s graph looks exactly like the demand curve that we saw earlier.
On the x-axis we had quantity.
This can be the quantity of maple syrup or quantity of ETH, the quantity of BTC, etc.
On the y-axis, we had price which again is a quantity of dollars.
But we could easily replace it with the quantity of ETH, BTC, USDC, etc.
Why do Uniswap pairs follow an exponential relationship?
If I trade a small amount of ETH in my real-life example then the price hardly moves.
But if I trade a large amount it executes at an exponentially worse rate.
If I sell 100 times the quantity of ETH I don’t get 100 times the quantity of USDC.
Let’s look at an extreme scenario
When I sold 1 ETH I got 3,223 USDC.
But say I was a whale (a large player in crypto lingo) and wanted to sell 10K ETH.
Then if I plug the numbers into the formula the price per ETH I would get would be $2,776.
My large transaction has shifted the market price.
Below is a table showing how the price per unit gets exponentially worse the larger the amount you wish to transact.
This example is for ETH and DAI where 1 ETH=100 DAI and a k=100K.
Note how the cost per ETH changes or slips along the curve the larger the transaction
5/9. What is slippage?
Slippage is the difference in the price of an asset when you place the order versus when it actually executes.
The price always slips.
Even if no one else is trading the price slips due to the Uniswap formula.
In our example where we sold 1 ETH the price still slipped. I just didn’t show it to you because the difference was in the decimals which were marginal.
The reality is that there are likely hundreds of transactions happening at the same time as when you place your order on Uniswap which will cause the price to fluctuate thus inevitably contributing to slippage.
What is slippage tolerance on Uniswap?
On Uniswap you can choose the maximum slippage you are willing to accept. The default slippage is 5% but you can set it according to your preferences. In the image below I have set it at 10.05%. This means that the trade will execute provided the resulting slippage is less than what I have set in my slippage tolerance settings. You can access the slippage tolerance by clicking on the preferences icon in the top right of the Uniswap app interface.
Note that slippage exists on centralized exchanges as well.
What is special about Uniswap and other decentralized exchanges is that by incentivizing LPs to provide liquidity they minimize slippage.
The more liquidity, the higher the invariant (k) and the lower the slippage.
Summing up Uniswap from a trader’s perspective
For a first-time trader, the experience is pretty smooth on Uniswap.
All you need to do is hook up your crypto wallet (e.g. Metamask) and exchange or “swap” one asset for another.
You don’t need to understand what a market order, limit order, stop limit, etc are.
The space is less cluttered. Intentionally so.
6/9. Uniswap liquidity providers
All this while, we have been examining Uniswap from the trader’s perspective.
The other stakeholders are those lovely people, the liquidity providers.
Each time a trade executes LPs get 0.3%.
The more transactions happen, the more frequently LPs accrue those 0.3% fees.
Hey, by the way, once you read this article you might be ready for something more advanced from DeFi 2.0 like Olympus and its OHM token. For a simple in-depth explanation check out What is Olympus DAO.
Uniswap LP Tokens
When you deposit your tokens into a liquidity pool you get a receipt.
Say you deposit 50% of the value in DAI and 50% in ETH into a pool.
We will represent this as DAI/ETH.
In return, Uniswap will give you a liquidity pool token that acts like a receipt called Uni v2 DAI/ETH. These are called equity tokens because they represent your equity in the pool.
This makes for a tidy book-keeping process and is common across crypto as it makes coding everything up more convenient.
But the cool thing about this is that you can take these equity tokens and use them on other protocols.
Compound was the first to introduce this methodology.
When you want to remove your DAI/ETH out of the pool, Uniswap will take your Uni DAI/ETH token and return your tokens to you plus any fees you may have earned.
The Uni DAI/ETH token represents your proportion of the DAI/ETH pool.
If you own 10% you get 10% of the fees.
Note that technically you can claim your fees before removing your liquidity.
BTW wondering if DAI crypto is a good investment? Check out that link to find out.
SushiSwap vs. Uniswap
Shortly after Uniswap came on the scene, a Uniswap clone emerged with more hostile leadership.
Led by a pseudonymous character named Chef Nomi, SushiSwap started accusing Uniswap of being controlled by evil VCs.
They claimed that the Uniswap project was not in the hands of the community.
Soon after, SushiSwap airdropped governance tokens to its liquidity providers in a bid to entice LPs to shift from Uniswap to SushiSwap.
Hayden says he had been suspicious of Chef Nomi’s behavior.
Shortly after the airdrop Chef Nomi reportedly sold all his tokens, known as a rug pull in the industry.
He later returned some of the ETH he earned back to the community but apparently was not ever really forgiven.
Chef Nomi seems to have regretted his behavior and later apologized for it.
Uniswap exchange airdrop
In order to counteract the SushiSwap airdrop, Uniswap fast-forwarded its own plans and issued UNI tokens to LPs.
UNI is the governance token on Uniswap and allows holders to vote on community proposals.
In September 2020, anyone who had used Uniswap, whether to trade or provide liquidity, was rewarded with UNI tokens.
All in all there were 150Mn tokens valued at $450Mn at the time ($4.5Bn today) distributed to 250K addresses
This is equivalent to renting out your house on Airbnb rather than letting it sit idle and being rewarded with equity on top of the rent you earn.
Why do liquidity providers need to split the token value 50-50?
You will have noticed that LPs always place 50% of the value in one token and the remaining 50% in the value of another.
In our example, there was $200Mn worth of ETH (62,054 ETH) and $200Mn worth of USDC in the liquidity pool.
There is a reason for this.
Note that the price of 1 ETH = 200Mn USDC / 62,054 ETH = 3223. That is 3,222 USDC per one ETH.
To extrapolate the current price of y in units of x is derived as x/y.
Well, imagine if the token value was not evenly split. Say you added 200Mn USDC but 0 ETH to the pool
This would imply a price of 400Mn USDC / 62,054 ETH = $6,446
People on Coinbase where ETH is going for $3,223 would buy it on Coinbase and sell it for twice as much on Uniswap until the ratios balanced out again.
To protect naive users Uniswap’s interface does not allow you to become a liquidity provider unless you have deposited 50% in one token and 50% in another.
Having said that there are other protocols that do not require a 50-50 split. For example, Balancer generalizes this formula for multiple assets and the amount of liquidity does not need to be equal.
The other thing to consider if you become a liquidity provider is impermanent loss.
7/9. What is impermanent loss?
Impermanent loss is the opportunity cost of providing liquidity. The opportunity cost is the money an LP would have made if they just sat on it.
Let’s understand this better.
When I went to college it meant that I decided to forgo the opportunity to travel the world instead.
The opportunity cost of going to college was traveling the world.
Similarly, the opportunity cost of becoming a liquidity provider is that you don’t fully capture a potential upswing in the value of the tokens.
This can better be understood through an example
Impermanent loss example
Assume I provide 10% of the liquidity in a pool that consists of 100K DAI and 1,000 ETH where the exchange rate is 100 DAI = 1 ETH.
Now imagine market demand shifts: Elon Musk tweets that he has some ETH so everyone thinks they should probably own some too.
Market demand pushes the price up to 1 ETH = 150 DAI.
What happens to our liquidity pool? Traders will buy ETH from Uniswap where it is trading for 1 ETH = 100 DAI and sell it on Coinbase for 150 DAI.
They will continue doing this until enough ETH has been bought that it causes the price to slip to 150 DAI.
To find the new amounts we need to solve the following equations
[new amount of DAI] * [new amount of ETH] = 100Mn (=k)
[new amount of DAI] / [new amount of ETH] = 150
Combining the two we get
[new amount of DAI] * [new amount of DAI]/150 = 100Mn
[new amount of DAI] = square root (100Mn * 150)=122,474
And new ETH = 122,474 / 150 = 816
Let’s do a soundness check:
k=122,474 *816 = 100Mn ✅
Price of ETH = 150 = 122,474 / 816 ✅
Now imagine the liquidity provider wants to withdraw liquidity.
What happens when liquidity is withdrawn from Uniswap
She owns 10%. Let’s see how much that is
12,247 DAI + 8.16 ETH * 150 (price of DAI / ETH) = $24,495
Ok, so what happened here?
This person put in 10,000 DAI and 100 ETH which was worth $20,000 and exited with $24,495 excluding fees.
Not bad you might say. I’ll have some of that!
But what would have happened if she had not provided the liquidity and just held on to the DAI and ETH
Well, then she would now have 10K DAI + 100 ETH*150 DAI/ETH= $25K.
By providing liquidity she has missed out on an opportunity to earn an additional $500.
This LP suffers an opportunity cost, an impermanent loss of $500.
It is impermanent because the market might move back down in the opposite direction.
If the price of ETH moved back down to 100 DAI it would be as if nothing had changed and there is no impermanent loss.
Impermanent loss can actually be pretty permanent
The term “impermanent loss” is somewhat misleading because if you had decided to exit your liquidity position when 1 ETH=150 your loss would have been very permanent indeed.
As you are probably starting to realize, it is not easy to intuitively have a sense of what the impermanent loss on a pair might be.
This is further complicated by the fact that the loss is counterbalanced by the fees you earn.
If ETH/DAI has been trading like wild on its way up to $150 then the fees you earned as an LP may have covered the impermanent loss.
A 3rd dimension to consider is any gains you may have made from airdropped UNI tokens.
So it’s confusing, to say the least.
A good rule of thumb is that the more correlated the two tokens are the less likely you are to suffer from impermanent loss.
For example, the impermanent loss for a pair of stablecoins is going to be close to 0.
There are also loads of impermanent loss calculators to play around with online.
Below is a graph of how impermanent loss increases as the price changes
8/9. What can you trade on the Uniswap exchange?
On Uniswap it is possible to start trading any pair of ERC-20 tokens.
Anyone can start a pair.
All you need to do is to provide 50% of one and 50% of the other.
Note that while a lot of pairs are ETH plus another token, ETH is not an ERC-20 token.
To make it an ERC token it goes through a process called wrapping.
We don’t need to worry about this too much just know that WETH stands for wrapped ETH and always has the same value as 1 ETH.
Up until now, I have been effectively describing Uniswap’s second version. But Uniswap has evolved over time and its latest version is the most impressive one.
First, let’s understand Uniswap’s iterations.
9/9. The three Uniswap versions explained
Version 1 was the original proof of concept that was launched with a small amount of funding from grants.
Uniswap version 2
Uniswap v2 was the more improved product after they raised $1Mn crypto venture capital company, Paradigm.
Launched in May 2020, the new version allowed for more pairs to be added and a more robust product.
In v1 you were only able to add pairs with respect to ETH.
Uniswap v2 allowed for liquidity providers to choose any pair they wanted without necessarily needing to be exposed to the price fluctuations of ETH.
Now that we have understood the basics let’s shoot for the stars and understand v3.
Before we do that let’s take a breather and recap what you have learned so far
- Uniswap was set up by a geek out of college
- It is a landmark DeFi dapp
- Uniswap automated transactions by incentivizing liquidity providers to offer liquidity
- The rule is simple: the quantity of one token times the quantity of the other must always equal k.
- If you provide liquidity you could suffer from impermanent loss
Now read on to Section 2.
Leave a Reply