4

A CrowdSale contract usually receives Ether in exchange of certain token. Is it possible to make it backwards? To receive certain token and give an amount of ether in exchange? Is as simple as changing positions of the variables in my code or it's a little bit more complicated?

5

It's slightly more complicated because users don't just send you tokens. They have to first give you allowance to spend the token, then they call your function (say tokenToEther())

First your user would call this function on the token contract, assuming the contract implements ERC-20 interface.

function approve(address _spender, uint256 _value) returns (bool success);

The spender would be your contract, the value would be however much they wish to spend, to receive ether from your contract.

Then your user would call function on your contract

function tokenToEther() returns (bool success);

The way you handle it in your contract is pretty simple if you understand ERC-20 interface. Something like

require(myToken.allowance(msg.sender, this) > 0);
uint tokenAmount = myToken.allowance(msg.sender, this);
require(myToken.transferFrom(msg.sender, this, tokenAmount));
msg.sender.transfer(getRate(tokenAmount));

The above code makes some important assumptions:

  • The myToken is a contract address, which is some kind of ERC-20 compatible token
  • Your sender must give allowance to your contract first, otherwise require will fail
  • Your contract will take all the allowance, transferring it to your contract.
  • Your contract will be the owner of the transferred tokens. Make sure you write a withdraw function or tokens will get locked up in your contract!
  • Great, your answer is very clear and I think it would help me a lot. Just one extra question: For the sender to give me allowance, it would be enough if he send me tokens in the traditional way, I mean, when I exchange tokens with someone, lets say someone sends me BAT token, he just need to send them to my address, that would be a kind of allowance approval? Wrapping it: when the user sends tokens to my contract is a way to give me allowance? Or he must specifically use approve function? – Moisés Briseño Estrello Nov 12 '17 at 23:47
  • 1
    Approve and transfer are different. The reason approve exists is that the users don't have to trust you to send them ether. If you want your contract to send tokens to you once tokenToEther is called, you can use transferFrom to transfer tokens to you instead of the contract itself – libertylocked Nov 13 '17 at 3:14

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.