[Ethereum] How to transfer Ether to ERC20 token contract

ethersoliditytokens

I have a function that needs to make transfers to a token smart contract as well as personal accounts upon satisfaction of some conditions.

function completeSale() onlyOwner public {
        if (something == true && balance >= requested) {
            tokenContract.transfer(requested/100);
            seller.transfer(requested - (requested/100));
            buyer.transfer(balance - requested);
            assert(address(this).balance == 0);
            complete = true;
        }
    }

However, looking at the ERC20 standard, transfer is implemented as a token method:

 function transfer(address to, uint tokens) public returns (bool success) {
         balances[msg.sender] = balances[msg.sender].sub(tokens);
         balances[to] = balances[to].add(tokens);
         emit Transfer(msg.sender, to, tokens);
         return true;    }

How does one then transfer value in ether to an ERC20 smart contract? Is this possible without writing another function that then requires a low level call (i.e. tokenAddress.myPayMethod.value(x) or tokenAddress.call.value(x)())?

Best Answer

You don't generally do that. It's a matter of separation of concerns.

The OP didn't say exactly what the end goal is. A common scenario is a token contract and a crowdsale contract. Let each one do what they do and don't mix up concerns.

The ERC20 contract's job is to keep track of use balances and facilitate transfers. That's it. Anything beyond that is creeping beyond the concerns of minting/supply and basic accounting.

A CrowdSale would typically offer some tokens for sale at some (business rule) price. This "store" is "stocked" with merchandise (the tokens) and it sells, possibly buys in exchange for ETH. Thus, it has simple functions to accept Ether and transfer tokens that it has, and possibly a method to redeem tokens. It's not concerned with wallets. The ERC20 "minter" or "deployer" usually receives the initial supply and can safely store the tokens, periodically "restocking" the store as the tokens are sold.

Things will work out much simpler if the token contract is considered separately from whatever activities one might want to use it for.

Hope it helps.

Related Topic