Skip to content

Instantly share code, notes, and snippets.

@wschae
Created June 10, 2019 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wschae/c6f6e6d476fd420862aa0e2c35930ea3 to your computer and use it in GitHub Desktop.
Save wschae/c6f6e6d476fd420862aa0e2c35930ea3 to your computer and use it in GitHub Desktop.
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