Reader small image

You're reading from  Building Full Stack DeFi Applications

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837634118
Edition1st Edition
Concepts
Right arrow
Author (1)
Samuel Zhou
Samuel Zhou
author image
Samuel Zhou

Samuel Zhou has over 15 years of software engineering experience in top high tech companies including being a blockchain developer as his hobby since 2018. In 2022, Samuel turned his enthusiasm on blockchain technology into a business by founding TiFi, which is a silicon valley based startup that builds e-Commerce platform on blockchain and brings blockchain to everyday life. Over there he has created TiFi Token that offers token rebates so people can get cash back when spending the token. Also he has built TiFi Bank which is a DeFi application that offers crypto saving, lending, trading, staking and liquidity management features. Samuel holds a Master Degree and a Bachelor Degree in Computer Science.
Read more about Samuel Zhou

Right arrow

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.

Previous PageNext Page
You have been reading a chapter from
Building Full Stack DeFi Applications
Published in: Mar 2024Publisher: PacktISBN-13: 9781837634118
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.
undefined
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 $15.99/month. Cancel anytime

Author (1)

author image
Samuel Zhou

Samuel Zhou has over 15 years of software engineering experience in top high tech companies including being a blockchain developer as his hobby since 2018. In 2022, Samuel turned his enthusiasm on blockchain technology into a business by founding TiFi, which is a silicon valley based startup that builds e-Commerce platform on blockchain and brings blockchain to everyday life. Over there he has created TiFi Token that offers token rebates so people can get cash back when spending the token. Also he has built TiFi Bank which is a DeFi application that offers crypto saving, lending, trading, staking and liquidity management features. Samuel holds a Master Degree and a Bachelor Degree in Computer Science.
Read more about Samuel Zhou