Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
 Building Full Stack DeFi Applications
 Building Full Stack DeFi Applications

Building Full Stack DeFi Applications: A practical guide to creating your own decentralized finance projects on blockchain

By Samuel Zhou
$31.99 $21.99
Book Mar 2024 490 pages 1st Edition
eBook
$31.99 $21.99
Print
$39.99
Subscription
$15.99 Monthly
eBook
$31.99 $21.99
Print
$39.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 29, 2024
Length 490 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837634118
Category :
Concepts :
Table of content icon View table of contents Preview book icon Preview Book

Building Full Stack DeFi Applications

Introduction to DeFi

Decentralized finance (DeFi) is one of the most popular topics when it comes to the cryptocurrency world. There are billions of dollars worth of cryptocurrencies running through various DeFi products every day. More and more cryptocurrency and blockchain projects started to build DeFi applications to expand the user communities and generate more cryptocurrency incomes.

In this chapter, we’ll introduce DeFi by explaining its main characteristics and terminologies. Then, we will cover some popular DeFi applications, and demonstrate the architecture of DeFi applications. Finally, we will discuss the vulnerable design and implementations of DeFi and their solutions. The topics that will be discussed in this chapter are essential to building DeFi applications and will help you understand how various DeFi applications work on blockchain.

By reading this chapter, you will do the following:

  • Get an overview of DeFi and understand its main concepts
  • Learn what people can do with several types of DeFi applications
  • Understand the architecture of DeFi applications
  • Discover the potential vulnerabilities in DeFi applications and their solutions

What is DeFi?

DeFi is an emerging financial technology based on distributed ledgers to support building financial applications. To be more specific, DeFi refers to financial applications that are built on blockchain technologies, typically using smart contracts, which are agreements that are enforced to run automatically on blockchain. Besides that, a complete DeFi solution may also leverage existing technologies such as remote procedure call (RPC) and frontend libraries to make it a full stack DeFi application.

In the era of Web3, DeFi is tied with blockchain, and people started using DeFi on the day Bitcoin was launched in 2009. However, the word DeFi was born almost 10 years later. It was first mentioned in a Telegram chat between Ethereum developers and entrepreneurs in August 2018. It was referred to as an open protocol for finance applications running on the Ethereum network at that time. Then, it became a buzzword across the crypto world. Nowadays, we can see many types of DeFi applications running on various blockchains, including Ethereum, Binance Smart Chain, Polygon, and Solana. These applications allow people to swap cryptocurrencies, earn interest by deposit, and get crypto loans. Next, we are going to discuss the characteristics of these DeFi applications.

Characteristics of DeFi

The main characteristics of DeFi differ compared to traditional finance services and applications. Let’s take a closer look.

Decentralization

The word decentralization is how DeFi got its name. It means that there are no centralized institutes such as banks or other financial institutions to manage or control transactions. We usually call the financial services with centralized institutes centralized finance (CeFi). Unlike CeFi, DeFi adopted blockchain technologies to remove third parties and centralized institutions when making transactions. The transactions are run on public blockchains such as Ethereum. Usually, these blockchains that run the DeFi applications have thousands of nodes; they run DeFi smart contracts and leverage some consensus methods to generate transaction records in blocks. Figure 1.1 shows the differences between CeFi and DeFi:

Figure 1.1 – CeFi versus DeFi

Figure 1.1 – CeFi versus DeFi

Note

As a decentralized system, DeFi applications have no centralized party that has more privileges than others. However, a DeFi project could be centralized if the DeFi smart contract doesn’t renounce ownership and/or a group of users has more privileges than others.

Transparency

The DeFi application transactions are visible to everyone through blockchain explorers. Although people don’t know who owns the address, they can see when a transaction is made, as well as what events and parameters are emitted for the transaction.

Some DeFi applications have their source code open sourced. This helps people understand how these smart contracts work. Even for close sourced smart contracts, they can easily be converted into bytecode to make people understand what the code does. Figure 1.2 shows the bytecode of a smart contract and its decompiled code on etherscan.io:

Figure 1.2 – Bytecode of a smart contract and bytecode decompilation on Etherscan.io

Figure 1.2 – Bytecode of a smart contract and bytecode decompilation on Etherscan.io

Open

We can access all the programs running on the public blockchain, regardless of where we are and who deployed the code. This is also true for DeFi. DeFi removes the borders of countries and ensures that everyone can use the same finance services equally. There are no differences between international transactions and transactions happening in the same city. DeFi makes our assets accessible globally and seamlessly. It’s just like what the internet did for information transferring; thus, DeFi is also called the Internet of Value.

Non-custodial

DeFi enables users to “custody” or control their crypto assets, instead of adopting intermediaries for securing or managing transactions or assets. Users have total control over the funds and how to use them by interacting with the DeFi applications. So, DeFi apps are non-custodial because users always maintain control of their cryptocurrency.

Anonymous

For traditional financial services, users must provide personal information such as their ID and contact information to access them. Conversely, DeFi applications do not require users to provide personal information and they can remain anonymous when using the DeFi services. What DeFi users need to have is a wallet address. This wallet address is a hashed string based on some encryption algorithms. Other people cannot tell who the owner of a specific wallet is and how many wallets belong to a user based on the on-chain data.

Note

We will use the term on-chain as a short form to describe data stored or code executed on the blockchain. Meanwhile, we’ll use the term off-chain to describe the data that’s not stored or code that’s not executed on the blockchain.

Zero downtime

Usually, a traditional financial service has some of its services open only during business hours. For example, the stock market is only open for a few hours a day and is closed on weekends and holidays. On the other hand, DeFi applications are on 24/7, so users can access the service any time on the blockchain.

Note

There are some extreme cases where a DeFi application goes down when the underlying blockchain has insufficient nodes to run, or transaction consensus is controlled by a small group of nodes that are managed by centralized organizations. For example, Binance shut down Binance Smart Chain in early October 2022 to prevent potential exploits. In this case, the blockchain breaks the rule of decentralization.

With that, we’ve looked at the six key characteristics of DeFi. There are several terminologies when entering the world of DeFi. We will discuss some of these terms in the next section and explain the remaining in the future chapters of this book.

Understanding terminologies

You may have heard of terms such as ERC-20, liquidity, Oracle, TVL, or APY when you came to the world of DeFi. Let’s discuss several of these terminologies as we will mention them frequently throughout our DeFi application development.

ERC-20

ERC-20 defines the standard of fungible tokens on the Ethereum blockchain. Fungible tokens are cryptocurrencies that people talk about. The smart contracts of fungible tokens implement cryptocurrencies that are exchangeable. This means the value of a token is the same as another token of the same cryptocurrency. For example, the value of 1 Bitcoin in Sam’s wallet is the same as 1 Bitcoin in Alice’s wallet. These characteristics of fungible tokens are different from non-fungible tokens (NFTs). With the smart contracts of NFTs, one token is different from another token implemented with the same smart contract. The reason is that each token has a unique ID, so the metadata and price could be different.

An ERC-20 token follows the standard interface to implement its smart contract to approve, transfer, and get the balances of the token.

The fungible token standard is especially important for building DeFi applications. It enables token compatibility across different decentralized applications (DApps) and makes DeFi applications support transactions with different tokens if the standard is followed by these tokens. For example, users can swap one type of ERC-20 token with another type of ERC-20 token.

Note

ETH (Ethereum) is a type of “coin,” not an ERC-20 token, because it is the native cryptocurrency of Ethereum, which is its own blockchain. Also, ETH is not an ERC-20 token. Token here means a type of cryptocurrency that doesn’t run on its own blockchain and operates on existing blockchain(s). For example, Shiba Inu Token (SHIB) is a token on the existing Ethereum blockchain and other Ethereum Virtual Machine (EVM)-compatible blockchains, but it doesn’t run on its own blockchain.

There are other token standards such as BEP-20 (for Binance Smart Chain) or TRC-20 (for TRON blockchain). These are the fungible token standards of other EVM-compatible blockchains. The interface definition is the same as ERC-20, but the cost of transactions, performance, and security are different based on the design of these blockchains.

We will work with ERC-20 tokens in this book to build a real-world DeFi application. To support non-standard coins or tokens on blockchains, people implemented wrapped tokens that conform to these standards (such as ERC-20), such as Wrapped ETH (WETH) for Ethereum and Wrapped BNB (WBNB) for Binance. Wrapped tokens are widely used to support the unified interface so that it can interact with DeFi smart contracts. We will learn more about wrapped tokens in Part 2, Designing and Implementing a DeFi Application for Trading Cryptos.

Liquidity

Liquidity may be a new concept for developers who’ve just started to learn about DeFi. However, liquidity is a fundamental concept for both DeFi and traditional finance services. It describes whether users can buy and sell an asset through a trading market and how efficiently they can make these transactions.

For example, a cryptocurrency project may have liquidity, which means people can buy and sell the cryptocurrency somewhere. If it does not have liquidity, there are no reserves for people to find the price of the cryptocurrency, and users will not be able to buy and sell the cryptocurrency through a trading market.

A liquidity pool is a place to hold the liquidity for people to trade assets. In the DeFi world, it is a specific smart contract that holds pairs of cryptocurrencies so that people can buy one type of cryptocurrency with another type of cryptocurrency or sell one for another. We call these buy or sell activities swaps.

A pair of liquidity pools means that the smart contract should hold two types of tokens so that they can be swapped from one to another. Both types of tokens should follow the standard of the underlying blockchain (for example, the ERC-20 tokens for Ethereum). For example, for an ETH/USDT liquidity pool, the smart contract holds an amount of WETH (the wrapped ETH token that follows the ERC-20 standard) and the same value of USDT.

The ratio of the tokens in the liquidity pool defines the prices of the two types of tokens in the pool. Imagine that we buy ETH with USDT; we must interact with the ETH/USDT liquidity pool. The purchase means we get ETH from the liquidity pool and put more USDT into the pool. Now, there are fewer ETH coins and more USDT in the pool for trading. Hence, the price of ETH will rise.

The amount of liquidity in a liquidity pool determines the stability of the price when people are swapping tokens. When the liquidity pool is bigger, the ratio of the pooled tokens is more stable for a transaction of the same amount. People tend to trade using bigger liquidity pools to trade at a more stable price.

Note

If you want to trade ETH with BTC (Bitcoin) in the case that we already have the ETH/USDT liquidity pool, the DeFi protocol should have another trading pair (ETH/BTC) as a liquidity pool so that you can trade ETH with BTC. Alternatively, we may have a BTC/USDT liquidity pool in the same protocol so that you can trade with the BTC -> USDT -> ETH route. However, it usually takes a higher gas fee to complete the transaction with a lengthy route.

We will discuss how to implement liquidity pools in Part 2, Designing and Implementing a DeFi Application for Trading Cryptos.

Oracle

Oracle in the Web3 ecosystem does not mean the brand of the database. It is a technology that allows smart contracts running on a blockchain to access information outside of the system. This information could come from off-chain or on-chain data sources. If the oracle depends on an off-chain data source, the smart contract can access centralized Web2 (the internet ecosystem before Web3) systems, so the smart contract may undermine the benefits that decentralized blockchains bring to us.

Oracle is a very important technology for DeFi applications. For example, if you want to get a reliable cryptocurrency price compared to a fiat currency, you must retrieve the price data from oracle network(s).

To access oracle services, DeFi smart contracts need to call third-party libraries that are not components of the system. For example, if you want to create a lottery application on Ethereum, and because there is no real random number generator for Ethereum, you may need to call Chainlink’s verifiable random function (VRF) to get true random numbers for selecting winners.

We can implement applications on blockchain for many things we can do in Web2 with oracle, including accessing the local weather or the price of a product on Amazon, or even calling any existing services. All these can be done through a hybrid smart contract, which is a kind of smart contract that can access off-chain systems. You can refer to https://chain.link/education-hub/hybrid-smart-contracts to learn more about hybrid smart contracts.

In Part 4, Building Crypto Loans for Lending and Borrowing, you will learn how to use oracle to implement a DeFi crypto loan application.

Total value locked (TVL)

TVL defines the value of the total assets being deposited in a DeFi protocol. Usually, a DeFi protocol that holds crypto assets has one or more smart contracts with different features running on the blockchain. TVL is the sum of crypto assets being held by these smart contracts that belong to the same protocol. Usually, the assets consist of multiple types of cryptocurrencies. DeFi projects convert the sum of these crypto assets into fiat (for example, US dollars) to represent TVL in public.

For example, if a DeFi project owns three liquidity pools with values of $1,000, $2,000, and $3,000, the TVL of the DeFi project is $6,000. If the project introduced a staking pool that has $2,000 worth of assets in it, the TVL of the DeFi project will become $8,000 by adding the $2,000 worth of staking pool.

Note

The word “locked” in the term TVL doesn’t mean withdrawals or asset transfers are not allowed. The smart contracts may still allow people to swap, add or remove liquidity, and stake or unstake tokens that impact the amount and value of cryptocurrencies being held by these smart contracts. The TVL will change accordingly.

Most public DeFi projects provide a public API for people to access TVL. DefiLlama (https://defillama.com/) is one such platform that uses a public API to collect data from DeFi projects. Based on the chart shown in Figure 1.3, the total TVL of all the projects they’ve collected was $49.5 billion in early January 2023. This is 22.3% of the all-time high, which was $213 billion in December 2021:

Figure 1.3 – DefiLlama – the total TVL of DeFi projects

Figure 1.3 – DefiLlama – the total TVL of DeFi projects

TVL is a significant indicator of a DeFi project. People usually trust DeFi projects that have higher TVLs. A higher TVL means more capital being held in the platform, and it intends to have a higher trading volume, which indicates higher yields. Also, a higher TVL means lower risk because the prices of cryptocurrencies are more stable when people make transactions; it prevents unnecessary loss caused by fluctuation.

Annual percentage yield (APY) and annual percentage rate (APR)

APY measures the rate of return when users deposit their cryptocurrencies in DeFi protocols. APY takes compound interest into account, so it requires users to keep depositing both principal and interest generated in each cycle for a full year to get the promised yield. However, some DeFi projects just offer a short-term deposit and an exceedingly high APY to attract users to buy their cryptos. Sometimes a high APY is a marketing strategy, and most projects only show APY and hide the actual earning rates users can get.

APR, on the other hand, sums up all the rates from every earning cycle through a year. For example, if a DeFi project has 12 earning cycles in a year and the earning rate is 1% for each cycle, the APR will be 12%, which is the sum of 12 1%s.

To calculate the APY, which is the compound yield from APR, we can use the following formula:

MathZone*IMGstyle="vertical-align:-0.308em;height:1.124em;width:6.696em"<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" display="block"><mml:mi>y</mml:mi><mml:mo>=</mml:mo><mml:msup><mml:mrow><mml:mo>(</mml:mo><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mfrac><mml:mrow><mml:mi>r</mml:mi></mml:mrow><mml:mrow><mml:mi>n</mml:mi></mml:mrow></mml:mfrac><mml:mo>)</mml:mo></mml:mrow><mml:mrow><mml:mi>n</mml:mi></mml:mrow></mml:msup><mml:mo>-</mml:mo><mml:mn>1</mml:mn></mml:math>

Where:

  • y is the APY
  • r is the APR
  • n is the number of earning cycles in one year

For example, if a DeFi project offers 12% of APR in earnings and each cycle is one month, which means there will be 12 cycles in a year, the APY will be as follows:

MathZone*IMGstyle="vertical-align:-0.499em;height:1.690em;width:10.919em"<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" display="block"><mml:msup><mml:mrow><mml:mo>(</mml:mo><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mfrac><mml:mrow><mml:mn>12</mml:mn><mml:mi>%</mml:mi></mml:mrow><mml:mrow><mml:mn>12</mml:mn></mml:mrow></mml:mfrac><mml:mo>)</mml:mo></mml:mrow><mml:mrow><mml:mn>12</mml:mn></mml:mrow></mml:msup><mml:mo>-</mml:mo><mml:mn>1</mml:mn><mml:mo>=</mml:mo><mml:mn>12.68</mml:mn><mml:mi>%</mml:mi></mml:math>

If we want to calculate the earning rate for each cycle by giving the APY, the formula is as follows:

MathZone*IMGstyle="vertical-align:-0.297em;height:1.122em;width:5.887em"<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><mrow><mrow><mi>R</mi><mo>&#x3d;</mo><mroot><mrow><mi>y</mi><mo>&#x2b;</mo><mn>1</mn></mrow><mi>n</mi></mroot><mo>&#x2212;</mo><mn>1</mn></mrow></mrow></math>

Where:

  • y is the APY
  • R is the earning rate of a single cycle
  • n is the number of earning cycles in one year

For example, a promotion activity offers 100% APY for an ETH deposit activity and the deposit term is 7 days, so the actual rate you can get during those 7 days is as follows:

MathZone*IMGstyle="vertical-align:-0.072em;height:1.132em;width:11.144em"<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" display="block"><mml:mroot><mml:mrow><mml:mn>100</mml:mn><mml:mi>%</mml:mi><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mrow><mml:mn>365</mml:mn><mml:mo>/</mml:mo><mml:mn>7</mml:mn></mml:mrow></mml:mroot><mml:mo>-</mml:mo><mml:mn>1</mml:mn><mml:mo>=</mml:mo><mml:mn>1.34</mml:mn><mml:mi>%</mml:mi></mml:math>

This means that when you deposit 100 ETH, you will get 1.34 ETH as earnings.

More DeFi terminologies are for specific DeFi features. We will discuss them later in this book.

Overview of DeFi applications

DeFi is one of the vibrant spaces in the Web3 world that people use to manage and grow their crypto assets. In this section, we will go through the DeFi applications we will build in this book.

Decentralized exchanges

Decentralized exchanges (DEXs) are one of the most popular DeFi applications that people use because it allows them to buy and sell cryptocurrencies on the blockchain. Different from traditional exchanges (such as stock exchanges) or centralized exchanges (CEXs), DEX applications are run on the blockchain in a decentralized manner and people can see the transactions for the smart contracts of the DEX. There is no intermediary to control the process and hold your funds. And you can get the result and/or tokens immediately after the transaction is executed by the blockchain.

A CEX for cryptos, on the other hand, is operated by financial service companies; they usually have crypto assets on blockchains to support on-chain transferring for their customers. However, the transactions and liquidities are maintained internally within the service institution and may not be visible outside of CEX.

Centralization is an issue that negatively affects security, trust, and privacy. The main reason is a lack of transparency and that people in CEXs can leverage the disclosed information (for example, upcoming promotion activities) to gain profit or even take money directly from customers. The recent bankruptcy news of FTX reported that they took at least $8 billion of their customers’ money and that this money may be lost permanently.

Automated market maker (AMM) is a type of DEX that allows cryptocurrencies to be bought and sold automatically based on the prices calculated from liquidity reserves in DEXs. AMMs are implemented with smart contracts that hold liquidity as reserves on the blockchain, which allow users to easily trade on-chain assets. They usually offer rewards to liquidity providers (the people who provide tokens that become part of liquidity in the DEX) from a small portion of trading volumes. Figure 1.4 shows the workflow of an AMM:

Figure 1.4 – Overview of AMM workflows

Figure 1.4 – Overview of AMM workflows

We will walk you through the process of building a full stack AMM (which is also a DEX) in Part 2, Designing and Implementing a DeFi Application for Trading Cryptos.

Crypto loans

Loans may be the most useful financial tools in our everyday lives. You can get property loans to purchase a new house. Meanwhile, you can deposit your money to earn interest, and banks may lend your saved money to other borrowers in the form of loans. This idea behind the scenes also applies to crypto loans.

A crypto loan is one of the most important DeFi use cases. The largest crypto loan project, AAVE, has $6 billion of TVL for their lending pool based on the information from their official website (https://aave.com/). More Web3 projects adopted crypto loans as their portfolios because of the high market potential of crypto loans.

Crypto loans have many use cases and can benefit diverse groups of DeFi users:

  • For online shopping, people can borrow platform-supported cryptos by providing collateral cryptocurrencies. For example, some online shopping companies only support Bitcoin or stablecoins such as USDT. People can provide ETH or BNB as collaterals and borrow Bitcoin and stablecoins without selling the ETH or BNB they hold.
  • For business, a company can raise money by providing crypto assets as collateral. In return, they can borrow stablecoins or other tokens to grow the business.
  • For cryptocurrency investment, crypto loans can help people reduce the risk of fluctuation of the crypto market. For example, let’s say you found a highly rewarded program for token A, but you only have USDT at hand. You can get token A by lending USDT without selling it. You can still get the original provided USDT back, so long as you pay back token A regardless of the price fluctuation of token A.

The term collateral has been mentioned several times regarding crypto loans. Collateral is the assets that a user provides to guarantee that this user will repay the loan when they borrow. For example, you can obtain property loans from a bank for your house and the bank could be an owner of the house because the house is the collateral. Collateral can also represent the assets a user deposited to earn interest.

Figure 1.5 shows the workflow of crypto loans in DeFi:

Figure 1.5 – The workflow for crypto loans

Figure 1.5 – The workflow for crypto loans

Usually, a crypto loan should support at least four operations: Deposit, Borrow, Repay, and Withdraw. To prevent loss when the collateral loses its value or the borrowed assets become more valuable, DeFi projects utilize a borrow limit with loan-to-value (LTV) and a liquidation process by providing the borrowed assets with a percentage of rewards. We will talk more about these when we implement a crypto loan application in Part 4, Building Crypto Loans for Lending and Borrowing.

Staking, yield farming, and liquidity mining

Staking, yield farming, and liquidity mining are three DeFi technologies that can generate passive income and enable cryptocurrency holders to earn more by depositing existing assets on the blockchain. In general, the relationship between the three DeFi technologies is shown in Figure 1.6:

Figure 1.6 – The general relationships between staking, yield farming, and liquidity mining

Figure 1.6 – The general relationships between staking, yield farming, and liquidity mining

Generally, staking means any action using some mechanism to generate passive earnings by holding users’ assets in another place (not the user’s wallet). This place could be on a blockchain or a centralized institute (for example, a CEX). Staking is a broader concept that people can earn from the three mechanisms:

  • Blockchain consensus mechanisms such as proof of stake (PoS) or proof of transfer (PoX).
  • Reward distribution. This means that some rewards will be distributed to certain places, such as staking smart contracts. Then, the rewards will be distributed to users with a fixed or floating APY when the user unstakes.
  • DEX swapping fees. When the user adds liquidities to liquidity pools, a small portion of the transaction fees from the DEX will be used to reward liquidity pool providers as passive income. Users can earn it by holding liquidity pool tokens.

Note

In most scenarios, staking means getting rewards by depositing one type of cryptocurrency. This is what we will build later in Part 3, Building DeFi Staking and Yield Farming.

In DeFi, liquidity mining means that users can get newly mined liquidity pool tokens (LP tokens) by providing liquidity. These LP tokens represent the share of the user’s contribution to a liquidity pool. Then, they can earn a portion of swapping fees from DEX as liquidity pool rewards.

Yield farming offers a way to maximize user compensation by providing liquidity. Although liquidity mining is one of the most popular types of yield farming, yield farming can stimulate yield farmers (yield farming users) to stake LP tokens by providing extra rewards from reward distributions. This encourages yield farmers to not remove liquidity from liquidity pools and make liquidity pools more stable and healthier. For example, yield farmers can get a CAKE token in PancakeSwap yield farming, so they can get both a liquidity pool reward and a farming reward (the CAKE token).

Note

Liquidity mining is a specific type of yield farming that doesn’t provide extra farming rewards. The yield is only a liquidity pool reward in this case.

Table 1.1 summarizes the different ways of earning from staking, yield farming, and liquidity mining in DeFi:

Ways of Earning

Staking

Yield Farming

Liquidity Mining

Swapping fee (liquidity pool reward)

Yes

Yes

Yes

Reward distribution

Yes

Yes

No

Blockchain consensus mechanism

Yes

No

No

Table 1.1 – Ways of earning for staking, yield farming, and liquidity mining in DeFi

We will learn how to build a full stack DeFi application with liquidity mining in Part 2, Designing and Implementing a DeFi Application for Trading Cryptos. We will add staking and yield farming features to the application in Part 3, Building DeFi Staking and Yield Farming.

There are more interesting DeFi applications that are not covered in this book, such as insurance, stablecoins, and decentralized autonomous organizations (DAOs). Please refer to https://101blockchains.com/decentralized-finance-applications/ for more information.

In the next section, we will explore the building blocks of DeFi applications by demonstrating the DeFi application architecture.

Architecture of DeFi applications

As we mentioned earlier, decentralization is one of the most noteworthy features of DeFi. It also means using a different architecture when building DeFi applications compared to non-Web3 applications.

When building an application that is either on-premises or on the cloud, we rely on a node or a group of nodes to run the business logic of the application. These nodes are either managed by business owners or cloud vendors. This means that we know who is running our services and are responsible for the healthiness of these nodes.

In the Web3 era, the business logic is run in blockchain. We don’t need to care about which nodes are running our code because these nodes are self-organized based on the same blockchain protocol and use some consensus mechanism to secure the transactions. We don’t need to set up a server or subscribe to cloud services. What we do need to do, however, is deploy smart contracts on the blockchain and pay the gas fees.

Figure 1.7 shows the architecture of DeFi applications:

Figure 1.7 – The architecture of DeFi applications

Figure 1.7 – The architecture of DeFi applications

Different from the architecture of traditional financial services, the business logic for DeFi does not require business-owned nodes to run. The user’s data is stored on blockchains, and the transactions are run on blockchains. Based on Figure 1.7, let’s look at the different components of DeFi applications.

DeFi application frontend

The DeFi application frontend is the user interface (UI) for accessing DeFi applications, although users can call smart contracts directly via RPC endpoints. The frontend can be a web page or mobile user interface. These frontend implementations are provided by DeFi developers for users to interact with smart contract functions much more easily. The code that accesses the blockchain for these web pages is usually implemented with the JavaScript or TypeScript programming language.

Usually, developers use Web3 frontend libraries such as web3.js or ethers.js for developing DeFi application web pages (frontend code) more easily. These libraries wrap up the connection, authentication, and RPC calls to smart contracts.

Note

Some of the libraries also provide support for other programming languages, such as Python and Java, so that developers can access the blockchain from backend servers. However, a decentralized system should not rely on the backend server code. The code of a DeFi application should be run on the client side (for example, a user’s web browser) and the blockchain. This is the rule we will follow when building DeFi applications in this book.

DeFi wallet

A DeFi wallet identifies a Web3 account that the user owns. DeFi applications can authorize the user to access the information owned by this user or perform permitted actions on the blockchain.

Compared to traditional applications, the DeFi wallet offers a more convenient process to use applications. Remember that, with traditional applications, you must register accounts for every application, note down the password, and worry about whether your personal information is being leaked to attackers. None of these problems exist when using DeFi wallets.

Creating a Web3 account only requires you to get a DeFi wallet app and follow the wizard when you open the app for the first time. This process only requires you to back up a seed phrase or private key and it is not necessary to provide any confidential information. Once you have a DeFi wallet, you can use the same wallet address to access all DeFi applications if they run on a supported blockchain.

Several DeFi wallet vendors are available, such as MetaMask and Trust Wallet. Most of the vendors are for software wallets. There are also hardware wallets such as paper (for example, you can write down the private key or seed phrase and recover it with any DeFi wallet app) or electronic hardware wallets (for example, Ledger: https://www.ledger.com).

CEX applications also offer wallets so that you can send or receive cryptocurrencies. However, you may not be allowed to use the wallets to access other DeFi applications or import the wallet into another DeFi wallet app. The reason is that users do not have access to the private key, so they cannot access the wallet and the funds in it via other DeFi wallet apps.

Note

Some DeFi wallets require you to back up a 12-word or 24-word seed phrase so that you can recover the wallet in the future. There are two differences between a seed phrase and a private key:

  • One private key maps to one wallet address (account); so, one private key can only be used for recovering one wallet address. Meanwhile, one set of seed phrases can be mapped to all addresses and used for recovering all addresses in a DeFi wallet app that belongs to one user.
  • One private key can be used to recover a wallet address (account) on any DeFi wallet, whereas a set of seed phrases generated by one wallet application is not guaranteed to recover the same set of wallet addresses in a different DeFi wallet application.

RPC endpoint

An RPC endpoint is the entry point for DeFi users and applications to access data and run transactions on the blockchain. Similar to using REST API calls, users can access the blockchain by sending requests to the RPC endpoint with a JSON payload to call smart contract functions and get the account balance in the EVM-based blockchain. https://ethereum.org/en/developers/docs/apis/json-rpc/ contains more information about JSON-RPC standards and different ways to call RPC endpoints.

RPC endpoints for Ethereum can be public or private. Public RPC endpoints are shared by others; they are usually slower and have limitations in terms of throughput compared to private RPC endpoints.

Developers usually use RPC endpoints from different providers for DeFi applications on Ethereum. The most famous RPC endpoint providers include Infura (https://infura.io/), Ankr (https://ankr.com/), and Cloudflare (https://cloudflare-eth.com/). At the time of writing this book, Cloudflare and Ankr provide publicly shared RPC endpoints. While Infura only provides private RPC endpoints, you can get API keys for free to use the endpoint for your project. This book suggests using private RPC endpoints for DeFi applications for their reliable connection between the UI code and blockchain.

You can also refer to https://cointool.app/rpcServer/eth or https://ethereumnodes.com/ for a list of publicly shared RPC endpoints for Ethereum.

Interactions between blockchain and oracle

As mentioned earlier, oracle is an important technology. Now, let’s discover how a blockchain network interacts with an oracle network.

An oracle network provides the services that blockchain doesn’t have – for example, to get the price of a stock, the total revenue of a company in 2022 Q4, or the population of a country. The nodes in the oracle network may not be decentralized because they are not a part of the blockchain.

To access the service provided in the oracle network, developers have to implement smart contracts that call the API provided by oracle. This type of smart contract is called a hybrid smart contract and it connects the blockchain network and the oracle network. In most cases, developers do not need to write code to call the API since oracle vendors such as Chainlink already implement some hybrid smart contracts in popular blockchains. So, you can directly call these smart contracts via Solidity, or use Web3 libraries to call hybrid smart contract functions directly from the frontend or backend code.

Figure 1.7 shows the basic workflow of accessing an oracle network from the blockchain. It is a two-step process for each request. The smart contract has to request for the oracle service first. Once the oracle network completes the request, it will call another section of code in the blockchain (callback) to fulfill the request.

The reason for leveraging this two-step pattern is that Solidity or Ethereum doesn’t have any synchronization mechanism to wait for an event in its code. Instead, a smart contract function returns immediately after a request is sent to the oracle network, at which point an off-chain process will “wait for” the completion of the request in the oracle network. Finally, the oracle network can call blockchain smart contract functions again to notify the completion of the request.

Now that we have covered the architecture of DeFi applications, next, we will discuss the possible vulnerabilities of DeFi applications and some best practices to prevent them from happening.

Vulnerabilities of DeFi applications

DeFi is one of the innovative technologies that introduced new financial activities for people and potentially changed the existing financial infrastructure. In this section, we will focus on the vulnerabilities that may occur in DeFi applications, especially the applications we are going to build in this book since hackers can leverage the vulnerabilities of smart contracts to exploit the crypto assets from smart contracts and users' wallets. Figure 1.8 shows that the total value hacked for DeFi has been around $6 billion since mid-2016:

Figure 1.8 – DefiLlama – DeFi loss by month

Figure 1.8 – DefiLlama – DeFi loss by month

Fortunately, most of the vulnerabilities have solutions. We will discuss various causes of these vulnerabilities and best practices to prevent these issues in this section. Some knowledge of the Solidity programming language will help you understand the code snippets in this section, but it is not required for you to understand the principles.

Reentrancy

Reentrancy is one of the most destructive security attacks in smart contracts written with Solidity. A reentrancy attack occurs when a function makes an external call to another untrusted contract. Then, the untrusted contract makes a recursive call back to the original function in an attempt to drain funds.

For example, an attack smart contract could implement a fallback function that withdraws funds from a vulnerable smart contract. When the attack smart contract receives the fund, the fallback function will be called automatically, which makes recursive calls, at which point it will withdraw the fund again until the fund in the vulnerable smart contract is drained. Figure 1.9 demonstrates the sequence of actions to perform this attack:

Figure 1.9 – The workflow of a reentrancy attack

Figure 1.9 – The workflow of a reentrancy attack

To find the relevant code example and learn more about reentrancy attacks, please go to https://solidity-by-example.org/hacks/re-entrancy/.

To prevent a reentrancy attack, we will use ReentrancyGuard from the OpenZeppelin (https://www.openzeppelin.com/) library when building DeFi applications later in this book.

Self-destruct operation

In the early days of Ethereum, one of the earliest DAO projects lost $3.6 million worth of ETH due to a hack. What’s even worse is that the attack continued for days due to the immutability of the smart contract on the blockchain, so the developer could not add a function to take back the ETH from smart contracts or destroy the smart contract to prevent hacking. In 2016, Ethereum introduced the selfdestruct function to serve as an exit door for smart contracts in case of an attack. Here is an example of how to use the selfdestruct function:

contract SelfdestructExample {
  function killContract(address payable receiver) external {
    selfdestruct(receiver);
  }
}

This code snippet defines a smart contract called SelfdestructExample. A person can call the killContract function to destroy the smart contract, at which point all the ETH held by the smart contract will be transferred to receiver when selfdestruct is called.

The behavior of transferring ETH to a specific address could cause a side effect. Hackers can then use this side effect to forcefully send ETH from a self-destruct smart contract to another smart contract to make it vulnerable.

The example at https://solidity-by-example.org/hacks/self-destruct/ shows the act of forcefully transferring ETH to a smart contract to break the rules of the game. There is a game that only allows players to transfer 1 ETH at a time. The person can win when the balance of the smart contract is equal to or greater than 7 ETH, and the winner can take all the ETHs. Although the game smart contract only allows a player to transfer 1 ETH every time, the attacker broke the rule by forcibly transferring more ETHs to the game smart contract in one transaction with the selfdestruct function.

The solution is using a storage variable in the smart contract to store the balance instead of using address(current_contract).balance. This will be the source of truth for the smart contract to rely on, and the selfdestruct function cannot manipulate the variable.

Gas overflow

All the transactions that need to write data on the blockchain need to pay for gas. For EVM-based blockchains, the gas is precalculated before the transaction and the gas is consumed while executing the bytecode of the smart contract. However, the gas estimation can be temporarily or consistently inaccurate due to the indeterminacy of the Solidity programming language and network traffic. As developers, we need to pay attention to the code that could cause this gas variation and try to optimize the code.

For example, a gaming smart contract may implement a function to reward winners, like so:

function rewardPlayers() external {
  if (isWinner(msg.sender)) {
    safeTransfer(token, msg.sender, winAmount);
    emit Win(msg.sender, winAmount);
  }
}

If isWinner(msg.sender) determines the winner with some randomness at the time of calling it, it would cause differences between the gas estimation and gas actual usage. This means that the gas estimation assumes that the safeTransfer function is not called, so it assigns a small amount of gas to run the transaction. However, at the time of execution, the caller of the function is selected as the winner, and the safeTransfer call in the if statement exceeds the gas limit, which causes a denial-of-service (DoS) attack.

Iterations can also cause gas overflow if the size of the iteration grows over time. Figure 1.10 shows the relationship between gas usage and the number of iterations:

Figure 1.10 – The relationship between gas usage and the number of iterations (benchmarked with Solidity v0.8.3)

Figure 1.10 – The relationship between gas usage and the number of iterations (benchmarked with Solidity v0.8.3)

Based on the data shown in Figure 1.10, gas usage grows exponentially along with the number of iterations. We need to be careful about arrays of a dynamic size and try to reduce this size when possible.

There are many ways to prevent gas overflow. The key thing is optimizing the Solidity code by following good practices. You can refer to https://dev.to/jamiescript/gas-saving-techniques-in-solidity-324c for some techniques for optimizing your Solidity code to save gas usage.

Random number manipulation

Randomness drives people to play against uncertainties. Nowadays, DeFi projects are increasingly introducing lotteries or other forms of randomness to give bonus rewards to their users and attract more users to use their DeFi applications. However, there is no ideal way to generate random numbers within EVM-compatible blockchains. This may cause attackers to manipulate the random number generation and get the number to steal the assets from the reward pool.

If you want to implement a random number generator with the facilities in EVM, you can use code similar to the following:

/*
 * Returns a random number.
 * If the caller of the function gets a random number
 * that can be divided by 10000, then the caller will win.
 */
function getRandomNumber() private view returns (uint256) {
  return uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender)));
}

As you can see, the getRandomNumber function returns a random integer. Inside the function, it concatenates block.timestamp and msg.sender to generate a long byte array, then hashes the bytes with the keccak256 algorithm to generate a pseudo-random number. Here, msg.sender is the caller’s address, and block.timestamp is the timestamp field of a block in its header. Because the timestamp is set by the miner, a hacker can set the block.timestamp function of the next block by being a miner to generate a random number that makes them win.

To get a true random number, we can use an oracle service such as Chainlink VRF. It relies on many nodes being on the network to generate a random number that is secure and almost impossible to manipulate by hackers. However, this random number retrieval requires a request and a callback to fulfill the request. The duration between the request and its fulfillment may take dozens of seconds to more than one minute, and each request may take an amount of LINK tokens plus the gas fee. As a result, it is better for a smart contract that relies on random numbers such as lottery games to wait for a certain period to reveal rewards instead of doing that on the spot (for example, reveal a group of winners daily or weekly).

To learn how to get random numbers with Chainlink oracle, go to https://docs.chain.link/vrf/v2/subscription/examples/get-a-random-number/.

There are many more types of vulnerabilities in DeFi. We will discuss this in more detail when we build DeFi applications later in this book. Now, let’s summarize what we have learned so far.

Summary

In this chapter, we learned about the different characteristics of DeFi and understood that decentralization is the key difference between DeFi and traditional financial solutions. We also went through the terminologies that will be mentioned frequently throughout the DeFi application development process. We learned that ERC-20 is the standard of fungible tokens on the Ethereum blockchain; we will build DeFi smart contracts that support ERC-20 tokens in this book. We also went through the various DeFi applications we will implement and briefly introduced the main use cases and how they work for these applications. This information will help you build a high-level view of DeFi applications.

Then, we explored some technical topics that will help us to build a DeFi application. We learned about the architecture of DeFi applications and went through various components, such as DeFi wallets, RPC endpoints, blockchain networks, and Oracle networks, and how they work together. Finally, this chapter explored a few popular vulnerabilities of DeFi applications and how to solve them.

In the next chapter, we will explore more techniques, tools, and libraries that will help us build DeFi applications. We will create a project for these applications and start to write code and learn how to use these tools to debug and test DeFi applications.

Further reading

If you want to learn more about the topics mentioned in this chapter, please refer to the following resources:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Gain the knowledge you need to start implementing DeFi principles in practice
  • Learn how to build full-stack real-world DeFi products from scratch with step-by-step instructions
  • Leverage tools like Hardhat, Ethers.js, Node.js, React.js, Solidity, and Web3 for effective DeFi application development
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Enter the world of Decentralized Finance (DeFi) with Building Full Stack DeFi Applications. Understand how this blockchain-based financial technology, designed to manage crypto assets, runs independently without centralized financial institutions like banks and brokerages, eliminating the fees that banks and other financial companies charge for using their services. This book will show you how DeFi solutions are built with smart contracts running on blockchains and how they allow users to gain and earn crypto assets based on the trust of the smart contracts. This book uncovers the inner workings of DeFi by guiding you through the mathematical foundations and teaching you how to build real-world DeFi products with Solidity and JavaScript. As you progress through the chapters, you’ll learn how to implement smart contracts of liquidity pools to trade cryptocurrencies and implement staking, including farming features that allow users to earn. You’ll also find out how to create asset pools that allow users to lend and borrow cryptocurrencies and generate interest. Additionally, you’ll discover how to use Web3 libraries to build the frontend of DeFi products. By the end of this book, you’ll will be well acquainted with popular tools, libraries, and design patterns for implementing a full-stack DeFi application with Web3 and Solidity.

What you will learn

Understand the key concepts and principles of DeFi and how it works Get to grips with smart contract development to solve complex problems Build your experience in designing, building, and deploying Web3 applications Implement liquidity pools and swapping features for seamless crypto exchanges Develop staking and farming features for DeFi applications Create smart contracts for crypto loans integrated with Web3 libraries

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 29, 2024
Length 490 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837634118
Category :
Concepts :

Table of Contents

21 Chapters
Preface Chevron down icon Chevron up icon
Part 1: Introduction to DeFi Application Development Chevron down icon Chevron up icon
Chapter 1: Introduction to DeFi Chevron down icon Chevron up icon
Chapter 2: Getting Started with DeFi Application Development Chevron down icon Chevron up icon
Chapter 3: Interacting with Smart Contracts and DeFi Wallets in the Frontend Chevron down icon Chevron up icon
Part 2: Design and Implementation of a DeFi Application for Trading Cryptos Chevron down icon Chevron up icon
Chapter 4: Introduction to Decentralized Exchanges Chevron down icon Chevron up icon
Chapter 5: Building Crypto-Trading Smart Contracts Chevron down icon Chevron up icon
Chapter 6: Implementing a Liquidity Management Frontend with Web3 Chevron down icon Chevron up icon
Chapter 7: Implementing a Token-Swapping Frontend with Web3 Chevron down icon Chevron up icon
Chapter 8: Working with Native Tokens Chevron down icon Chevron up icon
Part 3: Building a DeFi Application for Staking and Yield Farming Chevron down icon Chevron up icon
Chapter 9: Building Smart Contracts for Staking and Farming Chevron down icon Chevron up icon
Chapter 10: Implementing a Frontend for Staking and Farming Chevron down icon Chevron up icon
Part 4: Building a Crypto Loan App for Lending and Borrowing Chevron down icon Chevron up icon
Chapter 11: An Introduction to Crypto Loans Chevron down icon Chevron up icon
Chapter 12: Implementing an Asset Pool Smart Contract for a Crypto Loan Chevron down icon Chevron up icon
Chapter 13: Implementing a Price Oracle for Crypto Loans Chevron down icon Chevron up icon
Chapter 14: Implementing the Crypto Loan Frontend with Web3 Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.