Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Commit-Reveal Lottery in Solidity
pragma solidity >=0.4.0 <0.7.0;
contract CommitRevealLottery {
uint public ticketingCloses;
uint public revealingCloses;
address[] public tickets;
address public winner;
bytes32 seed;
mapping (address => bytes32) public commitments;
constructor(uint duration, uint revealDuration) public {
ticketingCloses = now + duration * 1 days;
revealingCloses = ticketingCloses + revealDuration * 1 days;
}
function buy(bytes32 commitment) public payable {
require(msg.value >= 0.001 ether);
require(now < ticketingCloses);
commitments[msg.sender] = commitment;
}
function createCommitment(address player, uint rand) public pure returns (bytes32) {
return keccak256(abi.encode(player, rand));
}
function reveal(uint rand) public {
require(now >= ticketingCloses);
require(now < revealingCloses);
bytes32 hash = createCommitment(msg.sender, rand);
require(hash == commitments[msg.sender]);
seed = keccak256(abi.encode(seed, rand));
tickets.push(msg.sender);
}
function drawWinner() public {
require(now > revealingCloses + 5 minutes);
require(winner == address(0));
winner = tickets[uint(seed) % tickets.length];
}
function withdraw() public {
require(msg.sender == winner);
msg.sender.transfer(address(this).balance);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment