Solidity – How to Send ERC20 Automatically from Contract to Beneficiary Upon Receiving

erc-20remixsolidity

I want to send both ether and ERC20 automatically from contract address to beneficiary. Following is the code that I've written to send ether –

contract FundTrans {    
    address owner;    
    constructor () public {
        owner = msg.sender;
    }    
    mapping (address => uint256) balances;    
    function () payable private {
       owner.transfer(msg.value);
    }    
}

I don't know how this will work for erc20. And if there are any improvements or correction in the current code please do give me suggestion.

Thanks in advance

Best Answer

Your code will send the ether sent to the contract to the owner. make your fallback public.

function () payable public {
       owner.transfer(msg.value);
    }    

This won't work for tokens sent to the contract. You will need to use the method approveAndCall on the ERC20. Problem is that not all ERC20 contracts implement approveAndCall.

If the function is implemented as described in the ethereum ERC20 standard wiki, your users should execute the function approveAndCall (see link above) in the token contract.

You should implement the following function in your contract.

function receiveApproval(address from, uint256 tokens, address token, bytes data) public {
    TokenERC20 tokenInstance =  TokenERC20(token);
    tokenInstance.transferFrom(from, owner, tokens);
}

As you can see, the annoying part here is that simply transferring the tokens to the contract won't work, because your contract will not know about the transfer and you will have to implement a function to manually check the balance and send the available tokens to your account. That is why the users will have to do approveAndCall which approve a number of tokens of a particular user to be moved by you and then calls you contract to let it know about the transfer.

Hope this helps.