[Ethereum] How to use erc20 transfer in another contract in remix ethereum using metamask

erc-20metamaskremixtransferfrom

I read a lot of documentation in here and another web pages, I have a question and I so tried to solved but nothing works for me.

I am using this example.

It works fine with truffle, but I don't know what I need to do to make this work fine using metamask.

The problem is the next:

  • Create a ERC20 Token // works
  • Import the IRC20 Token Contract to Another Contract Named "TokenReceiver" // I think I do correctly, I only copy and paste to test in remix ethereum.
  • Deploy, Use doStuff function into the new Contract "TokenReceiver" // Error here

The error says:

Gas estimation errored with the following message (see below). The
transaction execution will likely fail. Do you want to force sending?
gas required exceeds allowance (10000000) or always failing
transaction

The code is the same:

pragma solidity ^0.5.0;

import "./IERC20.sol";

/**
 * @title TokenReceiver
 * @dev Very simple example of a contract receiving ERC20 tokens.
 */
contract TokenReceiver {

    IERC20 private _token;

    event DoneStuff(address from);

    /**
     * @dev Constructor sets token that can be received
     */
    constructor (IERC20 token) public {
        _token = token;
    }

    /**
     * @dev Do stuff, requires tokens
     */
    function doStuff() external {

        address from = msg.sender;

        _token.transferFrom(from, address(this), 1000);

        emit DoneStuff(from);

    }
}

I read a lot but I really know I am doing something wrong but I don't know what it is, reading I see that I need to approve the function before using transfer, but nothing works for me, I am trying do this and the error is the same and I don't see the approve window with metamask:

function doStuff() external {

    address from = msg.sender;

    _token.approve(from,1000); // i trying adding this line

    _token.transferFrom(from, address(this), 1000);

    emit DoneStuff(from);

}

Somebody help me please, it is hard for me to understand what's happening but I really want to know what I am doing wrong.

Best Answer

First of all, get rid of this (executed inside your TokenReceiver contract):

address from = msg.sender;
_token.approve(from,1000);

It allows msg.sender to transfer tokens from your contract, and not the other way round as you would hope (and it's not something that you should hope for anyway, because if that was the case then anyone could steal your tokens at will).


Second, before calling your doStuff function, you need to execute the following transaction outside your contract (e.g., using Remix, MyEtherWallet, Web3.js, Web3.py, etc):

_token.approve(yourTokenReceiverContractAddress,1000);

And you need to execute this transaction using the account which you are using for your other actions (contract deployment, etc).

Related Topic