-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrandom.sol
More file actions
60 lines (50 loc) · 1.62 KB
/
random.sol
File metadata and controls
60 lines (50 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
pragma solidity ^0.4.21;
contract Random {
address private host;
address[] public players;
uint constant public TICKET_PRICE = 0.01 ether;
bool public closed = false;
bytes32 public hashedSeed;
uint public blockNumberToUse;
function Random() public {
host = msg.sender;
players.push(host);
}
modifier onlyHost() {
require(msg.sender == host);
_;
}
function () public payable {
require(msg.value == 0);
}
function purchaseTicket() public payable returns (address[]) {
require(closed == false);
require(msg.value > TICKET_PRICE);
uint256 refund = msg.value - TICKET_PRICE;
if (refund > 0) {
msg.sender.transfer(refund);
}
players.push(msg.sender);
return players;
}
event Winner(address winner);
function determineWinner(bytes32 _randomSeedHash) public onlyHost {
require(!closed);
closed = true;
hashedSeed = _randomSeedHash;
blockNumberToUse = block.number+1;
}
function declareWinner(bytes32 _randomSeed) public onlyHost returns (address winner) {
require(closed);
require(hashedSeed == keccak256(_randomSeed));
hashedSeed = "";
bytes32 blockHash = block.blockhash(blockNumberToUse);
uint random = uint(keccak256(uint(_randomSeed) + uint(blockHash)));
uint winnerIndex = random % players.length;
winner = players[winnerIndex];
players.length = 0;
closed = false;
emit Winner(winner);
winner.transfer(address(this).balance);
}
}