Skip to content

Instantly share code, notes, and snippets.

@leon-do
Created April 24, 2023 15:48
Show Gist options
  • Save leon-do/aa1684f3d4c7553c608a6507853ec3de to your computer and use it in GitHub Desktop.
Save leon-do/aa1684f3d4c7553c608a6507853ec3de to your computer and use it in GitHub Desktop.
Random Commit Reveal
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract RandomCommitReveal {
// global for testing
uint256 public randomNumber;
struct Commitment {
uint256 entropy;
uint256 blockNumber;
}
mapping (address => Commitment) commitments;
// 1. Commit a number on chain. Use as entropy
function commit(uint256 _entropy) public {
commitments[msg.sender].entropy = _entropy;
commitments[msg.sender].blockNumber = block.number;
}
// 2. After a few blocks, reveal random number
function reveal() public {
require(commitments[msg.sender].blockNumber != 0, "Must commit");
require(commitments[msg.sender].blockNumber < block.number, "Reveal too soon");
uint256 entropy = commitments[msg.sender].entropy;
// reset commitment
commitments[msg.sender].blockNumber = 0;
commitments[msg.sender].entropy = 0;
// set random number @TODO logic with this random number
randomNumber = uint256(keccak256(abi.encodePacked(
block.timestamp,
entropy
)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment