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?
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
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:
myTokenis a contract address, which is some kind of ERC-20 compatible token
- Your sender must give allowance to your contract first, otherwise
- 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!