1

I need to use a contract to trigger a function and transfer the token of the msg.sender to (this) contract. I can do it with the "approve" function in the Token contract, but I can't do it with this contract it self.

Any idea?

pragma solidity ^0.4.18;

contract ERC20 {

    address public tokenAddr = (my token address);
    ERC20 public token;

    function transfer(address _to, uint256 _value) public returns(bool);
    function balanceOf(address tokenOwner) public constant returns (uint balance);
    function approve(address spender, uint256 value) public returns (bool);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function allowance(address owner, address spender) public view returns (uint256);
}

contract SAY is ERC20 {

    string word = 'Something';

    function SAYSOMETHING() public returns(string)  {

        token.approve(msg.sender, 500);
        token.transferFrom(msg.sender,this, 500);
        return word;
    }

}
9
  • I'm confused about what you're trying to do. It looks like you're trying to have the contract just take your tokens without you approveing it first? That, of course, can't be done. Could you explain the scenario better? – user19510 Feb 27 '18 at 2:54
  • I'm trying to make a function "payable" with tokens. – Vultur Feb 27 '18 at 7:05
  • For an account (including a contract) to call transferFrom, the owner of the tokens must first call approve. So the caller of SAYSOMETHING must first call tokenAddr.approve(SAY, tokenAmount). – user19510 Feb 27 '18 at 7:08
  • I can do that in the same function? – Vultur Feb 27 '18 at 7:12
  • 1
    No, the caller needs to call approve. The contract can't just give itself permission to take somebody's tokens. :-) – user19510 Feb 27 '18 at 7:13
1

As mentioned by smarx, the user needs to call the approve function outside of the contract, then the contract will be able to transfer tokens on the behalf of the user.

You could allow this with a slight change/addition to the ERC20 standard implementation. If the token you want to use is not yet defined, I would explore this option as well.

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.