Guest User

Untitled

a guest
Jan 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. pragma solidity ^0.5.2;
  2.  
  3. contract Ballot {
  4. struct Voter {
  5. uint weight;
  6. bool voted;
  7. address delegate;
  8. uint vote;
  9. }
  10.  
  11. struct Proposal {
  12. bytes32 name;
  13. uint voteCount;
  14. }
  15.  
  16. address public chairperson;
  17. mapping(address => Voter) public voters;
  18. Proposal[] public proposals;
  19.  
  20. constructor (bytes32[] memory proposalNames) public {
  21. chairperson = msg.sender;
  22. voters[chairperson].weight = 1;
  23.  
  24. for (uint i = 0; i < proposalNames.length; i++) {
  25. proposals.push(Proposal({
  26. name: proposalNames[i],
  27. voteCount: 0
  28. }));
  29. }
  30. }
  31.  
  32. function giveRightToVote(address voter) public {
  33. require(
  34. (msg.sender == chairperson) &&
  35. !voters[voter].voted &&
  36. (voters[voter].weight == 0)
  37. );
  38. voters[voter].weight = 1;
  39. }
  40.  
  41. function delegate(address to) public {
  42. Voter storage sender = voters[msg.sender];
  43. require(!sender.voted);
  44.  
  45. require(to != msg.sender);
  46.  
  47. while (voters[to].delegate != address(0)) {
  48. to = voters[to].delegate;
  49.  
  50. require(to != msg.sender);
  51. }
  52.  
  53. sender.voted = true;
  54. sender.delegate = to;
  55. Voter storage delegate_ = voters[to];
  56. if (delegate_.voted) {
  57. proposals[delegate_.vote].voteCount += sender.weight;
  58. } else {
  59. delegate_.weight += sender.weight;
  60. }
  61. }
  62.  
  63. function vote(uint proposal) public {
  64. Voter storage sender = voters[msg.sender];
  65. require(!sender.voted);
  66. sender.voted = true;
  67. sender.vote = proposal;
  68.  
  69. proposals[proposal].voteCount += sender.weight;
  70. }
  71.  
  72. function winningProposal() public view
  73. returns (uint winningProposal_)
  74. {
  75. uint winningVoteCount = 0;
  76. for (uint p = 0; p < proposals.length; p++) {
  77. if (proposals[p].voteCount > winningVoteCount) {
  78. winningVoteCount = proposals[p].voteCount;
  79. winningProposal_ = p;
  80. }
  81. }
  82. }
  83.  
  84. function winnerName() public view
  85. returns (bytes32 winnerName_)
  86. {
  87. winnerName_ = proposals[winningProposal()].name;
  88. }
  89. }
Add Comment
Please, Sign In to add comment