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

Implementing a Token-Swapping Frontend with Web3

Token swapping is the key feature of liquidity pool-based decentralized exchanges (DEXs). Token swapping is the operation to exchange one token with another token. It enables people to buy or sell tokens on DEXs.

In Chapter 5, Building Crypto-Trading Smart Contracts you learned that token swapping is performed by an AMMRouter smart contract through interaction with smart contracts with the Hardhat console. Token swapping requires a user to transfer an amount of a token to a liquidity pool (the TokenPair smart contract) and the smart contract will transfer some other token from the liquidity pool back to the user. In this chapter, we will learn how to interact with smart contracts using JavaScript and implement the frontend of the token swapping feature.

Token swapping involves multiple liquidity pools if there are no token pairs for the two tokens for swapping. This may bring complexity for token swapping. However, we will show...

Overview of the token swapping frontend

Before implementing the code of the token swapping frontend, let’s introduce what we will build and the workflow of the token swapping frontend.

Similar to the liquidity management page, we will create a React /swap route for users to access the token swapping page. Figure 7.1 shows the snapshots of the token swapping page at different stages.

Figure 7.1 – The snapshots of the token swapping page at different stages

Figure 7.1 – The snapshots of the token swapping page at different stages

On the token swapping page, we allow the users to select a pair of tokens and provide the number of tokens they want to spend or want to receive for the swapping. After the pair of tokens and amounts are provided, the page will show the price for swapping, the price impact, and the best swapping path for the swapping operation. This information is calculated dynamically based on the amount for swapping and the reserves in existing liquidity pools. This page will also show an ENABLE <...

Generating token swapping paths

In this section, we will dive into the implementation of generating swapping paths. Similar to the liquidity provisioning page, AddLiquidity.js, which we discussed in Chapter 6, Implementing a Liquidity Management Frontend with Web3 we use the TokenSelectModal component for token selection. Once both tokens are selected, we will find all available paths from one token to another token. By reading this section, you will learn how to write the code to build the graph with the token pair information of a DEX, and how to find the swapping paths once after the tokens are selected.

Building the graph for token pairs

In order to find all available paths from spending tokens to receiving tokens, we can use the data structure of a bidirectional graph to represent all the token pairs of the DEX. The addresses of supported tokens of the DEX are the graph nodes, and all the token pairs (the smart contract instance of TokenPair that represents the paired tokens...

Identifying the best path, price, and price Impact

Best path, price, and price impact are three of the most important pieces of information before the user makes a decision for the transaction. If the price is not good or the price impact is too high, the user may not proceed with the transaction. The price and price impact are calculated based on the path the DeFi app selected. So, it is important to select a swapping path to make the deal. Compared to other paths that can make the swap, the best swapping path can do one of the following:

  • Receive more tokens when an amount of spending tokens is specified
  • Spend fewer tokens when an amount of receiving tokens is specified

Based on these principles, selecting the best path is determined by the following two types of factors:

  • The amounts of tokens in the reserves of the liquidity pools for every token pair along the path
  • The spending token amount or the receiving token amount specified by the user
...

Swapping token – after a wallet is connected

A user cannot perform token swapping without connecting to a wallet. After connecting to a wallet, the code needs to do the following checks before actually swapping the tokens:

  • Verify that the spending amount does not exceed the token balance in the wallet
  • Verify whether the account allows AMMRouter to transfer the spending amount to the liquidity pool (the instance of the TokenPair smart contract)

For balance verification, we can load the balances of the two tokens, similar to how we did for AddLiquidity.js, and disable the SWAP button when the balance is less than the spending amount.

For checking the allowance quota for AMMRouter to transfer the user’s token, we can check the allowed transferring amount by calling the allowance function of the ERC20 token, and compare the amount with the spending amount. If the allowed amount is less than the spending amount, the ENABLE button will show up, and the...

Improving user experiences for token swapping

Usually, a DEX implements several components to improve user experiences. In this section, we will discuss how to implement the following two components for the purpose:

  • The MAX button for the spending amount, which is useful when a user wants to sell all tokens in the wallet
  • The floating action button (FAB) for switching the spending and receiving tokens

Now, let’s implement the MAX button with this line of code:

<Button sx={{ fontSize: 12, padding: '0px' }}
  onClick={() => handleMax()} >Max</Button>

Once the button is clicked, it will call the handleMax function to set the amount to spend to all of the balance of the token. The function then calls setTokenIndex(indexTokenA) so that the swap operation knows the user is setting spending. The function will also call getReceivingAmount to update the receiving amount at the same time:

const handleMax = () => {
 ...

Summary

In this chapter, we have gone through the frontend workflow and the code of key features of the token swapping page. You have learned how to generate the graph by accessing the on-chain data with smart contracts, find the best prices for swapping tokens by iterating the graph, and interact with the AMMRouter smart contract to perform the token swapping.

We discussed liquidity management and token swapping for the tokens based on the existing blockchain till now. These tokens are also called non-native tokens and they follow a standard (e.g., ERC20), which is built on an existing layer 1 blockchain. However, a productionized DEX should support native tokens as well. The native token is also called a built-in token or native coin of a blockchain. For example, ETH is the native token of the Ethereum blockchain. To make native tokens such as ETH work with the DEXs or other DeFi smart contracts, we usually have to convert the native token to a wrapped token (such as Wrapped ETH...

lock icon
The rest of the chapter is locked
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