solidity – How to Use Payable to Receive Ethers?

crowdsaleerc-20solidity

I'm new to the smart contracts. I want to create a contract which accepts ether and will transfer the equivalent tokens to the sender ether address (crowdsale). after few days research, i was written this code. but it doesn't accept the ethers (in ropsten testnet). every time sending an ether to this contract results me fails.

contract YourTokenToken {

string public constant name = "YOURCOIN";
string public constant symbol = "YRC";
uint8 public constant decimals = 8;  // 8 decimal places.
uint256 public constant tokenCreationRate = 1500;
uint256 public constant tokenCreationCap = 10000 ether * tokenCreationRate;
uint256 public constant tokenCreationMin = 1000 ether * tokenCreationRate;
address public coinOwner; // Receives ETH and its own YRC endowment.
uint256 totalTokens; // The current total token supply.
mapping (address => uint256) balances;

event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed _from, uint256 _value);

function YourTokenToken() {
    coinOwner = msg.sender;
}

// Crowdfunding:

function create() payable external {

    if (msg.value == 0) throw;
    if (msg.value > (tokenCreationCap - totalTokens) / tokenCreationRate)
        throw;

    var numTokens = msg.value * tokenCreationRate;
    totalTokens += numTokens;
    // Assign new tokens to the sender
    balances[msg.sender] += numTokens;
    // Log token creation event
    Transfer(0, msg.sender, numTokens);
}

}

Best Answer

If you want to receive ether on contract using the contract address, then you have to implement an anonymous function with a payable keyword.

// Anonymous Function or Fallback Function
function() paybale{
if (msg.value == 0) throw;
if (msg.value > (tokenCreationCap - totalTokens) / tokenCreationRate)
    throw;

var numTokens = msg.value * tokenCreationRate;
totalTokens += numTokens;
// Assign new tokens to the sender
balances[msg.sender] += numTokens;
// Log token creation event
Transfer(0, msg.sender, numTokens);
}

For more information anonymous functions.

Related Topic