Skip to content

Instantly share code, notes, and snippets.

@pirapira
Last active November 4, 2021 13:32
Show Gist options
  • Save pirapira/2edd8d8cc641775ee211 to your computer and use it in GitHub Desktop.
Save pirapira/2edd8d8cc641775ee211 to your computer and use it in GitHub Desktop.
An auction contract written in Solidity
contract auction {
// An auction contract written in Solidity
// Can be deployed similarly to what is described at:
// https://dappsforbeginners.wordpress.com/tutorials/your-first-dapp/
// Initialization.
// Remembering bids from each address.
mapping (address => uint) bids;
// Also remembering the max_bid and the max_bidder to easily determine the winner.
uint max_bid = 0;
address max_bidder;
// Seller is always the creator of the contract.
address creator = msg.sender;
// When the auction is closed: 100 blocks after creation.
uint finish_block_id = block.number + 100;
// Interface bid().
function bid() returns (bool bid_made) {
// When the auction is over, go to the payout procedure.
if (block.number >= finish_block_id) {
return withdraw();
}
// Otherwise, record the bid.
bids[msg.sender] += msg.value;
// Sometimes, the current bid is the maximal bid so far.
if (bids[msg.sender] > max_bid) {
max_bid = bids[msg.sender];
max_bidder = msg.sender;
}
return true;
}
// Interface withdraw(). Pays back to those who didn't win the
// auction. The winner's bid goes to the seller.
function withdraw() returns (bool done) {
// Anything sent along the withdraw request shall be sent back.
uint payout = msg.value;
// If the auction is still going, withdrawal is not possible.
// That would require finding the second winner when the current winner cancels
// its bid.
if (block.number < finish_block_id) {
msg.sender.send(payout);
return false;
}
// The seller gets the winner's bid.
if (msg.sender == creator) {
payout += max_bid;
// But the next time, the seller will not get it.
max_bid = 0;
}
// The losing bidders get their own bids,
if (msg.sender != max_bidder) {
payout += bids[msg.sender];
// but not next time.
bids[msg.sender] = 0;
}
// The caller gets its payout.
msg.sender.send(payout);
return true;
}
// The winner can be found by looking at the value of max_bidder variable.
// An invalid call gets a payback (provided sufficient gas).
function() {
msg.sender.send(msg.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment