soliditysmartcontractserc20bep20

Smart Contract - BEP20: transfer amount exceeds allowance


I'm new in solidity and I'm trying to swap tokens from "Address A" to "Address B".

I used the functions approve and transferFrom, but I'm still getting the error: "Error: VM Exception while processing transaction: reverted with reason string 'BEP20: transfer amount exceeds allowance'"

Could you please help me with this issue?

// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;

import "./CryptoPlinkoBall.sol";
import "./CryptoPlinko.sol";

import "hardhat/console.sol";

contract TokenSwap {
    address admin;
    address public owner;
    address private _token;

    constructor(address token) {
        admin = msg.sender;
        _token = token;
    }

    function swapTokens(address recipient, uint256 amount) external {
         BEP20(_token).approve(msg.sender, amount);
        BEP20(_token).allowance(msg.sender, address(this));
        BEP20(_token).transferFrom(msg.sender, recipient, amount);
    }

}

Solution

  • When you call BEP20(_token).approve(msg.sender, amount); you are approving the user to move that amount of tokens that the contract owns if you want to transfer the tokens from the user, the user should have called the token contract and approved the amount before calling this function, if you are doing the frontend that will interact with the contract you will need to put the call to the token contract first then the call to this contract