74 lines
1.6 KiB
Solidity
Raw Normal View History

pragma solidity ^0.5.0;
contract DReddit {
2019-01-28 13:52:06 +01:00
enum Ballot { NONE, UPVOTE, DOWNVOTE }
struct Post {
uint creationDate;
bytes description;
address owner;
2019-01-28 13:52:06 +01:00
uint upvotes;
uint downvotes;
mapping(address => Ballot) voters;
}
Post [] public posts;
2019-01-28 12:35:32 +01:00
event NewPost(
uint indexed postId,
address owner,
bytes description
);
2019-01-28 13:52:06 +01:00
event NewVote(
uint indexed postId,
address owner,
uint8 vote
);
function createPost(bytes memory _description) public {
uint postId = posts.length++;
2019-01-28 12:35:32 +01:00
posts[postId] = Post({
creationDate: block.timestamp,
description: _description,
2019-01-28 13:52:06 +01:00
owner: msg.sender,
upvotes: 0,
downvotes: 0
});
2019-01-28 12:35:32 +01:00
emit NewPost(postId, msg.sender, _description);
}
2019-01-28 13:52:06 +01:00
function vote(uint _postId, uint8 _vote) public {
Post storage post = posts[_postId];
require(post.creationDate != 0, "Post does not exist");
require(post.voters[msg.sender] == Ballot.NONE, "You already voted on this post");
Ballot ballot = Ballot(_vote);
if (ballot == Ballot.UPVOTE) {
post.upvotes++;
} else {
post.downvotes++;
}
post.voters[msg.sender] = ballot;
emit NewVote(_postId, msg.sender, _vote);
}
2019-01-28 13:53:53 +01:00
function canVote(uint _postId) public view returns (bool) {
if (_postId > posts.length - 1) return false;
Post storage post = posts[_postId];
return (post.voters[msg.sender] == Ballot.NONE);
}
2019-01-28 13:54:54 +01:00
function getVote(uint _postId) public view returns (uint8) {
Post storage post = posts[_postId];
return uint8(post.voters[msg.sender]);
}
}