How to make a simple coinflip contract?

mikkaaamikkaaa Member Posts: 34
1) User sends 1 ether to a address.
2) Contract makes coinflip = random(0 - 1), (if coinflip == 0 'bank wins'), (if coinflip = 1 2 ethers are sent to the user)

Should be very simple, but I don't know the syntax. Some help?


  • thinredthinred Member Posts: 4
    I'm learning contracts too. This worked for me:
    contract CoinFlip {
    	function CoinFlip() {
    		// nothing here
            function() {
    		var bet = msg.value;
    		var flip = block.timestamp; // semirandom
    		if (flip % 2 == 0)
    			msg.sender.send(2 * bet);
    When you send money to CoinFlip, function() is called. Then we take the mined block timestamp as a semirandom source (the timestamp may not be fully random, I think, but it'd be hard to coerce miners to forge it) and either keep the money or pay two times the bet.

    You will notice that this won't really fly without some initial amount in the bank. At the
    beginning you will lose even if you win :smile: .

    Have fun!
  • mikkaaamikkaaa Member Posts: 34
    Thanks !! This can be used as a base for so many things.
  • Xophe92Xophe92 Member Posts: 3
    This is very dangerous and should be avoided:

    a contract can be constructed to generate transactions to your contract only in situations where block.timestamp%2 == 0.

    I think randomness is something which is not very well covered yet.

    I refer to

    Where the author, after having tried several approaches identifies someone who did better than him:

    "It’s another contract invocation. The sender simply invokes his own contract. The malicious contract has access to the same context-variables from the block header (timestamp, difficulty etc). Then the contract simply invokes the casino contract. Pretty nice way to do it!"

    --> the other contract know the timestamp and is able to deside whether ot not it has profit betting in your contract.

    be aware :)

Sign In or Register to comment.