1

Need a smart contract to exchange ERC20 for Ether and Ether for ERC20.

The goal is, you send ether you get erc20, you send erc20 you get ether back. Without having to use web3 tools.

The only way I can think for implementation is to use the ERC20 itself as exchange contract.

Then the token address will have to hold both ether and its own tokens.

This sounds like bad practice, or is it? Any better idea to achieve that?

2
  • Not sure if this is actually doable without web3 tools (to pass method parameters) and some sort of Oracle (if the price of the token is dynamic).
    – ReyHaynes
    Commented Feb 1, 2018 at 22:03
  • 1
    Mate, where you able to build this one? Commented Aug 12, 2018 at 4:13

1 Answer 1

2

You can certainly combine them, but I think it makes more sense to have a second contract. That way the ERC20 token contract stays simple and focused on just the token interface.

The contract doing the selling just needs two functions that deal with the token contract. In pseudocode, ignoring error checking, etc.

buyTokens():
    howMany = msg.value / pricePerToken * 10**decimals
    tokenContract.transfer(msg.sender, howMany)

sellTokens(howMany):
    // Caller will need to first approve() that many tokens
    tokenContract.transferFrom(msg.sender, howMany * 10**decimals)

    msg.sender.transfer(howMany * pricePerToken)
2
  • the idea was to make it simple for user just to send tokens to the sell address. With the sellTokens above sounds like user need to web3 to pass the parameter.
    – Nabil Sham
    Commented Feb 1, 2018 at 19:50
  • To transfer tokens to an address, some tools has to be used that knows how to pass parameters. If you want to piggyback on the existing transfer(address,uint256) function in an ERC20 token, then you would indeed need to put special code in there. ERC223 calls a tokenFallback in function if the destination is a smart contract... you could perhaps implement that or something like it..
    – user19510
    Commented Feb 1, 2018 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.