0

I want to receive an erc20 token as value for a function.
Basically, the function caller defines an amount which will then be transferred from their balance to the smart contract. Which transfer pattern should I use for this?

As an example, Why will this function not accept my ERC20 token input?

contract Transform {

    InputToken inputToken;
    OutputToken outputToken;

    event Transformed(address from, uint256 input, uint256 output);

    constructor(address _inputToken, address _outputToken) public {
    inputToken = InputToken(_inputToken); 
    outputToken = OutputToken(_outputToken); 
}

    function transformTokens(uint256 _amount) external payable {
        require(_amount > 0);

        uint256 input = _amount; //It's reverting here?? I don't see the issue
        uint256 rate = 1000;

        uint256 output = input.div(rate);
        uint256 excess;

        inputToken.transferFrom(msg.sender, address(this), input);
        outputToken.mint(msg.sender, output);

        Transformed(msg.sender, input, output);
    }
}
0

For a standard ERC20 this will not work

inputToken.transfer(address(this), input);

The contract is transferring tokens to itself.

To fix this you have to use transferFrom

inputToken.transferFrom(msg.sender, address(this), input);

For it to work the token's owner has to call approve to the contract address.

In javascript will be something like this

inputToken.methods.approve(contractAddress, amount, { from: tokenOwner });

Note: A contract cannot approve on behalf of someone else. Only the token's owner can call approve.

| improve this answer | |
  • Hi Ismael, I tried doing how you suggested. First I approve the contract by the msg.sender, and then I use transferFrom from within the function. However, I'm getting an error. I've commented in the code where it reverts, I'm not able to spot the problem? – NowsyMe May 5 at 20:35
  • @NowsyMe That is an unlikely place to revert, perhaps is the previous line. I'd suggest to deploy a new instance, or reload remix. – Ismael May 5 at 21:29
  • 1
    the problem was related to the math :) – NowsyMe May 6 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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