When I deploy a contract with a function with receiver.transfer(), receiver.send() or a msg.value function, the function can't get executed when I try to interact with it (MyEtherWallet and web3 via metamask), so I'm wondering how to use the functions in Solidity.
Here are examples with incorrect code:
First try:
function buytokens() public payable{
uint256 ethersent = msg.value / 1000000000000000000;
address zender = msg.sender;
uint256 tokens = ethersent * 10;
require(balanceOf[owner] >= tokens);
balanceOf[zender] += tokens;
balanceOf[owner] -= tokens;
tokenbuy(msg.sender, owner, ethersent, tokens);
}
Second try:
contract token{
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function buy() public payable returns (uint amount){
amount = msg.value; // 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) public 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;
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
}
}
Third try (from example Token contract: https://ethereum.org/token):
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
Could somebody tell me what I'm doing wrong?