ERC-20 Transfer Function – Calling Transfer Function of an ERC-20 Contract

contract-development

I want to call the transfer function of any ERC-20 contract in my Smart Contract.
I have seen that i should use "callcode" in a similar way of https://gist.github.com/critesjosh/68593429fd2f84f8f55d4ff7b74f0323.

function callcodeSetNum(address c2, uint _num) public {
if(!c2.callcode(bytes4(sha3("setNum(uint256)")), _num)) revert(); // C1's num is set
}

I could reproduce inter-contract calls to one-parameter function. However, I always get a strange error when trying to call a function with more than one parameter (as is the case of transfer).

Error: transact to TW.callSetNum errored: VM error: revert.
revert The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value. Debug the transaction to get more information.

Anyone has a clue?
Thank you

Best Answer

Perhaps you're just looking for this?

interface IERC20Token {
    function transfer(address to, uint256 amount) external returns (bool);
    // add other functions here as you want
}

contract MyContract {
    function doIt(address tokenContract, address to, uint256 amount) {
        IERC20Token(tokenContract).transfer(to, amount);
    }
}

See also https://programtheblockchain.com/posts/2018/08/02/contracts-calling-arbitrary-functions/ for when you don't know the ABI in advance (and want to just pass message data from the client).

Related Topic