Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learn Ethereum

You're reading from   Learn Ethereum A practical guide to help developers set up and run decentralized applications with Ethereum 2.0

Arrow left icon
Product type Paperback
Published in Aug 2023
Publisher Packt
ISBN-13 9781804616512
Length 814 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Authors (3):
Arrow left icon
Dongying Song Dongying Song
Author Profile Icon Dongying Song
Dongying Song
Zhihong Zou Zhihong Zou
Author Profile Icon Zhihong Zou
Zhihong Zou
Xun (Brian) Wu Xun (Brian) Wu
Author Profile Icon Xun (Brian) Wu
Xun (Brian) Wu
Arrow right icon
View More author details
Toc

Table of Contents (24) Chapters Close

Preface 1. Part 1: Blockchain and Ethereum Basics
2. Chapter 1: Blockchain and Cryptocurrency FREE CHAPTER 3. Chapter 2: Ethereum Architecture and Ecosystem 4. Chapter 3: Decentralized Finance 5. Chapter 4: EVM-Compatible Blockchain Networks 6. Chapter 5: Deep Research and the Latest Developments in Ethereum 7. Part 2:Ethereum Development Fundamentals
8. Chapter 6: Fundamentals of Solidity 9. Chapter 7: Web3 API Fundamentals 10. Chapter 8: Developing Your Own Cryptocurrency 11. Part 3: Ethereum Development Fundamentals
12. Chapter 9: Smart Contract Development and Test Fundamentals 13. Chapter 10: Writing a Frontend to Build the NFT Marketplace DApp 14. Chapter 11: Ethereum Tools and Frameworks 15. Part 4:Production and Deployment
16. Chapter 12: Setting Up Ethereum Private Chain 17. Chapter 13: Deployment of Your DApps 18. Chapter 14: Building Ethereum Wallets 19. Chapter 15: Oracles, Technology, and Layer 2 in Practice 20. Part 5:Conclusion
21. Chapter 16: Conclusion 22. Index 23. Other Books You May Enjoy

Understanding DeFi protocols

In this section, we will help you understand popular DeFi constructs and concepts and show you how different DeFi applications work, including decentralized lending and borrowing, exchange, derivative, and insurance. We will also dive deep into leading DeFi protocols in those categories.

Basic DeFi constructs

Let’s start by looking at the key DeFi building blocks and basic constructs:

  • Liquidity pool: Liquidity and liquidity pools play a critical role in the DeFi ecosystem. Liquidity, in the form of crypto assets, is the lifeline of any liquidity-based DeFi application. It is used to bootstrap, govern, and secure the DeFi protocol. It is used to facilitate the trading of crypto assets through the protocol rules. A liquidity pool is a mechanism where liquidity is locked into the smart contract; the process of locking liquidity is also called staking. The liquidity provider may get the governance token – that is, LP tokens – as proof of staking.

In the MakerDao Dai section, we showed you how liquidity and liquidity pools are used in MakerDao Dai, the popular stablecoin protocol. The governance token, MKR, is the LP token. A liquidity pool can lock one or multiple types of crypto coins. In MakerDao, it locks one type of crypto coin at once. In a DEX such as Uniswap, which we will discuss in the next few sections, the pool locks the pair of crypto coins to facilitate the exchange of one coin for another.

In return for their staking, the liquidity providers accrue interest in the form of governance tokens or some interest-bearing tokens. This type of process, in which tokens are staked for maximum returns, is a type of yield farming and is the most popular type. We will discuss yield farming later in this section.

  • Exchange: In traditional finance, an exchange is a marketplace where financial instruments such as stocks, commodities, futures, and derivatives are traded. The exchange of crypto assets is supported through DEX, where the crypto asset holder of one type of coin can trade their holdings in exchange for another type of crypto coin.

In traditional finance, such trades happened through the use of an order book, or via the market maker. An order book records the bid and asking price movements that reflect the interest of buyers and sellers in a particular financial instrument. A matching engine uses the order book to determine which orders can be fully or partially executed. A market maker is an entity that provides its liquidity for quoting both the buying and selling the assets in a trade, hoping to make a profit on the bid-ask spread.

In the DeFi world, on-chain order book matching is too costly, since the bids and asks, as well as the crypto price movement, have to be actively maintained on the blockchain network. Automated Market Maker (AMM) was introduced to allow people to match and swap two types of crypto coins. We will discuss the DeFi exchange and AMM in more detail in the following subsections.

  • Flash loan: We briefly mentioned flash loans when we discussed the technical architecture of MakerDao Dai. A flash loan is a common concept that’s implemented in many DeFi protocols. It is a type of uncollateralized loan that can be lent instantly without any collaterals, so long as the loans are repaid in the same blockchain transaction.
  • Oracle: We briefly introduced Oracle as a component of MakerDao Dai that collects pricing information about collateralized crypto assets. Oracle is a common concept in all DeFi protocols, as well as broad blockchain ecosystems. It is a mechanism that a blockchain uses to integrate with external systems. For example, a sports betting DApp may need weather information to determine how the bets are played out. In such cases, the DApp may have to rely on Oracle to retrieve the weather information to aid with betting. In DeFi, Oracles are commonly utilized to share and integrate the price movement of different types of crypto assets, as MakerDao Dai did.
  • Bridge: In addition to integrating with external systems, sometimes, a blockchain needs to communicate and gain visibility of transactions with other blockchains or L2 protocols. That is where Bridge comes into play. We mentioned Bridge when we discussed L2 rollups in Chapter 2, Ethereum Architecture and Ecosystem. There, we stated that it is a common design pattern for enabling the integration of token exchanges between the L1 and L2 networks. Bridge is another critical component in DeFi and blockchain that has been implemented in almost all DeFi protocols. Bridge acts as a smart contract component on both sides of a network to facilitate the communication and exchange of information between blockchains.
  • Tokenization: So far, we have mostly discussed native tokens and coins supported by blockchain and decentralized networks. In DeFi, tokenization is the process of designing fungible or NFTs representing the underlying physical or digital assets. For example, the real estate properties you own can be tokenized in the form of fungible tokens and put on a blockchain for buying or selling. If your property has any unique traits, you can tokenize them into NFTs and put them on the blockchain network as NFTs. Tokenization brought new liquidities to DeFi and made it possible to connect the real world to the crypto world.
  • Composability: Composability in DeFi refers to the ability to quickly integrate and aggregate different DeFi constructs and smart contracts, as well as create new DeFi products. As we saw in Figure 3.2, smart contracts are the real magic behind all these DeFi products and constructs. In a smart contract, composability enables one smart contract to utilize the features and behaviors of another smart contract via inheritance or composition. So long as they implement the same smart contract interface, new smart contracts can be Plug and Play, and make a new DeFi protocol by replacing some portion of the older protocol.

As you can see, once enabled by smart contracts, all these DeFi constructs are like the Lego blocks of the DeFi ecosystems. They empower DeFi’s innovation and make it possible to create new and innovative DeFi products. We will show you how different DeFi protocols work in the following subsections.

Lending and borrowing

Traditional lending and borrowing are normal financial activities we do all the time in our daily lives. When you purchase a house, instead of paying cash in full, which not many people can afford, you normally put down 20% of the purchase price as the down payment and get a mortgage to pay the remaining 80%. In return, the leader who lent you the money gets interest for a certain period – that is, until the loan has matured. The mortgage rate is determined by multiple factors, including your financial situation and credit score. Credit scores are personalized numbers that represent the creditworthiness of an individual. In the US, they normally come from agencies such as Equifax, Experian, and TransUnion.

DeFi lending and borrowing of crypto assets are very popular in the crypto world and the DeFi community. Similar concepts in traditional finance have been ported or implemented in the DeFi protocol but with one caveat: there is no central authority for crypto credit rating. Even if you can Oraclize real-world credit scores into the DeFi world, it will be very difficult to check someone’s creditworthiness due to the lack of know-your-customer (KYC), which is enforced by laws in the traditional finance world.

How does DeFi lending and borrowing work?

MakerDao Dai is a popular DeFi crypto lending platform that allows a borrower to borrow DAI tokens. As we discussed in the MakerDao Dai section, Dai is a stablecoin whose value is pegged to US dollars. Anyone can open a Maker vault, lock in Ether or Maker-accepted coins as collaterals, and generate Dais as a loan against those collaterals. The borrower can use the Dais for any other crypto transactions, or simply create a Dai saving account and earn interest.

In the absence of a credit score entity, or without knowing your customers, the MakerDao protocol has to resort to oversized collaterals as a risk control mechanism to protect the protocols from being liquidated by Maker vaults. This is how most DeFi lending and borrowing protocols work.

As shown in the following diagram, the protocol maintains a liquidity pool where the lenders can stake their crypto assets and, in turn, get LP tokens and earn interest until they close the stake and withdraw the funds. In the DeFi lending/borrowing protocol, protocol governance is enacted to govern the normal operations of the protocol. Its role in the DeFi protocol is to serve as a mechanism for making crucial decisions about protocol changes or even protocol governance framework changes. Protocol governance can be centralized, decentralized, or hybrid. In the case of decentralized governance, protocol governance is codified as smart contracts and made transparent on the blockchain:

Figure 3.11 – DeFi lending and borrowing

Figure 3.11 – DeFi lending and borrowing

Similar to the MarkerDao Dai protocol, the borrower can lock their crypto assets as collateral and obtain a crypto loan. Like MakerDao, the DeFi lending and borrowing protocol typically requires an over-collateralized position to get the loan to protect itself. Let’s say you have 300 Ether in your wallet. Instead of letting the 300 Ether sit idle and earn nothing, you can lock those 300 Ether into the DeFi lending and borrowing protocol and get a value of 200 Ether for a crypto loan. In DeFi, anyone can be a lender. You can turn around and lend them out and earn interest. The interest you earn could fluctuate every minute. The interest rates of underlying crypto assets vary protocol by protocol and change over time. The complexity and abundance of choices in earning interest made yield aggregation possible, which is the algorithmic process of maximizing the interests for a given crypto position. We will discuss yield aggregators in more detail in the upcoming subsection.

Like MakerDao Dai, liquidation in DeFi lending and borrowing is the process of liquidating crypto assets that are locked as collateral and selling them at a discount to close the loan. Crypto prices are very volatile. The collateralization ratio – that is, the collateral over the loan amount – fluctuates all the time and indicates the health of the borrower’s position. The DeFi protocol maintains a collateralization ratio threshold – that is, the minimal collateralization ratio the borrower can continue to use to hold their crypto loan position without liquidation. This threshold is normally defined by the governance protocol. It varies protocol by protocol. When any account’s collateralization ratio falls below this threshold, the protocol enacts the liquidation process and auctions the collaterals in the market to recover the potential loss from the protocol. Oracle is the component that feeds the protocol with the near real-time pricing information of all crypto assets. Different protocols may determine the crypto prices differently, depending on the protocol’s design.

Aside from MakerDao Dai, Aave and Compound are other popular DeFi lending and borrowing platforms. We will discuss the Aave protocol in the following subsection, as well as highlight the key differences between Aave and Compound.

Diving deep into Aave

Since it launched in 2020, Aave has become one of the most popular decentralized lending and borrowing protocols in the DeFi ecosystem. It is an open source smart contract platform that was built using Solidity, a popular smart contract language.

As a non-custodial liquidity protocol, it allows lenders to deposit crypto assets into a protocol and earn interest without transferring ownership of the tokens. The borrower can earn interest on their borrowed assets.

As shown in the following screenshot, the lender can deposit the interest-bearing tokens as a form of liquid into the Aave lending pool. In return, they will receive an equivalent amount of cTokens. For example, if you deposit 300 Ether into the Aave lending pool, Aave will lock 300 Ether into the lending pool and mint 300 cETH. In the same way, if you deposit 30,000 Dais into the Aave lending pool, the Aave protocol will lock 30,000 Dais into the pool and mint 30,000 cDais for you. The interest rates on cTokens are determined by the protocol. In Aave, the interest rates are algorithmically adjusted based on supply and demand. Interest is accrued in cTokens too. As the lender exits the system, they can simply return cTokens, including the original stakes and all accrued interests, and exchange the target tokens back to you:

Figure 3.12 – High-level technical view of the Aave protocol

Figure 3.12 – High-level technical view of the Aave protocol

The borrower has the option to get a stable rate loan or variable rate loan for the collateralized crypto assets. In Aave, if you choose a stable rate loan, the protocol will mint the same amounts of sTokens and issue them to you. Similarly, if you want a variable rate loan, you will get vTokens back. Stable rate loans and variable rate loans are like fixed-rate mortgages or adjustable-rate mortgages (ARMs) in traditional finance. In Aave, stable rates act as fixed rates in the short term but can be readjusted in the long term in response to the supply and demand in the market. Variable rates can always be adjusted based on the current market conditions.

As we introduced earlier, a flash loan is a special loan transaction that doesn’t require collateral for borrowing, so long as the loan, together with the fee, is paid within the same transaction. Flash loans are not directly supported in the Aave protocol. Instead, the protocol gives developers two options to build smart contracts to simulate the flash loan on Aave. One is done through theflashLoan operation, while the other is done through the flashLoanSimple operation. The former allows the borrower to access the liquidity in multiple reserves. The latter only allows the borrower to access a single reserve for flash loan transactions.

Portal was added in Aave v3 to support easy integration with other L1 or L2 networks. The role of Portal in Aave is to facilitate the circulation of liquidity among Aave v3 markets across various blockchain networks. In the latest version of the protocol, Aave v3, you can use bi-directional, governance-approved bridges to move assets from one network to another. Typically, that involves burning a Tokens on the source network while instantly minting them on the destination network. The underlying assets can then be staked to the Aave lending pool after it has been moved through a bridge. Not everyone can perform this asset movement over a bridge. A new system role, BRIDGE, was provided in V3. Only an address with such a role has permission to move the supplied liquidity through the bridge.

To access the price from external systems or other networks, Aave v3 leverages Chainlink, a decentralized Oracle network, as an Oracle proxy to supply the price and data required by the Aave protocol.

To secure the protocol, Aave v3 has a sophisticated governance model that incentivizes the AAVE holder to lock AAVE tokens into a Safety Module (SM) smart contract. Once locked, they are used by the protocol as a mitigation tool to cover the deficits in case some shortfall events occur. If you’re interested, you can learn more at https://docs.aave.com/aavenomics/governance#protocol-governance.

To conclude this section, let’s take a look at how Compound works.

A brief overview of Compound

Similar to Aave, Compound is another popular algorithmic and autonomous DeFi lending and borrowing platform. Compound offers its governance token, called COMP, to represent the voting rights over protocol and governance decisions. This includes the decision to incorporate new assets, protocol upgrades, or technical upgrades on the platform.

Similarly, it converts any crypto assets into Compound’s native tokens, cTokens, which are then used to track positions (supplied assets) in Compound. If you deposit 300 Ether into Compound, it will issue the same amount of cETH as the claims of your asset in the liquidity pool in Compound. Likewise, if you deposit 30,000 Dais to Compound, you will be issued 30,000 cDais. Similar to Aave, different cTokens can earn you different interest rates, and those interest rates are determined by the Compound protocol.

Just like any other DeFi protocol, a liquidation mechanism was designed to protect the borrower and the protocol from further detriments to the system. In Compound v3, the system defines the liquidation collateral factors and borrow collateral factors. Borrow collateral factors are used to determine the initial borrow capacity, while liquidation collateral factors are used to trigger the liquidation process. Liquidation collateral factors are always higher than the borrow collateral factors so that a price buffer is left to prevent unnecessary liquidation.

Liquidation is triggered when any account’s borrowing exceeds the limits set by liquidation collateral factors. When that happens, the protocol absorbs the debt of those underwater accounts. It takes over the collateral assets from those accounts and uses the cash reserve of the protocol to repay the debt.

The protocol sets the target amount of reserves of the base token to protect the protocol from the risk of insolvency. If the protocol holds less than the target reserves, the protocol allows the liquidators to buy the collaterals at a discount. If you’re interested in learning more, you can find more details about the Compound protocol at https://docs.compound.finance/liquidation/.

Decentralized exchanges

Earlier, we introduced the concept of exchange, where you can swap and trade one financial instrument with another. Crypto assets can be traded at centralized exchanges such as Coinbase, Binance, and DEX. In a centralized exchange, trades are typically normalized with the fiat currency. Let’s say you want to exchange your BTC with ETH – you will sell your BTC in exchange for a fiat currency, such as the US dollar, and then use the fiat currency to buy ETH.

DEX is a decentralized marketplace for trading crypto coins, tokens, and crypto products in a non-custodial manner. Typically, transactions are made directly between two traders without any intermediary or having to convert into fiat currency.

The leading DEX protocols include Uniswap and Curve. In the next section, we will discuss how DEX works and help you learn the mechanics of AMM. Then, we will dive deep into Uniswap, the leading DEX protocol. We will conclude this section with a brief overview of the DEX aggregator, a new type of DeFi service that’s become more popular lately. By the end of this section, you will have a good understanding of DEX and how leading protocols implement it.

How does DEX work?

In a traditional finance or centralized exchange, the exchange resorts to the order book to match the orders and facilitate the trade of one financial instrument for another. As we discussed earlier, the order book approach requires you to keep track of the bid and ask of all orders and match your bid with someone’s ask. This approach became costly in the DeFi world.

Another common approach in traditional finance is to use the market maker, who mediates the trades between traders. This becomes impractical in the DeFi ecosystem since, in the decentralized network, there won’t be any centralized intermediary to mediate the trades. This gives rise to the AMM concept in DeFi.

The following diagram shows the key concepts and mechanisms of a DEX protocol. Like any other DeFi product, DEX maintains a large pool of liquidities in the liquidity pool. Any liquid providers who want to generate yields from their crypto assets can stake their crypto assets into the liquidity pool. DEX leverages the liquidity pool to make the market and match the orders according to some deterministic algorithms. Similar to all other DeFi products, protocol governance is done through a decentralized protocol. In this case, Oracle was leveraged to bring the external pricing data into the DEX protocol. Some may use a decentralized Oracle network, such as Chainlink, to bring the pricing feed on-chain. Uniswap, instead of relying on a third-party Oracle feed, chose to build an Oracle with historical observations on-chain. We will discuss this when we unpack the Uniswap protocol in the subsequent sections:

Figure 3.13 – DEX

Figure 3.13 – DEX

AMM is the cornerstone of many popular DEX protocols on the market. It was initially proposed by Vitalik, the co-founder of Ethereum, as an idea in his Reddit post, which later became popularized following the successful implementation of constant products in Uniswap. AMM allows crypto assets to be traded in a permissionless and automatic way by matching the price determined by the supply and demand of liquidity pools within the protocol.

In the next subsection, we’ll cover the constant product AMM strategy and help you understand how the protocol determines the exchange rate between two types of crypto assets.

Understanding the mechanics of AMM

AMM is a novice market-making concept that originated from Ethereum. Typically, it comprises a set of smart contracts designed to facilitate the determine the pricing of underlying crypto assets based on the amounts of cryptocurrencies in the liquidity pool. The most popular is the constant product algorithm.

The constant product algorithm is based on the hypothesis that, when you exchange one token with another in a large pool, the product of two quantities of respective tokens may stay constant. Vitalik initially theorized this as X * Y = K (as a constant).

As seen in the following screenshot, we have a pool size of 1,000, which initially has 20 X coins and 50 Y coins. If a trader wants to buy 40 Y, this means that after the trade, the pool will have 10 Y left. Using the constant product formula, after the trade, the pool should have 100 X coins to make the pool size stay constant at 1,000. This means the trader has to put 80 X coins into the pool in exchange for 40 Y coins being taken out of the pool:

Figure 3.14 – Constant product AMM strategy

Figure 3.14 – Constant product AMM strategy

Let’s use some real-world crypto exchange examples to help you understand how AMM helps with market making. In current market conditions (October 2022), 1 ETH is priced at around 1,300 US dollars. Let’s say we set up a balanced ETH-DAI liquidity pool with an initial staked fund of 1.3 million in ETH (or 1,000 Ether) and 1.3 billion in DAI (or 1.3 million Dais). The constant product of ETH and Dais in the pool is exactly 1.3 billion.

If a trader opens a swap position to exchange 10 Ether in their wallet for some Dais, how will the AMM smart contract determine how many Dais the trader would receive? To exchange 10 Ether for Dais, they must add 10 Ether to the liquidity pool, which would end up containing 1,010 Ether if the trade goes through. According to the constant product formula, the liquidity pool should have the following Dais:

 1300000000 _ 1010  = 1,287,129 Dais

Upon deducting this from the total number of Dais before the trade, the trade would exchange 10 Ether for 12,871 Dais.

AMM is simple to implement. The downside is that it may create a price slippage for underlying assets, where the expected price of the exchange may be different than what AMM quoted. Another issue is it may incur an impermanent loss, where the liquidity provider may see their staked assets priced lower than the markets’ due to price fluctuation in the AMM market.

Unpacking the Uniswap protocol

Ever since Uniswap was launched and deployed on the Ethereum blockchain in November 2018, it has become one of the most popular decentralized exchange platforms. As we mentioned earlier, the initial idea of the constant product AMM strategy came from Vitalik, but the Uniswap team turned the hypothesis of AMM into a reality.

The following screenshot illustrates the earlier implementation of Uniswap. In the Uniswap v1 implementation, the liquidity providers deposit their pairs of crypto assets into the Uniswap liquidity pool, where the protocol will build all possible pairs of pools the platform allows. When a trader wants to exchange a number of A coins with B coins, it simply asks the protocol to swap two coins based on the price determined by the AMM, a smart contract that implements the constant product algorithm:

Figure 3.15 – Uniswap v1 protocol

Figure 3.15 – Uniswap v1 protocol

As we explained in the previous section, the new price will ensure the pair’s liquidity pool stays compliant with the constant product principle once the swap has been made. The trader pays a fee for this swap, which will be accrued and subsequently redistributed to the liquidity providers for their stake in the liquidity pool. The process of incentivizing the liquidity provider in this passive way is also called yield farming, which we will discuss at the end of this section.

Since its initial implementation, Uniswap has gone through multiple upgrades. v2 and v3 of the Uniswap protocol have added a lot of new capabilities to improve the price stability for the system, as well as capital efficiency for liquidity providers. The following diagram illustrates the Uniswap V3 architecture:

Figure 3.16 – Uniswap v2/v3 protocol

Figure 3.16 – Uniswap v2/v3 protocol

Although the basic mechanics didn’t change, a lot of new capabilities were added to the protocol. Here are some notable features:

  • Liquidity pool: In Uniswap v1 and v2, only a single pool can be initialized per pair, and each pool has a standard fee at a rate of 0.30%. It is simple to implement but also creates limitations in terms of the capital efficiency of the liquidity providers. A standard rate of 0.30% may be too high for stable assets such as stablecoins but could be too little for volatile assets. To address this capital efficiency issue, in v3, the protocol allows multiple pools to be created per pair, and each pool can have differentiated fee rates.
  • Concentrated liquidity: Introduced in Uniswap v3, concentrated liquidity allows the liquidity provider to specify a price range for the staked liquidity in the liquidity pool. This exchange can only be executed if the price falls within a certain price range. This makes sense since most crypto tokens are priced in a certain range. In earlier versions of Uniswap, the price range can be from zero to infinite due to the constant product formula. All staked positions earn yield uniformly, proportionally to the ownership percentage of the liquidity pool. In v3, with concentrated liquidity, the liquidity provider can open liquidity positions at different price points and with different liquidities. To support such customized staking positions, behind the scenes, Uniswap v3 leverages NFTs to manage the concentrated liquidity positions; swap fees are continuously collected and accrued.
  • Flexible fee: Instead of a fixed fee collected from every trade, v3 introduced a flexible fee structure. v3 allows multiple pools per asset pair; the fee tier for each pool can be set during the initialization of the liquidity pool. The fee tiers include 0.05%, 0.30%, and 1%.
  • Oracle: In its initial version, Uniswap doesn’t rely on the external price Oracle or historical prices on the liquidity pool to determine the price. Instead, it purely follows the constant product formula. In v2, it introduced the Time Weighted Average Price (TWAP) Oracle for building historical price observations on a chain. Historical data is stored as an array of observations. At each block, each pool tracks only the current observation. As the blocks progress, the observations are overwritten. It is the user’s or aggregator’s responsibility to aggregate such observations of the previous blocks. In v3, it accumulates such observations for the last 9 days. Any protocol that wants to quote the price before making the trade can leverage Oracle to get the historical observations.
  • Flash swap: Flash swaps were first implemented in v2. They allow the trade to go through without enforcing that enough input tokens have been received. Without a flash swap, the transaction will be rolled back on the Ethereum network if the input tokens don’t cover the underlying assets, as well as the fee. With a flash swap, such transactions can be executed and the remaining gaps can be sent as part of callback functions.

As with all DeFi protocols, Uniswap has a unique governance model that protects the platform. If you’re interested in learning more, check out https://docs.uniswap.org/protocol/introduction.

A glance at DEX aggregators

Before we wrap up our discussion on DEX, let’s briefly go over various exchanges on the market and understand the role of a DEX aggregator.

At this point, you should have a good understanding of decentralized exchanges and how Uniswap, the leading DEX protocol, works. In addition to Uniswap, there is quite a long list of DEXs on the market. We encourage you to check out listing sites such as CoinMarketCap (https://coinmarketcap.com/rankings/exchanges/dex/) for the top DEX protocols.

With the abundance of DEX protocols, there are a lot of options for traders to exchange and swap their crypto assets. DEX relies on liquidity pools to maintain the stability of pricing. Some DEXs may not have enough liquidity to be stable. These exchange rates vary from DEX to DEX. How you can generate a maximum return for the liquidity providers or get the best exchange rates for your assets becomes a challenge.

That is what DEX aggregators try to address. 1inch initiated such a concept and became the leading DEX aggregator. Typically, a DEX aggregator is built on top of existing DEX protocols, leveraging the composability of smart contracts. It provides a single entry point or dashboard for the traders to view all available DEX markets; price Oracles such as the Uniswap v3 TWAP Oracle advise the traders on the best trading strategy to handle slippages or impermanent loops, and maximize their yields.

Decentralized derivatives and insurance

Similar to traditional finance, derivatives are popular crypto financial products and services in the DeFi ecosystem too. Over the last few years, many DeFi derivative products, including futures, options, and swaps, were made available on decentralized exchanges. Leading DeFi derivative protocols, including Synthetix, UMA, dYdX, and others, started emerging. At the same time, decentralized insurance products, especially those that protect DeFi investments and smart contracts, were gaining traction. In the following subsection, we will provide a brief overview of decentralized derivatives and insurance in DeFi and go over some of the leading DeFi derivative and insurance protocols.

Overview of derivatives and insurance in DeFi

In financial terms, derivatives are the financial instruments that derive the values from the future pricing movement of underlying investment assets. The same applies to crypto derivatives. A decentralized derivative is a contract between two parties that generates profits from the performance of underlying crypto assets. When the contract’s conditions are met, the contract is executed through smart contracts on the blockchain. Popular DeFi derivatives include futures, options, and perpetuals. Let’s take a brief look at them:

  • Futures: Similar to futures in traditional finance, a crypto futures contract is an agreement between two parties involved in obliging to buy and sell certain crypto assets at a predefined price and date. For example, if you think that ETH will increase in price following the merge, you may want to open a long position on the Ether by buying an Ether futures contract with a monthly expiry date. If you felt the merge might introduce uncertainty and the price may drop, you may want to open a short position on the Ether future contract.
  • Options: In the same way, crypto options are available through DeFi options contracts. They are quite similar to crypto futures contracts; however, options contracts don’t mandate buying or selling the underlying crypto asset – they simply give the contract holder the option to execute the buy or sell order. It is normally a way to hedge on the price movement of underlying crypto assets in case the underlying price moves against you.
  • Perpetuals: A perpetual contract is a crypto futures contract that never expires. Similar to crypto futures, a perpetual contract allows the contract holder to buy or sell the underlying crypto asset at a pre-agreed price anytime in the future.

Insurance is a written contract in which the insurer indemnifies the policyholder against the financial losses from certain risks or perils. Insurance is all about risk and uncertainty, while risk is the probability that something bad could happen and it will cause financial losses when it happens. Traditionally, this involves a central entity, the insurer, who prices the risks and offers the insurance products for anyone to buy and get protection against such risks. In return, the insurer collects the premiums from the policyholders, and when something bad happens, they pay the insured person in the form of a claim.

In DeFi, a similar risk and insurance concept has been implemented in decentralized insurance protocols that allows peer-to-peer provisioning of insurance protection without a central entity. Leveraging blockchain and decentralized networks to replace traditional insurance is still relatively new, but insurance and protection from DeFi protocol risks have taken shape thanks to some of the leading decentralized insurance protocols on the market, such as Nexus Mutual.

In the next few subsections, we will introduce you to the leading DeFi protocols, dYdX and Nexus Mutual.

Understanding dYdX

In mathematical terms,  dy _ dx represents the first-order derivative of a function, y = f(x), as shown here:

 dy _ dx  = lim h0  f(x + h) f(x) _ h 

As its name suggests, dYdX is the DeFi protocol that has pioneered decentralized derivatives, including perpetuals, margin and spot trading, and lending and borrowing. It was originally built on the Ethereum L1 network, but in 2020, it moved to StarkNet, the L2 ZK rollup platform on Ethereum. All dYdX trades are settled in StarkNet, which, in turn, publishes ZK proofs periodically to Ethereum to ensure transaction security. Funds must be deposited to the Ethereum smart contract before they can be used to trade on dYdX. We mentioned StarkWare and its implementation of ZK rollups, StarkNet, in Chapter 2, Ethereum Architecture and Ecosystem.

As shown in the following screenshot, dYdX is a decentralized exchange for futures, options, and perpetuals. The key difference between dYdX and other DEXs is their margin and leverage. In dYdX, a margin allows the trader to buy derivatives with borrowed money, in the form of crypto assets, while the leverage is the collateral that protects the protocol from its pricing falling:

Figure 3.17 – dYdX protocol overview

Figure 3.17 – dYdX protocol overview

The trader needs to send crypto assets as collateral to open a margin account. Internally, collateral is held as USDC, and the quote asset for all perpetual markets is USDC. The trader can open multiple positions within the same account, but all positions will share the same collateral. The dYdX protocol defines three types of risk parameters per crypto type: the initial margin fraction, maintenance margin fraction, and incremental initial margin fraction. Maximum leverages are determined based on these risk parameters. The protocol then uses these leverages to determine the value that must be held by an account when opening a position, increasing positions, or avoiding liquidation of the account and positions.

Another key difference is that dYdX uses an off-chain order book to maintain the open positions and leverages an off-chain matching mechanism to match the orders, instead of using AMM on-chaining for order matching. All transactions are then posted on-chain for security and settlement once the orders are matched. The market maker can use dYdX too, just like the market maker in traditional finance. They do arbitrage trading when opportunities present themselves.

Liquidation may be triggered during the extreme market, where the high volatility of underlying assets may cause the account value to drop below zero before it can be liquidated. The protocol defines an insurance fund to protect the system from insolvency. When account liquidation is triggered, the insurance fund will absorb the loss. If the insurance fund is exhausted, the protocol will use profitable positions to offset underwater accounts to maintain the stability of the entire system.

dYdX plans to move the order book and matching on-chain in the future. Instead of staying on Ethereum, they plan to build out an L1 blockchain on Cosmos and leverage the validators in the decentralized network to manage the order book and match the orders. They foresee that this approach will enable the protocol to handle tens to thousands of transactions per second and at the same time, take advantage of an order book and stay decentralized.

Understanding the risks in the context of insurance

Although jurisdiction and local rules may differ, generally, insurance deals with the risks of unexpected events. The basic formula for insurance is that the fund that’s collected from the premiums paid by those who are insured can cover the cost of any incurred losses.

The following screenshot shows a high-level conceptual business model for insurance:

Figure 3.18 – Conceptual insurance business model

Figure 3.18 – Conceptual insurance business model

As we mentioned earlier in the Overview of derivatives and insurance in DeFi section, insurance is all about the risks and the probability of something bad happening. Risk and insurance always work in tandem. Without risks, there is no need for insurance. The probability is driven by risk factors and therefore could be different from person to person. The insurer will need to price the risks and come up with a premium so that when they sell the policy to the buyer, they can collect the premiums for the future payments of claims from those who suffer losses. The higher the risk, the stronger the likelihood that something bad may happen, and therefore, there would be a higher premium. The lower the risk is, the lower the premium; otherwise, no one would buy the protection. In both cases, premiums paid by all policyholders are pooled into the insurance reserve and any future claims are paid out of the reserve.

Introducing the Nexus Mutual protocol

Nexus Mutual is a decentralized insurance platform built on the Ethereum blockchain to protect smart contracts in DeFi and DApps. It protects smart contracts from bugs, hacks, and unforeseeable events. It is a membership-based, risk-sharing insurance model. Anyone who wants protection for their smart contracts can become a member, which allows them to buy insurance coverage and participate in the protocol’s governance. When an adversarial event occurs, any financial losses can be covered by the insurance reserve for the protocol.

The following diagram shows a high-level conceptual view of the Nexus Mutual protocol:

Figure 3.19 – Decentralized insurance Nexus Mutual protocol

Figure 3.19 – Decentralized insurance Nexus Mutual protocol

Nexus Mutual leverages tokens and incentives to govern insurance operations and members’ behaviors. At its core, this is the membership token, NXM, which is the native ERC-20 token on the Nexus Mutual platform. Anyone can purchase NXMs and become a member; they can then use these NXMs to purchase insurance coverage. Once insurance coverage has been established, 90% of those NXM tokens are burned; the other 10% is locked for the duration of the coverage, plus the system-defined timely claim filing period, which is currently set to 35 days for claim filing. In addition to being able to purchase smart contract coverage, NXMs enable members to take part in protocol governance and play a role in risk assessment and claims assessment.

Nexus Mutual introduced the concept of decentralized risk assessments, where the members can stake their NXMs and partake in the risk assessment. The members who stake for risk assessment become the risk assessors, and they earn risk assessment rewards as NXMs from the insurance coverage purchase. If there are any early claims indicating a lack of judgment in the risk assessment, those stakes may be lost.

Similarly, claims are assessed through voting by the claim assessors. The claim assessor will need to stake NXMs for taking part in the claims assessment. The stakes will be deposited for a certain period and will be returned, provided the claims are assessed and voted honestly. The members who stake for a claims assessment become the claim assessors. When a claim arises, they assess the claim and vote on approving or denying the claim. Voting within the consensus outcome, which is set at a 70% majority, entitles the claims assessors to earn additional NXMs as a processing fee. Voting against the consensus outcome will cause the assessor’s stake to be locked for a long period. If there is no consensus among claim assessors, the claim will be escalated to all members for voting.

Yield farming and DeFi continuum

As you can see, in all the DeFi protocols, one critical enabler is the liquidity pool, a collection of tokens or digital assets locked in a smart contract. These pools bootstrap the DeFi protocol and its ecosystems and provide liquidity for decentralized lending and borrowing, exchanges, derivatives, insurance, and other DeFi protocols. They facilitate trading, payments, and other peer-to-peer crypto transactions on the blockchain network. As we discussed when we talked about Uniswap, a paired liquidity pool allowed crypto assets to be exchanged in a decentralized manner via AMM. Without AMM, protocol designers have to rely on the order book to match orders, which is proven to be much harder and more expensive to implement.

Liquidity providers (LPs) provide liquidity to the liquidity pool. In return, they are incentivized, typically through interest, LP tokens, or governance tokens. In addition to financial rewards, this may enable the liquidity providers to partake in protocol governance and other protocol functions. The process of staking or locking liquidity into the liquidity pools and earning rewards is called yield farming. It is also called liquidity mining. To liquidity providers, this is a form of passive income from crypto assets.

Most of the DeFi protocols we’ve discussed in this section allow you to get rewards by participating in the liquidity pool. These rewards are typically annualized and calculated as an annual percentage yield (APY). These APYs could be vastly different among different protocols. This gives rise to a new category of DeFi protocol, called the yield aggregator, which you first saw in Figure 3.2.

In concept, a yield aggregator works as a set of smart contracts that pool crypto assets from investors and invest them in various yield-producing products or services with the intent to pursue optimal yields.

One such example is yearn.finance. It aggregates yields from leading DeFi lending and borrowing protocols such as Aave, Compound, and others and helps the liquidity providers find the best returns. The liquidity providers, also called yield farmers, deposit their crypto assets into the yearn vault, called yVault. The funds are then converted into yVault tokens, or yTokens. For example, if you deposit 10 ETH, they will be converted into yETH. If you deposit 10,000 DAIs, they will be converted into xDAIs. All yTokens are ERC-20 tokens, act as a deposit receipt, and represent the farmer’s share of the yVault that they are participating in.

A vault is a set of smart contracts that implement automated yield generation algorithms for different crypto assets, each driven by one or more yield strategies. These are defined as strategy contracts. A yVault may have many strategies active at the same time. It may change its strategies, rebalance capital allocations, or automatically shift capital as opportunities arise. One of the key functions of a strategy, called harvest, once called, will trigger the rebalancing process to realize the profits and reinvent the profits back into the strategy. Anyone can build a strategy and add it to the yVault. To add a new one, the strategist, who proposes the strategy, has to go through a rigorous strategy vetting process, including concept vetting, code review, security review, and mainnet testing steps.

DeFi has transformed traditional financial products and services and emerged as the future of the finance sector. However, it is not without its risks. Like any software, there are inherent risks when implementing software and its underlying blockchain infrastructure in DeFi. Scalability challenges in the L1 blockchain may deter DeFi adoption. Vulnerability in smart contract implementation has caused millions of dollars of losses in the leading DeFi platforms. Many protocols rely on Oracle to price the crypto assets, which could pose systematic risks if the prices are compromised.

Governments around the world are closely watching the DeFi protocols and decentralized financial instruments on the crypto markets. New regulations may come out at any time. Regulation risks may lead to additional uncertainty and volatility in the DeFi ecosystem. Government regulation on crypto markets may determine the future and rules of engagement in the DeFi ecosystem for years to come.

So far, you have learned how most of the leading DeFi protocols work. In the next section, we will discuss the economic perspective of the blockchain network and DeFi protocols and help you understand cryptoeconomics and tokenomics in the crypto world.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image