1

If someone sends tokens and eth to a contact, is there anyway to create a function that will transfer any and all tokens or eth to owner address?

function sendEverything()
public 
{
   owner.transfer(this.balance);
   owner.transfer(this.allthetokens);
}

In other words is there a generalized way to send any and all erc20 tokens, for instance even if the erc20 contract was created after my contract?

6

Sending the eth contained in a contract to another account (be it an account or another contract) is pretty straightforward:

beneficiary.transfer(this.balance);

will do the trick.

As for tokens, it is not that simple. Tokens don't reside in your own contract. They re kept in a balance inside the token contract. You (or your contract) just happen to have access to part of those tokens.

For your contract to be able to transfer the token it owns to another account or contract, you would have to call the following ERC20 function inside your contract.

function transfer(address _to, uint _value) returns (bool success);

This will work from the contract as long as it is the actual owner of those tokens.

If you wanted to have your contract transfer tokens owned by someone else, that someone else would have to give your contract an allowance first and then your contract would have to call transferFrom.

function approve(address _spender, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);

For your contract to be able to refund tokens that were sent to it by mistake, it would have to implement a function similar to this:

function refundTokens(address _token, address _refund, uint _value) onlyOwner {
    require(_token != this);
    ERC20 token = ERC20(_token);
    token.transfer(_refund, _value);
    RefundTokens(_token, _refund, _value);
  }
  • So there is no general way to send the erc20 token even if i know nothing about the contract with those tokens? For instance if the erc20 contract was created after my contract? – Victory Nov 16 '17 at 22:13
  • 1
    Your contract is the only one that can transfer tokens it owns. If those tokens were sent to it, and it doesn't have a function to send those tokens to another address, they are stuck within the contract forever. Here's a discussion regarding this subject: reddit.com/r/ethereum/comments/60ql37/… – pabloruiz55 Nov 16 '17 at 22:32

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.