动手编写第一个Solidity智能合约:投票
pragma solidity ^0.4.0;
//尝试写一个关于投票的智能合约;
//投票人每人只有一票;
//候选人票数多获胜,若平票则再投一轮;
//候选人不能参与投票;
contract Votegame{
struct voter{
address vaddr;//投票人地址
bool yn;//是否投票
uint amount;//票数
}
struct candidate{
address caddr;//候选人地址
uint get;//得到的票数
bool win;//是否获胜
}
address chairperson;
mapping(address => voter) voters;
mapping(address => candidate) candidates;
function candidater1(address Candidate1){
// 候选人初始化
candidates[Candidate1].get = 0;
candidates[Candidate1].win = false;
}
/*function candidater2(address Candidate2){
// initialize
candidates[Candidate2].get = 0;
candidates[Candidate2].win = false;
}*/
//投票人初始化
function giveRightToVote(address Voter) {
if (msg.sender != chairperson || voters[Voter].yn) return;
voters[Voter].amount = 1;
}
function vote(address Candidate) {
voter storage sender = voters[msg.sender];
//排除不合格的投票者;
if (sender.yn || sender.vaddr == Candidate ) return;
sender.yn = true;
candidates[Candidate].get = candidates[Candidate].get + 1 ;
}
function success(address Candidate1,address Candidate2) returns(address winner){
if(candidates[Candidate1].get > candidates[Candidate2].get) return Candidate1;
else return Candidate2;
}
}