How to Create a Token Swap dApp

Posted By : Prince

Mar 31, 2023

Token swaps specifically refer to the exchange of one token for another. This can occur on a DEX as a direct trade between two parties, where one party offers their token in exchange for another party's token. The swap is executed through a smart contract on the blockchain, which ensures that the transaction is secure and the tokens are exchanged correctly without the need for intermediaries or centralized authorities. As a result, they can be used for a variety of applications, including asset management, market-making, and liquidity management.

 

ERC20 is a standard for creating fungible tokens on the Ethereum blockchain. Fungible tokens are interchangeable and can be used for various purposes such as digital currencies, loyalty points, and asset tokens.

 

Token swaps are a type of trade that can occur on decentralized exchanges (DEXs), but they are not the only function of a DEX.

 

Now we'll go through the implementation of a basic token swap dApp on the Ethereum blockchain. We'll be using Solidity, a programming language specifically designed for Ethereum, and the Hardhat framework to set up our development environment. The smart contract we'll be building will enable users to exchange one ERC-20 token for another, based on a predefined exchange rate.

 

Creating a Token Swap dApp

 

Prerequisites:

 

  • Node.js (v12 or higher)
  • npm (Node.js package manager)
  • Hardhat
  • Basic knowledge of Ethereum and Solidity

 

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import "@openzeppelin/contracts/access/Ownable.sol";

 

contract TokenSwap is Ownable {

    using SafeERC20 for IERC20;

 

    mapping(address => bool) public tokens;

    mapping(address => mapping(address => uint256)) public exchangeRates;

    

    event Swap(address indexed _fromToken, address indexed _toToken, address indexed _user, uint256 _fromAmount, uint256 _toAmount);

 

function setExchangeRate(address _token1, address _token2, uint256 _rate1to2, uint256 _rate2to1) public onlyOwner {

  require(tokens[_token1], "Token not supported");

  require(tokens[_token2], "Token not supported");

  require(_token1 != _token2, "Cannot swap same token");

  exchangeRates[_token1][_token2] = _rate1to2;

  exchangeRates[_token2][_token1] = _rate2to1;

}

 

 

    function addToken(address _tokenAddress) public onlyOwner {

        require(_tokenAddress != address(0), "Invalid token address");

        tokens[_tokenAddress] = true;

    }

 

    function removeToken(address _tokenAddress) public onlyOwner {

        require(_tokenAddress != address(0), "Invalid token address");

        tokens[_tokenAddress] = false;

    }

 

    function swap(address _fromToken, address _toToken, uint256 _fromAmount) public {

        require(tokens[_fromToken], "Token not supported");

        require(tokens[_toToken], "Token not supported");

        require(_fromToken != _toToken, "Cannot swap same token");

 

        uint256 toAmount = _fromAmount * exchangeRates[_fromToken][_toToken];

 

        IERC20 fromToken = IERC20(_fromToken);

        IERC20 toToken = IERC20(_toToken);

 

        fromToken.safeTransferFrom(msg.sender, address(this), _fromAmount);

        toToken.safeTransfer(msg.sender, toAmount);

 

        emit Swap(_fromToken, _toToken, msg.sender, _fromAmount, toAmount);

    }

    function getExchangeRate(address _fromToken, address _toToken) public view returns(uint256) { 

require(tokens[_fromToken], "Token not supported");

        require(tokens[_toToken], "Token not supported");

        require(_fromToken != _toToken, "Cannot swap same token");

  return exchangeRates[_fromToken][_toToken];

}

}

 

setExchangeRate:

 

This function is used to set the exchange rate between two tokens. It can only be called by the owner of the contract and requires that the tokens being swapped are supported and that they are not the same token. The exchange rate is set in the exchangeRates mapping.

 

addToken:

 

This function is used to add a token to the list of supported tokens. It can only be called by the owner of the contract and requires a valid token address.

 

removeToken:

 

This function is used to remove a token from the list of supported tokens. It can only be called by the owner of the contract and requires a valid token address.

 

swap:

 

This function is used to swap one token for another. It requires that both tokens are supported and that they are not the same token. It also requires that the user has a sufficient balance of the fromToken to swap and that the contract has sufficient liquidity of the toToken. The swap is executed by transferring the fromToken from the user to the contract and then transferring the corresponding amount of toToken from the contract to the user.

 

getExchangeRate:

 

This function retrieves the exchange rate between two tokens, given their respective token addresses. However, it's important to note that this functionality can only be utilized if the platform supports both the _fromToken and _toToken.

 

To build the front end of the token swap dApp, we can use any web development framework or library like React, Angular, Vue.js, etc. The front should allow users to connect their wallet, select the tokens they want to swap, input the amount to be swapped, and execute the transaction by calling the swap function on the smart contract. To interact with the smart contract, we can use the web3.js or ethers.js library, which allows us to interact with the Ethereum blockchain from a JavaScript environment. We can use a web3 provider like Metamask to connect the front end to the blockchain. With this setup, users can seamlessly swap tokens on the blockchain through our dApp's user-friendly interface.

 

You may also like to read | Interacting with Ethereum Smart Contracts through Web3.js Library

 

If you already have a project in mind or want to discuss anything related to dApp development, you may connect with our skilled smart contract developer


 

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

November 18, 2024 at 03:09 pm

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button

Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text