0

I am a solidity beginner of Remix-IDE. I want to transfer an ERC20 token from one of my account to another buy using contract. I can find the ERC20 token that I have transfered is in my contract. But when I transfer it to another account, I got an error:
ERC20: transfer amount exceeds allowance. Where is the problem?

pragma solidity >=0.6.0 <0.8.0;

interface IERC20 {
    function approve(address spender, uint256 amount) external returns (bool);  
  
    function transfer(address recipient, uint256 amount) external returns (bool);

    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    function allowance(address owner, address spender) external view returns (uint256);

    event Transfer(address indexed from, address indexed to, uint256 value);

    event Approval(address indexed owner, address indexed spender, uint256 value);
    
}


contract MyContract {

    address MyToken = 0x............;
    address MyAccount2 = 0x............;

    function Myfunction(uint256 amount) public 
    {

        require(amount > 0, 'zero amount');
        
        IERC20(MyToken).approve(msg.sender, amount); //OK
        IERC20(MyToken).transfer(address(this), amount); //OK
        IERC20(MyToken).allowance(msg.sender, address(this));//OK
        IERC20(MyToken).approve(address(this), amount); //OK 
        IERC20(MyToken).transferFrom(address(this), MyAccount2, amount);//Error

    }
}
0
1

You can send the ERC-20 tokens from account A to account B using a contract by following method:

// SPDX-License-Identifier: no license
pragma solidity ^0.8.6;

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

contract MyContract{

  function transferTokens(address token, address recipient, uint256 amount) payable external {
    IERC20 token_ = IERC20(token);
      token_.transferFrom(msg.sender, recipient, amount);
    }
  }
3
  • Thank you very much. I have tried it, but got the same error message.
    – Masa
    Oct 10 at 5:10
  • When you try to send tokens more than the allowance, then you get this error. Try to send the same amount of tokens. Oct 10 at 7:39
  • I only send 1/10 of the token in my wallet, but got the same ERROR.
    – Masa
    Oct 10 at 13:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.