setPrices()添加了onlyOwner修改器,注意买卖的价格单位是wei(最小的货币单位: 1 eth = 1000000000000000000 wei)
现在来添加买卖函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
function buy() payable returns (uint amount){ amount = msg.value / buyPrice; // calculates the amount require(balanceOf[this] >= amount); // checks if it has enough to sell balanceOf[msg.sender] += amount; // adds the amount to buyer's balance balanceOf[this] -= amount; // subtracts amount from seller's balance Transfer(this, msg.sender, amount); // execute an event reflecting the change return amount; // ends function and returns }
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 }