From the buy/sell example on ethereum.org:
function buy() payable returns (uint amount){
amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount);
return amount;
}
function sell(uint amount) returns (uint revenue){
require(balanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
balanceOf[this] += amount; // adds the amount to owner's balance
balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance
revenue = amount * sellPrice;
msg.sender.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks
Transfer(msg.sender, this, amount); // executes an event reflecting on the change
return revenue; // ends function and returns
}
In the sell function, I understand that Ether is transferred from the contract to the caller via:
msg.sender.transfer(revenue)
But in the buy function, I see nothing equivalent to ensure that Ether is transferred from the caller to the contract.
So how exactly does that take place? Does the keyword payable have anything to do with it?
Thank you!
payablekeyword does not only "have something to do with it", but is also the actual trigger which ensures that Ether is transferred into the contract... Am I right? – goodvibration Jul 02 '18 at 14:15payableis just a flag that allows ether to be sent together with the function call. Without it the function automatically rejects the call if it has any ether value. It's just a safety measure to prevent accidental payments to functions that don't do anything with the received amount. – rustyx Jul 02 '18 at 14:46payable) which is called with{msg.value > 0}? – goodvibration Jul 02 '18 at 14:55