Building Full Stack DeFi Applications - Samuel Zhou - E-Book

Building Full Stack DeFi Applications E-Book

Samuel Zhou

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 614

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Building Full Stack DeFi Applications

A practical guide to creating your own decentralized finance projects on blockchain

Samuel Zhou

Building Full Stack DeFi Applications

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kaustubh Manglurkar

Publishing Product Manager: Apeksha Shetty

Book Project Manager: Hemangi Lotlikar

Content Development Editor: Manikandan Kurup

Technical Editor: Rahul Limbachiya

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Vijay Kamble

Senior DevRel Marketing Executive: Nivedita Singh

First published: March 2024

Production reference: 1080324

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83763-411-8

www.packtpub.com

To the moon, not the dream.

– Samuel Zhou

Contributors

About the author

Samuel Zhou is the founder of TiFi, which is a Silicon Valley-based company that builds decentralized e-commerce platforms on blockchain. He built a DeFi ecosystem that offers crypto saving, lending, trading, staking, and liquidity management features. Before starting the venture in 2022, Samuel worked for 15 years as a full stack engineer and software architect for top companies in Silicon Valley. He started exploring blockchain and Web3 in 2018. He has extensive experience in building smart contracts and Web3 applications. Samuel has two US patents under his name. He also holds a master’s degree and a bachelor’s degree in computer science.

I want to thank the people who have been close to me and supported me, especially my wife, Tina, and my little boy, who smiles, cries, and makes me a happy dad.

To all the people who motivated me to write the book and the team at Packt for their help and support throughout the process.

About the reviewer

Ankur Daharwal is a seasoned blockchain expert, dedicating more than seven years to pioneering innovative Web3 solutions. Embarking on his blockchain journey at IBM Blockchain Garage in 2016, he led transformative global projects in asset management, value exchange, and traceability. Ankur’s influence extends to leadership roles in prestigious institutions, including the ISO TC307 DLT standards technical committee and the IIB Council Blockchain Advisory Board, highlighting his commitment to industry standards. Fueled by a passion for solving real-world challenges and seamlessly integrating Web3 solutions, his emphasis on trust, transparency, and enhanced user experience is evident in his contributions to the blockchain domain.

Table of Contents

Preface

Part 1: Introduction to DeFi Application Development

1

Introduction to DeFi

What is DeFi?

Characteristics of DeFi

Understanding terminologies

Overview of DeFi applications

Decentralized exchanges

Crypto loans

Staking, yield farming, and liquidity mining

Architecture of DeFi applications

DeFi application frontend

DeFi wallet

RPC endpoint

Interactions between blockchain and oracle

Vulnerabilities of DeFi applications

Reentrancy

Self-destruct operation

Gas overflow

Random number manipulation

Summary

Further reading

2

Getting Started with DeFi Application Development

Technical requirements

Creating a DeFi project

Installing Node.js

Creating a project with create-react-app

Installing and configuring Hardhat

Writing, compiling, and deploying a smart contract in a local environment

Writing and compiling a smart contract

Bytecode and ABI

Running a local EVM environment

Deploying the smart contract

Deploying a smart contract on Testnet

Acquiring the RPC endpoint of Testnet

Configuring the deployer account

Smart contract deployment and verification

Adding a deployment script to package.json

Testing and debugging the smart contract

Verifying smart contract with the Hardhat console

Writing and running automated tests for smart contracts

Debugging smart contracts with Hardhat

Summary

Further reading

3

Interacting with Smart Contracts and DeFi Wallets in the Frontend

Technical requirements

Overview of DeFi application frontend development

Running the UI wireframe

Deploying smart contract metadata to the frontend

Connecting to a DeFi wallet

The architecture of DeFi wallet connectivity with blockchain

Implementing a wallet connection in the DeFi project

Reading data from blockchain

Making transactions on blockchain

Summary

Part 2: Design and Implementation of a DeFi Application for Trading Cryptos

4

Introduction to Decentralized Exchanges

The three main types of DEXs

AMMs

Order book DEXs

DEX aggregators

The mathematics of AMMs

Relation functions

Constant Function Market Maker (CFMM)

Liquidity mining and burning

Impermanent loss

The architecture of AMM

Adding liquidity

Removing liquidity

Swapping

Summary

5

Building Crypto-Trading Smart Contracts

Implementing token pair smart contracts

Creating the skeleton of a token pair

Initializing token pairs

Storing retrieving token reserves

Transferring tokens safely

Minting LP tokens

Reward distribution for liquidity providers and DEX owners

Minting LP tokens for the DEX owner’s reward

Burning liquidity pool tokens

Swapping token

skim and sync

Implementing pair factory smart contracts

Introducing the smart contract source file

Creating token pairs

Retrieving addresses for token pairs

Verifying the token pair factory

Implementing AMM router smart contracts

Liquidity provisioning

Liquidity removal

Swapping

Verifying DEX smart contracts

Deploying AMMRouter with a script

Verifying smart contracts using the Hardhat console

Summary

6

Implementing a Liquidity Management Frontend with Web3

Implementing URL routes for liquidity management

Retrieving liquidity information

Checking whether the wallet is connected

Getting LP tokens owned by a connected account

Getting the pooled token amount and liquidity share percentage

Finishing up the liquidity listing page

Implementing the liquidity provisioning page

Overview of the liquidity provisioning page

Frontend workflow of liquidity provisioning

Loading the token pair information from the search parameter

Selecting tokens and providing token amounts

Checking the allowance and increasing the allowance

Interacting with smart contracts for adding liquidity

Implementing the liquidity removal page

Frontend workflow of liquidity removal

Inputting the LP token amount

Calculating pooled token amounts

Getting the allowance, increasing the allowance, and removing liquidity

Verifying liquidity management pages

Summary

7

Implementing a Token-Swapping Frontend with Web3

Overview of the token swapping frontend

Frontend workflow of token swapping

Preparing for the token swapping page

Generating token swapping paths

Building the graph for token pairs

Finding all paths given a pair of tokens

The default token pair

Identifying the best path, price, and price Impact

How does the best path change for different amounts?

Why the reserve can be insufficient

Calculating the receiving and spending amounts with code

Calculating the price impact

Swapping token – after a wallet is connected

Improving user experiences for token swapping

Summary

8

Working with Native Tokens

Diving into the WETH smart contract

Demystifying the WETH smart contract

Verifying a WETH smart contract with the Hardhat console

Refactoring smart contracts to support native tokens in a DEX

The router as the intermediary

Function definitions for native tokens in the router

Improving AMMRouter to support the native token

Implementing addLiquidityETH and removeLiquidityETH

Implementing token-swapping functions to support ETH

Implementing the DEX frontend for the native token

Supporting the native token in the liquidity management pages

Supporting the native token on the token-swapping page

Summary

Part 3: Building a DeFi Application for Staking and Yield Farming

9

Building Smart Contracts for Staking and Farming

Understanding the architectures of staking and farming

Two types of architectures for staking

Calculating the reward for staking and farming

Reward per block, starting block, and ending block

Share, reward per share, and reward debt

Implementing the staking pool smart contract

Defining smart contract variables and implementing a constructor

Updating the parameters for the staking pool

Implementing the deposit and withdraw functions

Implementing the utility functions of the staking pool

Implementing the smart contract for staking pool management

Verifying staking pool smart contracts

Implementing the command to mine blocks with Hardhat

Verifying staking pool smart contracts in the Hardhat console

Summary

10

Implementing a Frontend for Staking and Farming

Overview of frontend pages for staking and farming

Implementing a staking pool listing dashboard

Retrieve staking pools

Use the accordion component to show the list

Hide expired pools

Implementing pages for creating staking pools and supplying rewards

Improving the token selection modal component

Implementing a page to create a staking pool

Implementing a page for supplying rewards

Implementing frontend components for deposits, withdrawals, and harvesting

Deposit page for staking pools

Withdrawal page for staking pools

Implementing the harvest function

Implementing the farming frontend

Refactoring frontend code for farming

Summary

Part 4: Building a Crypto Loan App for Lending and Borrowing

11

An Introduction to Crypto Loans

Technical requirements

Exploring the characteristics of a crypto loan

Zero waiting time for approval

No credit checks

No term constraints

No requirement for selling out of crypto holdings

Designing crypto loan smart contracts

Crypto loan personas

The architecture of a crypto loan smart contract

Understanding interest rate model and pool configuration

The borrowing interest rate and lending interest rate

Demystifying the interest rate model

The collateral rate

The liquidation bonus rate

Implementing the pool configuration smart contract

Implementing an asset pool share and its deployer

Introducing an asset pool share

Implementing the asset pool share smart contract

Implementing the asset pool share deployer

Exploring a crypto loan system by example

An introduction to Aave

An Aave protocol version 2 overview

New features in the Aave protocol version 3

Summary

12

Implementing an Asset Pool Smart Contract for a Crypto Loan

Technical requirements

Implementing the code to manage the asset pools

Pool status

Pool management

Pool parameter calculation

Managing records in user ledgers

Amount conversion between shares and asset tokens

Retrieving user-lending and -borrowing information

User account healthiness

Implementing the functions for user requests

Depositing

Withdrawal

Borrowing

Repaying

Liquidation

Withdrawing the reserve

Deploying and testing the crypto loan smart contracts

Deploying crypto loan smart contracts

Configuring asset pools for crypto loans

Testing crypto loan smart contracts

Summary

13

Implementing a Price Oracle for Crypto Loans

How price manipulation attacks are carried out on crypto loan systems

Executing a crypto loan exploit

An example of attacking crypto loan systems with price manipulation

Building an on-chain price oracle with cumulative prices

Calculating cumulative prices

Calculating time-weighted average prices

Calculating prices with the moving window

Implementing a manipulation-resistant price oracle smart contract

Updating information when the reserve amount changes in a liquidity pool

Information update for the current period in the price oracle

Calculating the token price in the price oracle

Deploying, maintaining, and verifying the price oracle

Deploying the PriceOracleV2 smart contract

Price oracle maintenance

Verifying the manipulation-resistant price oracle

Summary

14

Implementing the Crypto Loan Frontend with Web3

Technical requirements

Implementing the account summary and asset pool listing page

Implementing the UI components in ListAssetPools.js

Retrieving the user summary information for the crypto loan system

Retrieving the information for all asset pools

Implementing the pages for deposit, withdrawal, borrowing, and repayment

Implementing the deposit page

Implementing the withdrawal page

Implementing the borrowing page

Implementing the repayment page

Best practices for decentralized crypto loan systems

Select blue chip assets

Liquidity utilization rate maintenance

Monitoring and liquidating unhealthy accounts

Closed asset pools

Disabling the use of assets as collateral

Summary

Index

Other Books You May Enjoy

Preface

Decentralized Finance (DeFi) is one of the most popular technologies of the Web3 era. It incentivizes people to come to the world of blockchain for investment and makes blockchain the Internet of Money. Since Ethereum was born, there have been tremendous Decentralized Applications (DApps) built on top of various blockchain networks. DeFi applications constitute a giant share of DApps because of the innovation they bring and their ease of adoption by new users.

There are many resources that introduce the Web3 revolution, including elaborating the concepts and usage of DeFi applications. However, when interacting with various DeFi applications such as Decentralized Exchanges (DEXs) or crypto loan systems, users may be curious about the concepts involved (such as liquidity pools), the mathematics behind the scenes, and how they might build a profitable DeFi application. This book will reveal the mystery and make you an expert in building various DeFi applications.

After exploring various DeFi applications on the market, I found that DeFi jargon and applications usually come from simple mathematics and classic financial principles. If you have an engineering background, it will be easier for you to dive in and implement DeFi concepts with code once you understand the underlying principles.

In this book, you will explore some of the most popular DeFi applications. For every DeFi application, you will start by learning what it is, how it works with the aid of mathematical formulas and architecture diagrams, and then implement the core – the math and the business logic – and finally, you will see how we wrap the core with UI code to make it a ready-to-use application.

There are thousands of DeFi projects on the market that offer various applications and continue to empower blockchain as the Internet of Money. A lot of traditional companies are approaching Web3 and especially applying DeFi to monetize their products and acquire customers. Meanwhile, Web3-native projects and start-ups are still booming. This book will help you gain practical experience in building and adopting DeFi and Web3 technologies for your projects and businesses.

Who this book is for

Whether you have DeFi experience or not, you will gain practical skills with experience of building full stack applications. Even if you have no experience in programming, this book will help you to understand how various DeFi applications work and how to build these features from a high-level view.

There are four main personas that are the target audience of the book:

Web3 developers who want to advance their knowledge of DeFi and gain hands-on experience with DeFi applicationsSoftware engineers who are not familiar with DeFi or Web3 but want to dive into the area and learn how to build DeFi applicationsDeFi application users and crypto investors who want to learn how DeFi works and use DeFi products to optimize their return on investmentEntrepreneurs seeking to introduce DeFi features into their business or wanting to learn how to monetize DeFi applications

What this book covers

Chapter 1, Introduction to DeFi, explores the main characteristics of DeFi and introduces some of the popular DeFi applications. It also discusses the general architecture of DeFi applications, uncovers possible vulnerabilities in DeFi applications, and provides solutions.

Chapter 2, Getting Started with DeFi Application Development, shows how to create a starter DeFi project with an ERC20 token smart contract using the Solidity programming language that will run on Ethereum Virtual Machine (EVM). You will learn how to use Hardhat to compile, deploy, and debug the smart contract.

Chapter 3, Interacting with Smart Contracts and DeFi Wallets in the Frontend, guides you through building the frontend of DeFi applications with Node.js, React.js, and Material UI. You will also learn how to write code for interacting with smart contracts and connecting DeFi wallets to your applications to call smart contract functions.

Chapter 4, Introduction to Decentralized Exchanges, introduces different types of DEX. It dives into Automated Market Maker (AMM), which is a type of DEX we will build in this book. Meanwhile, we will explore the mathematics principles and the architecture of AMM.

Chapter 5, Building Crypto-Trading Smart Contracts, explores how to write smart contracts for token swapping, liquidity pool minting, and liquidity pool burning for a Constant Product Market Maker (CPMM), which is one of the most popular types of AMM on the market. By reading through the chapter, you will also learn how to deploy and verify smart contracts.

Chapter 6, Implementing a Liquidity Management Frontend with Web3, guides you through the process of building a frontend for liquidity management, including adding and removing liquidity. You will learn how to use ethers.js to interact with the smart contracts implemented in Chapter 5, Building Crypto-Trading Smart Contracts.

Chapter 7, Implementing a Token-Swapping Frontend with Web3, explores how to write the code for the frontend for the user to perform token swapping. Besides that, this chapter also discusses and implements code to find the swapping path between any pair of tokens in the DEX using a graph and explores how to calculate the price impact for each swapping.

Chapter 8, Working with Native Tokens, discusses how to deal with the native tokens of a blockchain network in smart contracts. It also shows you how to support native tokens in the smart contracts. Meanwhile, this chapter also implements improvements to the frontend code from Chapter 6, Implementing a Liquidity Management Frontend with Web3 and Chapter 7, Implementing a Token-Swapping Frontend with Web3 to support native tokens.

Chapter 9, Building Smart Contracts for Staking and Farming, explains the two DeFi features: of staking and farming by diving into the architecture and reward calculation. It also shows how to implement and verify smart contracts for staking and farming.

Chapter 10, Implementing a Frontend for Staking and Farming, guides you through the implementation of the staking pool listing dashboard, the pages for administrators to create staking, pool, and supply rewards, as well as the pages for users to deposit and withdraw tokens and harvest rewards.

Chapter 11, Introduction to Crypto Loans, introduces the characteristics of a crypto loan system and the architecture of the crypto loan smart contract we will build in this book. It also discusses the interest rate model we will use for our crypto loans, the concept of an asset pool, and the token to represent the shares of the asset pools.

Chapter 12, Implementing an Asset Pool Smart Contract for a Crypto Loan, explores the implementation of the most important component of a crypto loan system: asset pool smart contracts. By exploring this smart contract, you will learn how assets are managed and how user ledgers are implemented to keep track of lending and borrowing records.

Chapter 13, Implementing a Price Oracle for Crypto Loans, introduces and implements a price oracle smart contract based on the DEX implemented in Chapter 5, Building Crypto-Trading Smart Contracts. A price oracle is an essential component of a crypto loan system. After implementing the price oracle, the chapter also shows you how to deploy and run the price oracle for a crypto loan system.

Chapter 14, Implementing the Crypto Loan Frontend with Web3, discusses how to interact with the smart contracts in a crypto loan system with ethers.js. It guides you through the implementation of a crypto loan frontend, including the pages for displaying account summaries and asset pool information. Also, you will learn how to implement the pages for deposit, withdrawal, borrowing, and repayment by interacting with crypto loan smart contracts.

To get the most out of this book

You need to have basic knowledge of programming and building software to read through the code examples in this book. If you have some experience with Solidity, JavaScript, and/or React.js, you will have a smoother experience of learning with the book.

Software/hardware covered in the book

Operating system requirements

Solidity

Windows, macOS, or Linux

Node.js

Windows, macOS, or Linux

React.js

Windows, macOS, or Linux

Ethers.js

Windows, macOS, or Linux

Hardhat

Windows, macOS, or Linux

Material UI

Windows, macOS, or Linux

The book provides guidance to install and configure the software and tools whenever it is necessary. For now, it is totally fine if you have no idea what they are, because it won’t impact your understanding of the DeFi concepts we introduce in this book. But we highly encourage you to refer to the official documentation or communities for more information on these tools to help you while exploring the book.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Besides the code, the book also elaborates on several concepts in DeFi. We highly recommend you read the links in the Further reading sections in some of the chapters to learn the background and knowledge behind the concepts.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Building-Full-stack-DeFi-Application. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “First, let’s create a file called TokenPair.sol in the src/backend/contracts/ folder.”

A block of code is set as follows:

pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/ITokenPair.sol"; contract TokenPair is ITokenPair, ERC20 {

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<Routes>   <Route path='/' element={<TokenOperations />} />   <Route path='/liquidity/*' element={<LiquidityRouter />} /> </Routes>

Any command-line input or output is written as follows:

$ mkdir css $ cd css

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “To do that, you can click the icon on the top-right corner of the MetaMask plugin, go to Settings, click Advanced, click the Clear activity tab data button, and confirm the operation in the popup dialog.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

Share Your Thoughts

Once you’ve read Building Full Stack DeFi Applications, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781837634118

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Introduction to DeFi Application Development

In this first part, you will get an overview of Decentralized Finance (DeFi) and learn the generic architecture of DeFi applications. Building on the concepts you will learn, you will start building a DeFi application by creating a starter project. You will learn how to use Hardhat to build, deploy, and debug smart contracts written with Solidity, test smart contracts with JavaScript, interact with smart contracts from UI with Ethers.js and React.js, and the DeFi wallet connection with the UI.

This part has the following chapters:

Chapter 1, Introduction to DeFiChapter 2, Getting Started with DeFi Application DevelopmentChapter 3, Interacting with Smart Contracts and DeFi Wallets in the Frontend

1

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 conceptsLearn what people can do with several types of DeFi applicationsUnderstand the architecture of DeFi applicationsDiscover 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

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

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

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:

Where:

y is the APYr is the APRn 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:

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

Where:

y is the APYR is the earning rate of a single cyclen 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:

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

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

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

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

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

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

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