Skip to content

Instantly share code, notes, and snippets.

@vis-kid
Created March 20, 2022 20:00
Show Gist options
  • Save vis-kid/422ddfc89f9e519a1f1d2cf16b5629fe to your computer and use it in GitHub Desktop.
Save vis-kid/422ddfc89f9e519a1f1d2cf16b5629fe to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.7+commit.e28d00a7.js&optimize=false&runs=200&gist=
pragma solidity >=0.7.0 <0.9.0;
contract BlindAuction {
// Variables
struct Bid {
bytes32 blindedBid;
uint depositAmount;
}
address payable public beneficiary;
uint public biddingEnd;
uint public revealTime;
bool public ended;
mapping(address => Bid[]) public bids;
address public highestBidder;
uint public highestBid;
mapping(address => uint) pendingReturns;
// Events
event AuctionEnded(address winner, uint highestBid);
// Modifiers
modifier onlyBefore(uint _time) {
require(block.timestamp < _time);
_;
}
modifier onlyAfter(uint _time) {
require(block.timestamp > _time);
_;
}
// Functions
constructor(address payable _beneficiary, uint _biddingEnd, uint _revealTime) {
beneficiary = _beneficiary;
biddingEnd = block.timestamp + _biddingEnd;
revealTime = biddingEnd + _revealTime;
}
function generateBlindedBidBytes32(uint _value, bool fake) public pure returns(bytes32) {
return keccak256(abi.encodePacked(_value, fake));
}
function bid(bytes32 _blindedBid) public payable onlyBefore(biddingEnd) {
bids[msg.sender].push(Bid({ blindedBid: _blindedBid, depositAmount: msg.value }));
}
function placeBid(address _bidder, uint _value) internal returns(bool success) {
if (_value <= highestBid) {
return false;
}
if (highestBidder != address(0)) {
pendingReturns[highestBidder] += highestBid;
}
highestBidder = _bidder;
highestBid = _value;
return true;
}
function reveal(uint[] memory _values, bool[] memory _fake) public onlyAfter(biddingEnd) onlyBefore(revealTime) {
uint length = bids[msg.sender].length;
require (_values.length == length);
require (_fake.length == length);
for(uint i=0; i<length; i++) {
Bid storage bidToCheck = bids[msg.sender][i];
(uint value, bool fake) = (_values[i], _fake[i]);
if(bidToCheck.blindedBid != keccak256(abi.encodePacked(value, fake))) {
continue;
}
if(!fake && bidToCheck.depositAmount >= value) {
if(!placeBid(msg.sender, value)) {
payable(msg.sender).transfer(bidToCheck.depositAmount * (1 ether));
}
}
bidToCheck.blindedBid = bytes32(0);
}
}
function withdraw() public {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
pendingReturns[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
}
function auctionEnd() public payable onlyAfter(revealTime) {
require(!ended);
emit AuctionEnded(highestBidder, highestBid);
ended = true;
beneficiary.transfer(highestBid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment