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 &gt; 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

}

}

Masa
  • 1
  • 1

1 Answers1

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

Umair Janjua
  • 175
  • 4