Skip to content

Latest commit

 

History

History
executable file
·
108 lines (52 loc) · 23.8 KB

Day67.md

File metadata and controls

executable file
·
108 lines (52 loc) · 23.8 KB

Decentralized Exchanges

A DEX is an exchange that is inherently decentralized. Traditionally, exchanges have been run by centralized companies that are responsible for all aspects of how the company operates. Normally, entities known as "market makers" form the backbone of all trading on a platform by providing the majority of liquidity. This is usually from the reserves that the exchange itself is holding or from major players operating on the exchange. By placing orders on both the buy and sell sides of the order book, they make it possible for other traders, called market takers, to be able to execute their own trades with maximum efficiency. DEX, however, handled all of this with pure code, meaning there's no central authority that has any power over the system. This is made possible because of smart contracts that act as automatic market makers. AMM acts to guarantee liquidity  in the market via algorithms instead of any human intervention.

The liquidity comes from providers, which could be anyone who is incentivized to lock their tokens into liquidity pools in return for a share of all network fees. DEXs can offer virtually all the functionality of a centralized exchange but with notably lower fees, no KYC requirements, and no type of registration. This has many benefits and is attractive to a variety of users, but it's also completely unregulated and, as such, comes with some level of risk.

DEX risk

While it's true that you don't have to trust a person or a company, you do need to trust the smart contracts you're interacting with. There are still some potential issues to consider. One is called slippage which means the difference between the expected price of a trade and the actual price that gets executed. This can happen because the market moves just as an order is going through, or when liquidity is too low, the trade itself can actually move the market quite a bit. There are usually some safety nets in place. If a user isn't careful, they can end up paying more or receiving less than they had originally anticipated.

This is best combated by paying close attention to the amount of liquidity available for the asset you're trying to exchange and avoiding small volume pools. Services like Uniswap offer the ability to set slippage tolerances that will cancel a trade if it's going to move the price past a certain percentage, which can certainly help to at least mitigate some mistakes.

One more serious issue to watch out for with DEXs are scam tokens. Since everything is user-run and unregulated, often anyone can deploy a new asset to the ecosystem. While this gives freedom and flexibility to project developers, it also paves the way for scammers to make virtually identical copies of existing tokens, all in the hopes of confusing users who are trying to purchase the real asset. The name and icon can be exactly the same; the only obvious difference will be the address of the smart contract you're interacting with. This is why you should always follow official links from the developer's website when looking to trade new tokens on DEXs. By sticking only to verified links, you should be able to avoid scams.

How a Decentralized Cryptocurrency Exchange Works

On Ethereum, DEX allows us to trade ERC20 tokens for other ERC20 tokens. In DEX, you have to manage your funds yourself, and the benefit of this is that exchanges could get hacked and you could lose all your funds.

The DEX allows you to trade Ethereum-based tokens from one wallet or one account with another wallet or another account, and the funds never leave your wallet until the trade actually happens. So if I'm a maker and I submit an order and a taker takes the order, the exchange does the swap of tokens and never holds on to them in the middle. You don't have the vulnerability of the smart contract being hacked and your funds being siphoned out.

If I'm using an exchange like Uniswap, I need to have some crypto funds. I have to use a browser extension like Metamask to manage crypto funds, fill out the order, submit it, and the taker will take that order. So this is a high-level overview. So you need to bring your own wallet to an exchange  and then DEX will basically take your orders.

DEX uses a protocol, which is a project that has its own Ethereum-based token and is a protocol for creating decentralized exchanges. It's a protocol for taking orders that you see on an exchange and putting those on a server that isn't necessarily decentralized. This is called a relayer, and it just relays orders. It needs to be fast because there's a transaction limitation on the Ethereum blockchain, and it needs to create orders and fulfill them really fast. But your orders are secure. Your funds never go to that server. It's just your intent. Whenever someone takes your order, the relayer basically talks to smart contracts on the blockchain that take your funds and perform atomic swap which basically takes the funds from one ERC20 token to another ERC20 token and transfers the balances instantly.

You do have centralization features like 0x Relay, but they don't expose you to the same kind of vulnerabilities that a traditional crypto currency centralized exchange does. The centralized feature of the relayer is to make orders faster and support higher volumes of trading. To trade Ethereum for other ERC20 tokens, ether itself needs to know how to act like an ERC20 token, which it doesn't do natively. To turn ether into a token, you have to wrap it in a smart contract that has a one-to-one relationship between the ether balance and the WETH.

Atomic Swaps

If you've tried switching between two different cryptocurrencies, you've probably noticed the high switching costs it involves. For example, if you want to trade Bitcoins for Litecoins, you'll need to do several things. First, you'll need to find an exchange that supplies this currency pair. Once you've found such an exchange, you'll need to sign up for it and go through its KYC process to verify your identity. Assuming you've passed the KYC process, you can then deposit your bitcoins into the exchange, essentially forcing you to give up control over your coins. Once the Bitcoins are on the exchange, you can then trade the coins for a transaction fee. Finally, once the trade is complete, you can withdraw the Litecoins from the exchange, which will include additional fees and a waiting period until the coins arrive in your wallet.

As you can imagine, this situation is less than optimal. In a truly decentralized world, users will be able to exchange crypto for crypto directly, instantly, and for free. That's exactly where atomic swaps come in. An atomic swap allows users to trade two cryptocurrencies directly without the need for an intermediary or trust. It will allow me to exchange Bitcoins for Litecoins with complete strangers directly from my wallet. The term "atomic" means that either the operation is conducted as planned or it isn't conducted at all. With an automatic swap, I'll either exchange my coins with the other party exactly as we agreed, or it won't happen at all.

A non-autonomous swap would be me sending Bitcoins to a stranger and hoping for Litecoins in return. This leaves the door open for fraud  or theft since my counterparty can just walk away with my money. In an atomic swap, on the other hand, either both of us get the money or neither of us do. There's no room for human error or manipulation. It's important to note that the atomix swaps don't work with fiat currencies; they only work with cryptocurrencies.

Let's say I want to participate in an atomic swap of bitcoins for litecoins. As the initiator of this swap, I'll take my bitcoins, represented by fiat cash, and put them inside a lock that can only be opened with a long secret combination that I've written down and kept hidden in my pocket. I then send the box over so he can inspect it and see that it has the right amount of bitcoins for the swap. Once another user verifies the amount is correct, the user takes his or her Litecoins and puts them in his or her own see through box. However, my box will have the same exact lock on it as my box has it.So another user doesn't know the combination to open the box. At the moment, only I hold the combination that opens the two boxes, and that combination is hidden in my pocket.

So another user will send the box of Litecoins to me, so I can verify the amount as well. Once I see everything is in order, I pull out the secret combination from my pocket to open the box of Litecoins. As soon as I did that, another user was able to see the combination as well and can now use it to open the box of bitcoins that I sent him/her.We then each get our funds, and the atomic swap is complete.

In real life, boxes are actually "smart contracts," which state that if the transaction doesn't occur as expected within a specific time frame, each party will get their money back. To get a bit more technical, these smart contracts are called Hashed Time Lock Contracts or HTLC. The lock on the box is called a hash, and the combination to open the lock is called preimage.Putting this all together, in an atomic swap, funds are locked inside smart contracts that can be publicly inspected on the blockchain. The funds can only be released with a private key of sorts that matches the hash of these contracts. If at any point either party wants to cancel the swap, they can just walk away, and the funds will be automatically returned to the original owners.

Atomic swapping technology is still in its early stages and has several limitations. Both currencies that are being exchanged must have the same hash algorithm, and both currencies should support specific types of smart contracts.

Liquidity pools and automated market makers

Liquidity pools

Liquidity pools, in essence, are pools of tokens that are locked in a smart contract. They're used to facilitate trading by providing liquidity.

On Coinbase and Binance, trading is done based on the order book. This is also the way traditional stock exchanges work. In this order book model, buyers and sellers come together and place their orders. Buyers tend to buy certain assets for the lowest price possible, while sellers try to sell the same asset for as much as possible. For trades to happen, both buyers and sellers have to agree on the price. This can happen by either a buyer bidding higher or a seller lowering their price.

What if no one is willing to place their orders at a fair price level? What if there aren't enough coins that you want to buy?

This is where market makers come into play. They facilitate trading by always being willing to buy or sell a particular asset. By doing so, they provide liquidity. So the users can always trade and don't have to wait for another counterparty to show up.

We can reproduce this in Defi, but this is really slow, expensive, and pretty much results in a poor user experience. The order book model relies heavily on market makers willing to always make a market in a certain asset. Without market makers, an exchange becomes instantly illiquid. On top of that, market makers usually charge different prices for an asset by constantly changing their prices. This results in a huge number of orders and cancellations that are being sent to exchanges. Ethereum can only process 12–15 transactions per second, and the block time of 10–19 seconds is not really a viable option for an order book exchange. On top of that, every interaction with a smart contract costs a gas fee. As a result, market makers would go bankrupt simply by updating their orders.

How do they work?

A single liquidity pool holds two tokens, and each pool creates a new market for that particular pair of tokens. DAI/ETH can be a good example of a popular liquidity pool on Uniswap. When a new pool is created, the first liquidity provider is the one that sets the initial price of the assets in the pool. The liquidity provider is incentivized to supply equal value for both tokens in the pool. If the initial price of the tokens diverges from the current global market price, it creates an instant arbitrage opportunity that can result in lost capital for the liquidity provider. This concept of supplying tokens in the correct ratio remains the same for other liquidity providers that are willing to add more funds to the pool later.

When liquidity is supplied to the pool, the liquidity provider receives special tokens called LP tokens in proportion to how much liquidity they supplied to the pool. When the trade is facilitated by the pool, 0.3% fee is proportionally distributed amongst all the LP token holders. If the liquidity provider wants to get their underlying liquidity back plus any accrued fees, they must burn their LP token. Each token swap that the liquidity pool facilitates results in a price adjustment according to a deterministic pricing algorithm called AMM.

AMM

Ever wondered how decentralized exchanges process trades and discover prices?

Unlike traditional exchanges, a DEX uses an automated market maker (AMM) to enable a fluid trading system that borders on autonomy, liquidity, and automation. Market-making connotes the process involved in defining the prices of assets while simultaneously providing liquidity to the market. In other words, a market maker does create liquidity for a financial asset. It must find a way of meeting the selling and buying requests of traders, which in turn plays into the pricing of said asset. For instance, a Bitcoin exchange uses an order book and an order matching system to facilitate trades. Here, the order book records and showcases the prices at which traders desire to buy or sell bitcoin. The order matching system, on the other hand, matches and settles sell and buy orders at every given time. The most recent price at which bitcoin was bought will automatically feature as the market price of the digital asset. In some cases where there are not enough counterparties to trade with, the market is said to be illiquid or prone to slippage. Slippage occurs when processing large order volumes drives the price of an asset up or down. To mitigate this occurrence, some crypto exchanges hire professional traders in the form of brokers, banks, and other institutional investors to provide liquidity on a continuous basis. Liquidity providers ensure that there are always counterparties to trade with by providing bids and offers for orders that match the orders of traders. The process involved in providing liquidity is called "market making," and those entities that deliver liquidity are market makers.

Decentralized trading protocols do away with order books, order matching systems, and financial institutions acting as market makers. Uni swap, sushi swap, curve, and balancer are a few examples. The goal is to eliminate the input of third parties so that users can execute trades directly from their personal wallets. Hence, the majority of the processes are executed and governed by smart contracts. In other words, AMM enables traders to interact with smart contracts to enable liquidity and discover prices.

How do AMMs work?

Keep in mind that AMMs use preset mathematical formulas to determine and maintain the prices of paired cryptocurrencies. Also note that AMMs allow anyone to provide liquidity for paired assets. To elaborate, the protocol allows anyone to become a liquidity provider, or LP. Take the uni swap as a case study. The protocol uses the popular x * y = K equation. where x denotes the value of asset A, y represents that of asset B, and "K" is a constant value. Hence, regardless of changes in the value of asset A or B, their product must always be equal to constant K. It is important to remember that the equation used as an example is only one of the existing formulas used to balance AMMs.

They require liquidity to function properly and negate slippages. These protocols incentivize liquidity providers by offering them a share of the commission generated by liquidity pools and governance tokens. In other words, you get to receive transaction fees when you provide capital for running liquidity pools; once you stake your fund, you will receive liquidity provider tokens that denote your share of the liquidity deposited in a pool. These tokens also make you eligible to receive transaction fees as passive income. Tokens can be deposited on other protocols that accept them for higher yield farming opportunities, and to withdraw your liquidity from the pool, you would have to turn in your LP tokens. If we want to trade BAT for the Graph token, the liquidity pool is extremely useful. Well, most decentralized exchanges will hook up two liquidity pools together to allow us to perform that trade directly. First, it will swap BAT for ETH and then ETH for the Graph token. Essentially, BAT is being exchanged for the Graph token. This is known as Routing. DEX will route some trades for us, and we can trade any token on their platform. As more and more people start to trade, the fees go to the liquidity provider.

Let's say you're a banana farmer. You're tired of only eating bananas. You live in a village of banana farmers, so you can't trade with them. Along comes a trader who says that he found an island where people grow an orange and want to trade it for any other fruit, and he's here to see if you're interested in a trade. Well, the orange farmers had put up 50,000 oranges to add to the banana-orange exchange business. If you give the trader 50,000 bananas, the business will start. Because both farmers had planted 50,000 bananas and oranges, the trader expects both of these figures to be constant, i.e., 2.5 billion in our scenario, which is 50,000 * 50,000. If one year there are fewer oranges, it'll cost more to buy them. The trader says, "Right now, I've got a 1:1 ratio of bananas to oranges." "When you start trading, one may become more valuable, and thus it should be priced higher than another."

Here the liquidity pool has 50,000 bananas and oranges, and the product of these is equal to 2.5 billion. So let's say a banana farmer comes along with 7,000 bananas to trade. He gives them to the smart contract, and the contract has 57,000 bananas. We need to know how many oranges to give to the banana farmer. We take 2.5 billion and divide by 57,000, which is 43859. This is the number of oranges that should be left over in the smart contract. However, right now there are 50,000. So we find out the difference and give it to the banana farmer, which is 6140. As more and more oranges are bought, they become more expensive. This is why the banana farmer didn't get exactly 7000 oranges back, and 57,000 * 43,859 does equal to 2.5 billion.

impermanent loss

Although AMMs provide significant returns to LPs, there's risk involved. The most common is impermanent loss. This phenomenon arises when the price ratio of assets and liquidity pools changes. LPs who have deposited funds in affected pools will automatically incur an impermanent loss. The greater the shift in the price ratio, the greater the loss.

Let's say you put up 100 Ethereum and $10,000 into a liquidity pool. Most liquidity pools want a 50:50 ratio whenever you initially start your deposit. So we can reasonably assume the price of one Ethereum at this point is $100. Here we've got $10,000 worth of stable coins and $10,000 worth of Ethereum that you're putting in a liquidity pool, hoping to gain a profit on some of the fees that will happen within the pool.

Let's say the price of Ethereum rises to $110. A trader can come along and realize that he can buy Ethereum at your liquidity pool for $100 and then sell it to Coinbase for $110. So he keeps buying more and more, and the algorithm will keep charging him more and more until he stops making money. That's how these DEXs work. It created an arbitrage opportunity for a trader. We estimated that he could give $488 and buy 4.652 ETH until the liquidity pool price reached $110. If he bought any more Ethereum, he would be losing money. He immediately sold cheaper Ethereum to Coinbase for $511.82, which means he made a profit of $23.82 simply by buying and selling between two different liquidity pools.

Now let's take the position of being that liquidity provider. This means that there's now $10,488 worth of stablecoin in the pool and 95.347 ETH in the pool. So if we take 95.347 and multiply it by $110 because that's the going price of Ethereum, we get $10,488. If we take $10,488 of our stablecoin and $10,488 of Ethereum and add them together, we get a total value of $20,976. So the liquidity provider now has a total value of $20,976, meaning he made $976 because Ethereum went up.

However, to calculate impermanent loss, we need to calculate how much money he would have had if he didn't invest in the liquidity pool and just held his stablecoin and Ethereum in his wallet instead. So obviously he would still have his $10,000, but what about the Ethereum? Well, now that 100 Ethereum would be worth $11,000 (110 * 1000), he would have a total of $21,000 if he just held it. This means we can calculate his impermanent loss to be $21,000 minus $20,976, which is $24. So, in short, this liquidity provider would have made more money if he just held on to his Ethereum and stablecoin. If Ethereum goes back to $100, the impermanent loss is cancelled, and there's no impermanent loss because both assets would be the same as when the liquidity provider initially invested them. They call it an impermanent loss because it only becomes permanent when you cash out your liquidity. Until you do that, there's still an opportunity for the loss to normalize itself.

It gets really tricky when both assets' prices start moving. In short, if they go in opposite directions, the liquidity provider starts to lose money very quickly. However, if they increase at the same rate or decrease at the same rate, the liquidity provider may not lose money due to impermanent loss at all, and they may just reap the rewards of the profits from the trading fees.

However, there is a reason why this loss is referred to as an impermanent. As long as you do not withdraw deposited tokens while the pool is experiencing a price ratio shift, it is still possible to mitigate the loss. The loss disappears when the prices of the tokens revert to the original value at which they were deposited, and those who withdraw funds before the prices revert suffer permanent losses. Regardless, it is possible for the income received via transaction fees to cover such losses.

Rug Pull

A rugpull is a malicious maneuver in the cryptocurrency industry where crypto developers abandon projects and run away with investors' funds, otherwise known as a scam coin. Rug pulls most often happen in the DEFI ecosystem, especially on DEXs, where malicious individuals create a token and list it on DEX, then pair the scam coin with a leading cryptocurrency like Ethereum. When a large number of unsuspecting investors exchange their ETH for their listed token, the creators withdraw everything from the liquidity pool, causing the coin price to fall to zero.

Rug pulls can happen during or after an ICO (initial coin offering). Scam coin promoters may even use social media to create a temporary buzz around it in order to gain attention. They may also initially inject a substantial amount of liquidity into their pool to cultivate investor confidence. Another major characteristic of a possible rug pull is a coin that skyrockets in price within hours. For example, a rug-pull coin can move from 0 to 50 times within 24 hours. This trick is meant to drive the FOMO (fear of missing out) that leads to more people investing in the token.

Rug pull thrives on DEXs because, unlike centralized cryptocurrency exchanges, DEXs allow users to list tokens free of charge and without audit. Furthermore, creating tokens on open-source blockchain protocols like Ethereum is easy and free. Make sure to research more about the coin and look for telltale signs of rugpulls like a low liquidity pool, low team credibility, or unknown founders, short lock-in periods, extreme rewards, few wallet holders, ambiguous and unclear white papers, and large promotional spending and marketing.