DReddit.sol
1 pragma solidity ^0.5.0; 2 3 contract DReddit { 4 5 enum Ballot { NONE, UPVOTE, DOWNVOTE } 6 7 struct Post { 8 uint creationDate; 9 bytes description; 10 address owner; 11 uint upvotes; 12 uint downvotes; 13 mapping(address => Ballot) voters; 14 } 15 16 Post [] public posts; 17 18 event NewPost( 19 uint indexed postId, 20 address owner, 21 bytes description 22 ); 23 24 event NewVote( 25 uint indexed postId, 26 address owner, 27 uint8 vote 28 ); 29 30 function createPost(bytes memory _description) public { 31 uint postId = posts.length++; 32 33 posts[postId] = Post({ 34 creationDate: block.timestamp, 35 description: _description, 36 owner: msg.sender, 37 upvotes: 0, 38 downvotes: 0 39 }); 40 41 emit NewPost(postId, msg.sender, _description); 42 } 43 44 function vote(uint _postId, uint8 _vote) public { 45 Post storage post = posts[_postId]; 46 47 require(post.creationDate != 0, "Post does not exist"); 48 require(post.voters[msg.sender] == Ballot.NONE, "You already voted on this post"); 49 50 Ballot ballot = Ballot(_vote); 51 52 if (ballot == Ballot.UPVOTE) { 53 post.upvotes++; 54 } else { 55 post.downvotes++; 56 } 57 58 post.voters[msg.sender] = ballot; 59 emit NewVote(_postId, msg.sender, _vote); 60 } 61 62 function canVote(uint _postId) public view returns (bool) { 63 if (_postId > posts.length - 1) return false; 64 Post storage post = posts[_postId]; 65 return (post.voters[msg.sender] == Ballot.NONE); 66 } 67 68 function getVote(uint _postId) public view returns (uint8) { 69 Post storage post = posts[_postId]; 70 return uint8(post.voters[msg.sender]); 71 } 72 73 function numPosts() public view returns (uint) { 74 return posts.length; 75 } 76 } 77