// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./TokenA.sol";
import "./TokenB.sol";
contract TokenSwap{
TokenA public tokenA;
TokenB public tokenB;
address public admin;
uint public fees;
event swap(string from, string to,uint indexed amt);
//stores the exchange rates of two tokens
mapping(string=>mapping(string=>uint))exchangeRates;
constructor(address _tokenA,address _tokenB,uint256 _exchangeRateAtoB,uint256 _exchangeRateBtoA)
{
admin=msg.sender;
tokenA=TokenA(_tokenA);
tokenB=TokenB(_tokenB);
exchangeRates["A"]["B"]=_exchangeRateAtoB;
exchangeRates["B"]["A"]=_exchangeRateBtoA;
// approve
tokenA.approve(address(this),tokenA.totalSupply());
tokenB.approve(address(this),tokenB.totalSupply());
}
modifier onlyAdmin()
{
require(msg.sender==admin,"Only admin can call this function");
_;
}
function setPlatformFees(uint256 fee) public onlyAdmin returns(uint)
{
fees=fee;
return fees;
}
function swapAtoB(uint amount) public
{
require(amount>0,"amount must be greater than zero");
require(tokenA.balanceOf(msg.sender)>=amount,"Not enough tokens are present");
uint exchangeRate=exchangeRates["A"]["B"];
uint exchangeAmtB=(amount*exchangeRate)/100;
// fees is deducted as defi platform fee
uint AmtToTransfer= exchangeAmtB - fees;
require(AmtToTransfer>0,"amt must be greater than zero");
require(tokenB.balanceOf(address(this))>AmtToTransfer,"Not enough tokenB to make the swap");
//exchanges
tokenA.transferFrom(msg.sender,address(this),amount);
tokenB.approve(msg.sender,AmtToTransfer);
tokenB.transferFrom(address(this),msg.sender,AmtToTransfer);
emit swap("tokenA","tokenB",AmtToTransfer);
}
function swapBtoA(uint amount) public
{
require(amount>0,"amount must be greater than zero");
require(tokenB.balanceOf(msg.sender)>=amount,"Not enough tokens are present");
uint exchangeRate=exchangeRates["B"]["A"];
uint exchangeAmtA=(amount*exchangeRate)/100;
// fees is deducted as defi platform fee
uint AmtToTransfer= exchangeAmtA - fees;
require(AmtToTransfer>0,"amt must be greater than zero");
require(tokenA.balanceOf(address(this))>AmtToTransfer,"Not enough tokenB to make the swap");
//exchanges
tokenB.transferFrom(msg.sender,address(this),amount);
tokenA.approve(msg.sender,AmtToTransfer);
tokenA.transferFrom(address(this),msg.sender,AmtToTransfer);
emit swap("tokenB","tokenA",AmtToTransfer);
}
}
Error while calling swapAtoB
transact to TokenSwap.swapAtoB errored: Error occured: revert.
revert
The transaction has been reverted to the initial state.
Reason provided by the contract: "ERC20: insufficient allowance".
Debug the transaction to get more information.