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 {

closed as too broad by user19510, Eli Drion, Achala Dissanayake, mirg, Richard Horrocks Apr 5 '18 at 18:35

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


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.

  • 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 7 '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 7 '18 at 23:40

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