Building Full Stack DeFi Applications

Book description

Take your blockchain and Web3 development skills to the next level by building real-world full-stack DeFi applications with Solidity and JavaScript

Key Features

  • 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

Book 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

Who this book is for

If you are a blockchain developer experienced in Web3 and Solidity development, or anyone interested in learning about blockchain and DeFi technologies, this book is for you. Product managers, executives, and other management professionals looking to start or delve into a DeFi project will also benefit from this book, as will developers and architects with basic blockchain knowledge who want to advance their skills in building full-stack DeFi products. Experience with Solidity, JavaScript, and Web3 will help you get the most out of this book.

Table of contents

  1. Building Full Stack DeFi Applications
  2. Contributors
  3. About the author
  4. About the reviewer
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Conventions used
    6. Get in touch
    7. Share Your Thoughts
    8. Download a free PDF copy of this book
  6. Part 1: Introduction to DeFi Application Development
  7. Chapter 1: Introduction to DeFi
    1. What is DeFi?
      1. Characteristics of DeFi
      2. Understanding terminologies
    2. Overview of DeFi applications
      1. Decentralized exchanges
      2. Crypto loans
      3. Staking, yield farming, and liquidity mining
    3. Architecture of DeFi applications
      1. DeFi application frontend
      2. DeFi wallet
      3. RPC endpoint
      4. Interactions between blockchain and oracle
    4. Vulnerabilities of DeFi applications
      1. Reentrancy
      2. Self-destruct operation
      3. Gas overflow
      4. Random number manipulation
    5. Summary
    6. Further reading
  8. Chapter 2: Getting Started with DeFi Application Development
    1. Technical requirements
    2. Creating a DeFi project
      1. Installing Node.js
      2. Creating a project with create-react-app
      3. Installing and configuring Hardhat
    3. Writing, compiling, and deploying a smart contract in a local environment
      1. Writing and compiling a smart contract
      2. Bytecode and ABI
      3. Running a local EVM environment
      4. Deploying the smart contract
    4. Deploying a smart contract on Testnet
      1. Acquiring the RPC endpoint of Testnet
      2. Configuring the deployer account
      3. Smart contract deployment and verification
      4. Adding a deployment script to package.json
    5. Testing and debugging the smart contract
      1. Verifying smart contract with the Hardhat console
      2. Writing and running automated tests for smart contracts
      3. Debugging smart contracts with Hardhat
    6. Summary
    7. Further reading
  9. Chapter 3: Interacting with Smart Contracts and DeFi Wallets in the Frontend
    1. Technical requirements
    2. Overview of DeFi application frontend development
      1. Running the UI wireframe
    3. Deploying smart contract metadata to the frontend
    4. Connecting to a DeFi wallet
      1. The architecture of DeFi wallet connectivity with blockchain
      2. Implementing a wallet connection in the DeFi project
    5. Reading data from blockchain
    6. Making transactions on blockchain
    7. Summary
  10. Part 2: Design and Implementation of a DeFi Application for Trading Cryptos
  11. Chapter 4: Introduction to Decentralized Exchanges
    1. The three main types of DEXs
      1. AMMs
      2. Order book DEXs
      3. DEX aggregators
    2. The mathematics of AMMs
      1. Relation functions
      2. Constant Function Market Maker (CFMM)
      3. Liquidity mining and burning
      4. Impermanent loss
    3. The architecture of AMM
      1. Adding liquidity
      2. Removing liquidity
      3. Swapping
    4. Summary
  12. Chapter 5: Building Crypto-Trading Smart Contracts
    1. Implementing token pair smart contracts
      1. Creating the skeleton of a token pair
      2. Initializing token pairs
      3. Storing retrieving token reserves
      4. Transferring tokens safely
      5. Minting LP tokens
      6. Reward distribution for liquidity providers and DEX owners
      7. Minting LP tokens for the DEX owner’s reward
      8. Burning liquidity pool tokens
      9. Swapping token
      10. skim and sync
    2. Implementing pair factory smart contracts
      1. Introducing the smart contract source file
      2. Creating token pairs
      3. Retrieving addresses for token pairs
      4. Verifying the token pair factory
    3. Implementing AMM router smart contracts
      1. Liquidity provisioning
      2. Liquidity removal
      3. Swapping
    4. Verifying DEX smart contracts
      1. Deploying AMMRouter with a script
      2. Verifying smart contracts using the Hardhat console
    5. Summary
  13. Chapter 6: Implementing a Liquidity Management Frontend with Web3
    1. Implementing URL routes for liquidity management
    2. Retrieving liquidity information
      1. Checking whether the wallet is connected
      2. Getting LP tokens owned by a connected account
      3. Getting the pooled token amount and liquidity share percentage
      4. Finishing up the liquidity listing page
    3. Implementing the liquidity provisioning page
      1. Overview of the liquidity provisioning page
      2. Frontend workflow of liquidity provisioning
      3. Loading the token pair information from the search parameter
      4. Selecting tokens and providing token amounts
      5. Checking the allowance and increasing the allowance
      6. Interacting with smart contracts for adding liquidity
    4. Implementing the liquidity removal page
      1. Frontend workflow of liquidity removal
      2. Inputting the LP token amount
      3. Calculating pooled token amounts
      4. Getting the allowance, increasing the allowance, and removing liquidity
    5. Verifying liquidity management pages
    6. Summary
  14. Chapter 7: Implementing a Token-Swapping Frontend with Web3
    1. Overview of the token swapping frontend
      1. Frontend workflow of token swapping
      2. Preparing for the token swapping page
    2. Generating token swapping paths
      1. Building the graph for token pairs
      2. Finding all paths given a pair of tokens
      3. The default token pair
    3. Identifying the best path, price, and price Impact
      1. How does the best path change for different amounts?
      2. Why the reserve can be insufficient
      3. Calculating the receiving and spending amounts with code
      4. Calculating the price impact
    4. Swapping token – after a wallet is connected
    5. Improving user experiences for token swapping
    6. Summary
  15. Chapter 8: Working with Native Tokens
    1. Diving into the WETH smart contract
      1. Demystifying the WETH smart contract
      2. Verifying a WETH smart contract with the Hardhat console
    2. Refactoring smart contracts to support native tokens in a DEX
      1. The router as the intermediary
      2. Function definitions for native tokens in the router
      3. Improving AMMRouter to support the native token
      4. Implementing addLiquidityETH and removeLiquidityETH
      5. Implementing token-swapping functions to support ETH
    3. Implementing the DEX frontend for the native token
      1. Supporting the native token in the liquidity management pages
      2. Supporting the native token on the token-swapping page
    4. Summary
  16. Part 3: Building a DeFi Application for Staking and Yield Farming
  17. Chapter 9: Building Smart Contracts for Staking and Farming
    1. Understanding the architectures of staking and farming
      1. Two types of architectures for staking
    2. Calculating the reward for staking and farming
      1. Reward per block, starting block, and ending block
      2. Share, reward per share, and reward debt
    3. Implementing the staking pool smart contract
      1. Defining smart contract variables and implementing a constructor
      2. Updating the parameters for the staking pool
      3. Implementing the deposit and withdraw functions
      4. Implementing the utility functions of the staking pool
      5. Implementing the smart contract for staking pool management
    4. Verifying staking pool smart contracts
      1. Implementing the command to mine blocks with Hardhat
      2. Verifying staking pool smart contracts in the Hardhat console
    5. Summary
  18. Chapter 10: Implementing a Frontend for Staking and Farming
    1. Overview of frontend pages for staking and farming
    2. Implementing a staking pool listing dashboard
      1. Retrieve staking pools
      2. Use the accordion component to show the list
      3. Hide expired pools
    3. Implementing pages for creating staking pools and supplying rewards
      1. Improving the token selection modal component
      2. Implementing a page to create a staking pool
      3. Implementing a page for supplying rewards
    4. Implementing frontend components for deposits, withdrawals, and harvesting
      1. Deposit page for staking pools
      2. Withdrawal page for staking pools
      3. Implementing the harvest function
    5. Implementing the farming frontend
      1. Refactoring frontend code for farming
    6. Summary
  19. Part 4: Building a Crypto Loan App for Lending and Borrowing
  20. Chapter 11: An Introduction to Crypto Loans
    1. Technical requirements
    2. Exploring the characteristics of a crypto loan
      1. Zero waiting time for approval
      2. No credit checks
      3. No term constraints
      4. No requirement for selling out of crypto holdings
    3. Designing crypto loan smart contracts
      1. Crypto loan personas
      2. The architecture of a crypto loan smart contract
    4. Understanding interest rate model and pool configuration
      1. The borrowing interest rate and lending interest rate
      2. Demystifying the interest rate model
      3. The collateral rate
      4. The liquidation bonus rate
      5. Implementing the pool configuration smart contract
    5. Implementing an asset pool share and its deployer
      1. Introducing an asset pool share
      2. Implementing the asset pool share smart contract
      3. Implementing the asset pool share deployer
    6. Exploring a crypto loan system by example
      1. An introduction to Aave
      2. An Aave protocol version 2 overview
      3. New features in the Aave protocol version 3
    7. Summary
  21. Chapter 12: Implementing an Asset Pool Smart Contract for a Crypto Loan
    1. Technical requirements
    2. Implementing the code to manage the asset pools
      1. Pool status
      2. Pool management
      3. Pool parameter calculation
    3. Managing records in user ledgers
      1. Amount conversion between shares and asset tokens
      2. Retrieving user-lending and -borrowing information
      3. User account healthiness
    4. Implementing the functions for user requests
      1. Depositing
      2. Withdrawal
      3. Borrowing
      4. Repaying
      5. Liquidation
      6. Withdrawing the reserve
    5. Deploying and testing the crypto loan smart contracts
      1. Deploying crypto loan smart contracts
      2. Configuring asset pools for crypto loans
      3. Testing crypto loan smart contracts
    6. Summary
  22. Chapter 13: Implementing a Price Oracle for Crypto Loans
    1. How price manipulation attacks are carried out on crypto loan systems
      1. Executing a crypto loan exploit
      2. An example of attacking crypto loan systems with price manipulation
    2. Building an on-chain price oracle with cumulative prices
      1. Calculating cumulative prices
      2. Calculating time-weighted average prices
      3. Calculating prices with the moving window
    3. Implementing a manipulation-resistant price oracle smart contract
      1. Updating information when the reserve amount changes in a liquidity pool
      2. Information update for the current period in the price oracle
      3. Calculating the token price in the price oracle
    4. Deploying, maintaining, and verifying the price oracle
      1. Deploying the PriceOracleV2 smart contract
      2. Price oracle maintenance
      3. Verifying the manipulation-resistant price oracle
    5. Summary
  23. Chapter 14: Implementing the Crypto Loan Frontend with Web3
    1. Technical requirements
    2. Implementing the account summary and asset pool listing page
      1. Implementing the UI components in ListAssetPools.js
      2. Retrieving the user summary information for the crypto loan system
      3. Retrieving the information for all asset pools
    3. Implementing the pages for deposit, withdrawal, borrowing, and repayment
      1. Implementing the deposit page
      2. Implementing the withdrawal page
      3. Implementing the borrowing page
      4. Implementing the repayment page
    4. Best practices for decentralized crypto loan systems
      1. Select blue chip assets
      2. Liquidity utilization rate maintenance
      3. Monitoring and liquidating unhealthy accounts
      4. Closed asset pools
      5. Disabling the use of assets as collateral
    5. Summary
  24. Index
    1. Why subscribe?
  25. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share Your Thoughts
    3. Download a free PDF copy of this book

Product information

  • Title: Building Full Stack DeFi Applications
  • Author(s): Samuel Zhou
  • Release date: March 2024
  • Publisher(s): Packt Publishing
  • ISBN: 9781837634118