-1

I want to implement the possibility to receive token after having sent eth to the contract. How can i do? Maybe i have to modify this function?

function () public payable {
    revert();   
}
alle.manfredi
  • 75
  • 1
  • 7

1 Answers1

0

You have left out one important detail: Is the token a different contract?

If we suppose that the token is in a separate contract and want to send 10 tokens for each ether contributted (I'm assuming the token has 18 decimals like ether)

ERC20 token; // <-- Token address assigned on the constructor for example.

function () public payable {
    // Received amount of ether
    uint amount = msg.value;
    // Convert to tokens
    uint tokens = amount * 10;
    // Transfer tokens assigned to this contract to sender
    token.transfer(msg.sender, tokens);
}

For the ERC20 contract interface you can use the OpenZeppelin implementation.

I'd recommend to take a look a the other contracts implemented by the OpenZeppelin team so you have a better idea how to program other things.

Ismael
  • 30,570
  • 21
  • 53
  • 96
  • i put your code inside the fallback function but when i try to transfer some eth i receive the following error: "value transfer did not complete most likely as a result of a revert opcode" – alle.manfredi Apr 07 '18 at 16:24
  • There are a lots of thing that can go wrong with that error message. Did you assign tokens to your contract with the fallback function? a contract can make transfer only when it was assigned enough tokens. Without a look at your code it is pretty difficult to determine the exact causes. I'd recommend to create a new question and putting a link to this one. – Ismael Apr 07 '18 at 23:40
  • https://ethereum.stackexchange.com/questions/45132/value-transfer-did-not-complete-most-likely-as-a-result-of-a-revert-opcode – alle.manfredi Apr 09 '18 at 09:38