0

Iam trying to write method in solidity where it checks if the given ether is enough to buy my coin. If its enough I will give them the respective amount of coins but if the ether is not enough I need to send back the ether which is getting used to buy a coin. Is there any method to do that ?

This is the method i have written to buy a coin.

function buyTokens(uint256 noOfCoins) public payable returns (bool success){
    if(CoinValue*noOfCoins <= msg.value)
    {
        balances[msg.sender] += noOfCoins;
        return true;
    }
    else{

        emit TokenIssues("You doesnt have enough balances to purchase these quartz base coins");
        msg.sender.transfer(msg.value);
        return false;
    }
}
mani deep
  • 1
  • 1
  • 5
  • apart from your actual problem i find 2 issues with your method. **1.** you can't return any value from a function that changes the state of your contract. **2.** If a user accidentally sends excess `ether` to buy your token, you are keeping it and not refunding the excess `ether` – Iftifar Taz Feb 23 '19 at 07:43

1 Answers1

0

If the msg.value is lower then the amount you are expecting just throw in the else clause. That way the ether will be returned to the user.

dHour
  • 180
  • 1
  • 5