Bruno Massaro
Bruno Massaro

Reputation: 3

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);
    }

}

Upvotes: 0

Views: 6583

Answers (2)

jhonny
jhonny

Reputation: 858

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

Upvotes: 1

Julissa DC
Julissa DC

Reputation: 259

The approve must be mined before the transferFrom gets called.You can't do both on the same call, meanning the approve should occur before going into the swapTokens function.

Upvotes: 0

Related Questions