The following contract is quite complex, but showcases
a lot of Solidity’s features. It implements a voting
contract. Of course, the main problems of electronic
voting is how to assign voting rights to the correct
persons and how to prevent manipulation. We will not
solve all problems here, but at least we will show
how delegated voting can be done so that vote counting
is automatic and completely transparent at the
same time.

The idea is to create one contract per ballot,
providing a short name for each option.
Then the creator of the contract who serves as
chairperson will give the right to vote to each
address individually.

The persons behind the addresses can then choose
to either vote themselves or to delegate their
vote to a person they trust.

At the end of the voting time, winningProposal()
will return the proposal with the largest number
of votes.

pragmasolidity^0.4.16;/// @title Voting with delegation.contractBallot{// This declares a new complex type which will// be used for variables later.// It will represent a single voter.structVoter{uintweight;// weight is accumulated by delegationboolvoted;// if true, that person already votedaddressdelegate;// person delegated touintvote;// index of the voted proposal}// This is a type for a single proposal.structProposal{bytes32name;// short name (up to 32 bytes)uintvoteCount;// number of accumulated votes}addresspublicchairperson;// This declares a state variable that// stores a `Voter` struct for each possible address.mapping(address=>Voter)publicvoters;// A dynamically-sized array of `Proposal` structs.Proposal[]publicproposals;/// Create a new ballot to choose one of `proposalNames`.functionBallot(bytes32[]proposalNames)public{chairperson=msg.sender;voters[chairperson].weight=1;// For each of the provided proposal names,// create a new proposal object and add it// to the end of the array.for(uinti=0;i<proposalNames.length;i++){// `Proposal({...})` creates a temporary// Proposal object and `proposals.push(...)`// appends it to the end of `proposals`.proposals.push(Proposal({name:proposalNames[i],voteCount:0}));}}// Give `voter` the right to vote on this ballot.// May only be called by `chairperson`.functiongiveRightToVote(addressvoter)public{// If the argument of `require` evaluates to `false`,// it terminates and reverts all changes to// the state and to Ether balances. It is often// a good idea to use this if functions are// called incorrectly. But watch out, this// will currently also consume all provided gas// (this is planned to change in the future).require((msg.sender==chairperson)&&!voters[voter].voted&&(voters[voter].weight==0));voters[voter].weight=1;}/// Delegate your vote to the voter `to`.functiondelegate(addressto)public{// assigns referenceVoterstoragesender=voters[msg.sender];require(!sender.voted);// Self-delegation is not allowed.require(to!=msg.sender);// Forward the delegation as long as// `to` also delegated.// In general, such loops are very dangerous,// because if they run too long, they might// need more gas than is available in a block.// In this case, the delegation will not be executed,// but in other situations, such loops might// cause a contract to get "stuck" completely.while(voters[to].delegate!=address(0)){to=voters[to].delegate;// We found a loop in the delegation, not allowed.require(to!=msg.sender);}// Since `sender` is a reference, this// modifies `voters[msg.sender].voted`sender.voted=true;sender.delegate=to;Voterstoragedelegate_=voters[to];if(delegate_.voted){// If the delegate already voted,// directly add to the number of votesproposals[delegate_.vote].voteCount+=sender.weight;}else{// If the delegate did not vote yet,// add to her weight.delegate_.weight+=sender.weight;}}/// Give your vote (including votes delegated to you)/// to proposal `proposals[proposal].name`.functionvote(uintproposal)public{Voterstoragesender=voters[msg.sender];require(!sender.voted);sender.voted=true;sender.vote=proposal;// If `proposal` is out of the range of the array,// this will throw automatically and revert all// changes.proposals[proposal].voteCount+=sender.weight;}/// @dev Computes the winning proposal taking all/// previous votes into account.functionwinningProposal()publicviewreturns(uintwinningProposal_){uintwinningVoteCount=0;for(uintp=0;p<proposals.length;p++){if(proposals[p].voteCount>winningVoteCount){winningVoteCount=proposals[p].voteCount;winningProposal_=p;}}}// Calls winningProposal() function to get the index// of the winner contained in the proposals array and then// returns the name of the winnerfunctionwinnerName()publicviewreturns(bytes32winnerName_){winnerName_=proposals[winningProposal()].name;}}

In this section, we will show how easy it is to create a
completely blind auction contract on Ethereum.
We will start with an open auction where everyone
can see the bids that are made and then extend this
contract into a blind auction where it is not
possible to see the actual bid until the bidding
period ends.

The general idea of the following simple auction contract
is that everyone can send their bids during
a bidding period. The bids already include sending
money / ether in order to bind the bidders to their
bid. If the highest bid is raised, the previously
highest bidder gets her money back.
After the end of the bidding period, the
contract has to be called manually for the
beneficiary to receive his money - contracts cannot
activate themselves.

pragmasolidity^0.4.21;contractSimpleAuction{// Parameters of the auction. Times are either// absolute unix timestamps (seconds since 1970-01-01)// or time periods in seconds.addresspublicbeneficiary;uintpublicauctionEnd;// Current state of the auction.addresspublichighestBidder;uintpublichighestBid;// Allowed withdrawals of previous bidsmapping(address=>uint)pendingReturns;// Set to true at the end, disallows any changeboolended;// Events that will be fired on changes.eventHighestBidIncreased(addressbidder,uintamount);eventAuctionEnded(addresswinner,uintamount);// The following is a so-called natspec comment,// recognizable by the three slashes.// It will be shown when the user is asked to// confirm a transaction./// Create a simple auction with `_biddingTime`/// seconds bidding time on behalf of the/// beneficiary address `_beneficiary`.functionSimpleAuction(uint_biddingTime,address_beneficiary)public{beneficiary=_beneficiary;auctionEnd=now+_biddingTime;}/// Bid on the auction with the value sent/// together with this transaction./// The value will only be refunded if the/// auction is not won.functionbid()publicpayable{// No arguments are necessary, all// information is already part of// the transaction. The keyword payable// is required for the function to// be able to receive Ether.// Revert the call if the bidding// period is over.require(now<=auctionEnd);// If the bid is not higher, send the// money back.require(msg.value>highestBid);if(highestBid!=0){// Sending back the money by simply using// highestBidder.send(highestBid) is a security risk// because it could execute an untrusted contract.// It is always safer to let the recipients// withdraw their money themselves.pendingReturns[highestBidder]+=highestBid;}highestBidder=msg.sender;highestBid=msg.value;emitHighestBidIncreased(msg.sender,msg.value);}/// Withdraw a bid that was overbid.functionwithdraw()publicreturns(bool){uintamount=pendingReturns[msg.sender];if(amount>0){// It is important to set this to zero because the recipient// can call this function again as part of the receiving call// before `send` returns.pendingReturns[msg.sender]=0;if(!msg.sender.send(amount)){// No need to call throw here, just reset the amount owingpendingReturns[msg.sender]=amount;returnfalse;}}returntrue;}/// End the auction and send the highest bid/// to the beneficiary.functionauctionEnd()public{// It is a good guideline to structure functions that interact// with other contracts (i.e. they call functions or send Ether)// into three phases:// 1. checking conditions// 2. performing actions (potentially changing conditions)// 3. interacting with other contracts// If these phases are mixed up, the other contract could call// back into the current contract and modify the state or cause// effects (ether payout) to be performed multiple times.// If functions called internally include interaction with external// contracts, they also have to be considered interaction with// external contracts.// 1. Conditionsrequire(now>=auctionEnd);// auction did not yet endrequire(!ended);// this function has already been called// 2. Effectsended=true;emitAuctionEnded(highestBidder,highestBid);// 3. Interactionbeneficiary.transfer(highestBid);}}

The previous open auction is extended to a blind auction
in the following. The advantage of a blind auction is
that there is no time pressure towards the end of
the bidding period. Creating a blind auction on a
transparent computing platform might sound like a
contradiction, but cryptography comes to the rescue.

During the bidding period, a bidder does not
actually send her bid, but only a hashed version of it.
Since it is currently considered practically impossible
to find two (sufficiently long) values whose hash
values are equal, the bidder commits to the bid by that.
After the end of the bidding period, the bidders have
to reveal their bids: They send their values
unencrypted and the contract checks that the hash value
is the same as the one provided during the bidding period.

Another challenge is how to make the auction
binding and blind at the same time: The only way to
prevent the bidder from just not sending the money
after he won the auction is to make her send it
together with the bid. Since value transfers cannot
be blinded in Ethereum, anyone can see the value.

The following contract solves this problem by
accepting any value that is larger than the highest
bid. Since this can of course only be checked during
the reveal phase, some bids might be invalid, and
this is on purpose (it even provides an explicit
flag to place invalid bids with high value transfers):
Bidders can confuse competition by placing several
high or low invalid bids.

pragmasolidity^0.4.21;contractBlindAuction{structBid{bytes32blindedBid;uintdeposit;}addresspublicbeneficiary;uintpublicbiddingEnd;uintpublicrevealEnd;boolpublicended;mapping(address=>Bid[])publicbids;addresspublichighestBidder;uintpublichighestBid;// Allowed withdrawals of previous bidsmapping(address=>uint)pendingReturns;eventAuctionEnded(addresswinner,uinthighestBid);/// Modifiers are a convenient way to validate inputs to/// functions. `onlyBefore` is applied to `bid` below:/// The new function body is the modifier's body where/// `_` is replaced by the old function body.modifieronlyBefore(uint_time){require(now<_time);_;}modifieronlyAfter(uint_time){require(now>_time);_;}functionBlindAuction(uint_biddingTime,uint_revealTime,address_beneficiary)public{beneficiary=_beneficiary;biddingEnd=now+_biddingTime;revealEnd=biddingEnd+_revealTime;}/// Place a blinded bid with `_blindedBid` = keccak256(value,/// fake, secret)./// The sent ether is only refunded if the bid is correctly/// revealed in the revealing phase. The bid is valid if the/// ether sent together with the bid is at least "value" and/// "fake" is not true. Setting "fake" to true and sending/// not the exact amount are ways to hide the real bid but/// still make the required deposit. The same address can/// place multiple bids.functionbid(bytes32_blindedBid)publicpayableonlyBefore(biddingEnd){bids[msg.sender].push(Bid({blindedBid:_blindedBid,deposit:msg.value}));}/// Reveal your blinded bids. You will get a refund for all/// correctly blinded invalid bids and for all bids except for/// the totally highest.functionreveal(uint[]_values,bool[]_fake,bytes32[]_secret)publiconlyAfter(biddingEnd)onlyBefore(revealEnd){uintlength=bids[msg.sender].length;require(_values.length==length);require(_fake.length==length);require(_secret.length==length);uintrefund;for(uinti=0;i<length;i++){varbid=bids[msg.sender][i];var(value,fake,secret)=(_values[i],_fake[i],_secret[i]);if(bid.blindedBid!=keccak256(value,fake,secret)){// Bid was not actually revealed.// Do not refund deposit.continue;}refund+=bid.deposit;if(!fake&&bid.deposit>=value){if(placeBid(msg.sender,value))refund-=value;}// Make it impossible for the sender to re-claim// the same deposit.bid.blindedBid=bytes32(0);}msg.sender.transfer(refund);}// This is an "internal" function which means that it// can only be called from the contract itself (or from// derived contracts).functionplaceBid(addressbidder,uintvalue)internalreturns(boolsuccess){if(value<=highestBid){returnfalse;}if(highestBidder!=0){// Refund the previously highest bidder.pendingReturns[highestBidder]+=highestBid;}highestBid=value;highestBidder=bidder;returntrue;}/// Withdraw a bid that was overbid.functionwithdraw()public{uintamount=pendingReturns[msg.sender];if(amount>0){// It is important to set this to zero because the recipient// can call this function again as part of the receiving call// before `transfer` returns (see the remark above about// conditions -> effects -> interaction).pendingReturns[msg.sender]=0;msg.sender.transfer(amount);}}/// End the auction and send the highest bid/// to the beneficiary.functionauctionEnd()publiconlyAfter(revealEnd){require(!ended);emitAuctionEnded(highestBidder,highestBid);ended=true;beneficiary.transfer(highestBid);}}

pragmasolidity^0.4.21;contractPurchase{uintpublicvalue;addresspublicseller;addresspublicbuyer;enumState{Created,Locked,Inactive}Statepublicstate;// Ensure that `msg.value` is an even number.// Division will truncate if it is an odd number.// Check via multiplication that it wasn't an odd number.functionPurchase()publicpayable{seller=msg.sender;value=msg.value/2;require((2*value)==msg.value);}modifiercondition(bool_condition){require(_condition);_;}modifieronlyBuyer(){require(msg.sender==buyer);_;}modifieronlySeller(){require(msg.sender==seller);_;}modifierinState(State_state){require(state==_state);_;}eventAborted();eventPurchaseConfirmed();eventItemReceived();/// Abort the purchase and reclaim the ether./// Can only be called by the seller before/// the contract is locked.functionabort()publiconlySellerinState(State.Created){emitAborted();state=State.Inactive;seller.transfer(this.balance);}/// Confirm the purchase as buyer./// Transaction has to include `2 * value` ether./// The ether will be locked until confirmReceived/// is called.functionconfirmPurchase()publicinState(State.Created)condition(msg.value==(2*value))payable{emitPurchaseConfirmed();buyer=msg.sender;state=State.Locked;}/// Confirm that you (the buyer) received the item./// This will release the locked ether.functionconfirmReceived()publiconlyBuyerinState(State.Locked){emitItemReceived();// It is important to change the state first because// otherwise, the contracts called using `send` below// can call in again here.state=State.Inactive;// NOTE: This actually allows both the buyer and the seller to// block the refund - the withdraw pattern should be used.buyer.transfer(value);seller.transfer(this.balance);}}