public static Vote Convert(VoteInput input) { var optionRepo = new OptionRepository(); var surveyRepo = new SurveyRepository(); return(new Vote(input.Date, surveyRepo.GetById(input.SurveyId), optionRepo.GetById(input.OptionId))); }
public async Task VoteContract_VoteSuccess() { await GenerateNewVoteEvent("topic1", 2, 100, 4, false); var voteAmount = 10_000L; var voteUser = SampleECKeyPairs.KeyPairs[1]; var beforeBalance = await GetUserBalance(voteUser.PublicKey); var input = new VoteInput { Topic = "topic1", Sponsor = DefaultSender, Option = _options[1], Amount = voteAmount }; var voteUserStub = GetVoteContractTester(voteUser); var transactionResult = (await voteUserStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Mined); var afterBalance = await GetUserBalance(voteUser.PublicKey); beforeBalance.ShouldBe(afterBalance + voteAmount); }
public async Task HandleAsync(VoteInput input, IVoteOutputPort output) { try { Poll poll = await this.pollGateway.GetAsync(input.Id); if (poll is null) { output.NotFound("Poll not found!"); this.loggerService.LogInformation("Cannot retrieve a poll with {@id}", input.Id); return; } poll.Vote(input.ParticipantEmailAddress, input.Options, this.dateTime.UtcNow); await this.pollGateway.UpdateAsync(poll); output.Success(); } catch (DomainException ex) { this.loggerService.LogInformation("{@excepton} occured when trying to vote with {@input}", ex, input); output.Error(ex.Message); } }
private VotingItem AssertValidVoteInput(VoteInput input) { var votingItem = AssertVotingItem(input.VotingItemId); Assert(input.Option.Length <= VoteContractConstants.OptionLengthLimit, "Invalid input."); Assert(votingItem.Options.Contains(input.Option), $"Option {input.Option} not found."); Assert(votingItem.CurrentSnapshotNumber <= votingItem.TotalSnapshotNumber, "Current voting item already ended."); if (!votingItem.IsLockToken) { Assert(votingItem.Sponsor == Context.Sender, "Sender of delegated voting event must be the Sponsor."); Assert(input.Voter != null, "Voter cannot be null if voting event is delegated."); Assert(input.VoteId != null, "Vote Id cannot be null if voting event is delegated."); } else { var votingResultHash = GetVotingResultHash(votingItem.VotingItemId, votingItem.CurrentSnapshotNumber); var votingResult = State.VotingResults[votingResultHash]; // Voter = Transaction Sender input.Voter = Context.Sender; // VoteId = Transaction Id; input.VoteId = Context.GenerateId(Context.Self, votingResult.VotesAmount.ToBytes(false)); } return(votingItem); }
public async Task <IActionResult> Vote(int id, VoteRequest request) { var createVoteInput = new VoteInput(id, request.ParticipantEmailAddress, request.Options); await this.voteInputPort.HandleAsync(createVoteInput, this.votePresenter); return(this.votePresenter.ViewModel); }
public async Task VoteContract_VoteFailed() { //did not find related vote event { var input = new VoteInput { Topic = "Not existed vote", Sponsor = Address.Generate(), }; var transactionResult = (await VoteContractStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Voting event not found").ShouldBeTrue(); } //without such option { await GenerateNewVoteEvent("topic0", 2, 100, 4, true); var input = new VoteInput { Topic = "topic0", Sponsor = DefaultSender, Option = "Somebody" }; var otherKeyPair = SampleECKeyPairs.KeyPairs[1]; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains($"Option {input.Option} not found").ShouldBeTrue(); } //not enough token { await GenerateNewVoteEvent("topic1", 2, 100, 4, false); var input = new VoteInput { Topic = "topic1", Sponsor = DefaultSender, Option = _options[1], Amount = 2000_000L }; var otherKeyPair = SampleECKeyPairs.KeyPairs[1]; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Insufficient balance").ShouldBeTrue(); } }
public async Task VoteContract_Vote_NotSuccess_Test() { //did not find related vote event { var input = new VoteInput { VotingItemId = Hash.FromString("hash") }; var transactionResult = (await VoteContractStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Voting item not found").ShouldBeTrue(); } //without such option { var votingItem = await RegisterVotingItemAsync(100, 4, true, DefaultSender, 2); var input = new VoteInput { VotingItemId = votingItem.VotingItemId, Option = "Somebody" }; var otherKeyPair = SampleECKeyPairs.KeyPairs[1]; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain($"Option {input.Option} not found"); } //not enough token { var votingItemId = await RegisterVotingItemAsync(100, 4, true, DefaultSender, 2); var input = new VoteInput { VotingItemId = votingItemId.VotingItemId, Option = votingItemId.Options.First(), Amount = 2000_000_000_00000000L }; var otherKeyPair = SampleECKeyPairs.KeyPairs[1]; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain("Insufficient balance"); } }
private async Task <TransactionResult> UserVote(ECKeyPair voteUser, string topic, Address sponsor, string option, long amount) { var input = new VoteInput { Topic = topic, Sponsor = sponsor, Option = option, Amount = amount }; var voteUserStub = GetVoteContractTester(voteUser); var transactionResult = (await voteUserStub.Vote.SendAsync(input)).TransactionResult; return(transactionResult); }
/// <summary> /// Execute the Vote action,save the VoteRecords and update the VotingResults and the VotedItems /// Before Voting,the VotingItem's token must be locked,except the votes delegated to a contract. /// </summary> /// <param name="input">VoteInput</param> /// <returns></returns> public override Empty Vote(VoteInput input) { var votingItem = AssertValidVoteInput(input); var votingRecord = new VotingRecord { VotingItemId = input.VotingItemId, Amount = input.Amount, SnapshotNumber = votingItem.CurrentSnapshotNumber, Option = input.Option, IsWithdrawn = false, VoteTimestamp = Context.CurrentBlockTime, Voter = input.Voter, IsChangeTarget = input.IsChangeTarget }; //save the VotingRecords into the state. State.VotingRecords[input.VoteId] = votingRecord; UpdateVotingResult(votingItem, input.Option, input.Amount); UpdateVotedItems(input.VoteId, votingRecord.Voter, votingItem); if (votingItem.IsLockToken) { // Lock voted token. State.TokenContract.Lock.Send(new LockInput { Address = votingRecord.Voter, Symbol = votingItem.AcceptedCurrency, LockId = input.VoteId, Amount = input.Amount, Usage = $"Voting for {input.VotingItemId}" }); } Context.Fire(new Voted { VoteId = input.VoteId, VotingItemId = votingRecord.VotingItemId, Voter = votingRecord.Voter, Amount = votingRecord.Amount, Option = votingRecord.Option, SnapshotNumber = votingRecord.SnapshotNumber, VoteTimestamp = votingRecord.VoteTimestamp }); return(new Empty()); }
public async Task <IActionResult> Submit(VoteInput input) { var token = HttpContext.Request.Headers["Authorization"].Last().Split(" ").Last(); var roles = new List <string>() { "User" }; var handler = new JwtSecurityTokenHandler(); var sub = handler.ReadJwtToken(token).Payload.Sub; if (RoleService.CheckRoles(token, roles, _userManager)) { var vote = VoteInputConverter.Convert(input); var detailsRepo = new UserDetailsRepository(); var voteRecordsRepo = new VoteRecordRepository(); var detailsId = detailsRepo.GetByUserId(sub).Id; var surveyId = vote.SurveyId; if (voteRecordsRepo.GetAll().Count(x => x.UserDetailsId == detailsId && x.SurveyId == surveyId) == 0) { _repository.Add(vote); var record = new VoteRecord(surveyId, detailsId); voteRecordsRepo.Add(record); return(CreatedAtAction("Submit", vote)); } return(BadRequest("You already voted")); } else { return(BadRequest("Only Users can vote.")); } }
private VotingItem AssertValidVoteInput(VoteInput input) { var votingItem = AssertVotingItem(input.VotingItemId); Assert(input.Option.Length <= VoteContractConstants.OptionLengthLimit, "Invalid input."); Assert(votingItem.Options.Contains(input.Option), $"Option {input.Option} not found."); Assert(votingItem.CurrentSnapshotNumber <= votingItem.TotalSnapshotNumber, "Current voting item already ended."); if (!votingItem.IsLockToken) { Assert(votingItem.Sponsor == Context.Sender, "Sender of delegated voting event must be the Sponsor."); Assert(input.Voter != null, "Voter cannot be null if voting event is delegated."); Assert(input.VoteId != null, "Vote Id cannot be null if voting event is delegated."); } else { //Voter just is the transaction sponsor input.Voter = Context.Sender; //VoteId just is the transaction ID; input.VoteId = Context.TransactionId; } return(votingItem); }
/// <summary> /// Execute the Vote action,save the VoteRecords and update the VotingResults and the VotedItems /// Before Voting,the VotingItem's token must be locked,except the votes delegated to a contract. /// </summary> /// <param name="input">VoteInput</param> /// <returns></returns> public override Empty Vote(VoteInput input) { //the VotingItem is exist in state. var votingItem = AssertVotingItem(input.VotingItemId); Assert(votingItem.Options.Contains(input.Option), $"Option {input.Option} not found."); Assert(votingItem.CurrentSnapshotNumber <= votingItem.TotalSnapshotNumber, "Current voting item already ended."); if (!votingItem.IsLockToken) { Assert(votingItem.Sponsor == Context.Sender, "Sender of delegated voting event must be the Sponsor."); Assert(input.Voter != null, "Voter cannot be null if voting event is delegated."); Assert(input.VoteId != null, "Vote Id cannot be null if voting event is delegated."); } else { //Voter just is the transaction sponsor input.Voter = Context.Sender; //VoteId just is the transaction ID; input.VoteId = Context.TransactionId; } var votingRecord = new VotingRecord { VotingItemId = input.VotingItemId, Amount = input.Amount, SnapshotNumber = votingItem.CurrentSnapshotNumber, Option = input.Option, IsWithdrawn = false, VoteTimestamp = Context.CurrentBlockTime, Voter = input.Voter }; //save the VotingRecords into the state. State.VotingRecords[input.VoteId] = votingRecord; UpdateVotingResult(votingItem, input.Option, input.Amount); UpdateVotedItems(input.VoteId, votingRecord.Voter, votingItem); if (votingItem.IsLockToken) { // Lock voted token. State.TokenContract.Lock.Send(new LockInput { Address = votingRecord.Voter, Symbol = votingItem.AcceptedCurrency, LockId = input.VoteId, Amount = input.Amount, Usage = $"Voting for {input.VotingItemId}" }); } Context.Fire(new Voted { VoteId = input.VoteId, VotingItemId = votingRecord.VotingItemId, Voter = votingRecord.Voter, Amount = votingRecord.Amount, Option = votingRecord.Option, SnapshotNumber = votingRecord.SnapshotNumber, VoteTimestamp = votingRecord.VoteTimestamp }); return(new Empty()); }
private void AddVoteToPicture(VoteInput model, Picture picture) { var oldVote = picture.Votes.FirstOrDefault(x => x.UserId == this.CurrentUser.Id); if (oldVote != null) { oldVote.Rating = model.Rating; } else { picture.Votes.Add(new Vote() { Rating = model.Rating, UserId = this.CurrentUser.Id }); } }
public JsonResult Vote(VoteInput model) { if (this.ModelState.IsValid && model != null) { var picture = this.Data.Pictures.Find(model.PictureId); if (picture != null) { this.AddVoteToPicture(model, picture); this.Data.SaveChanges(); this.cache.RemoveContestsFromCache(); } this.AddToastMessage(String.Empty, GlobalConstants.VoteSuccessMessage, ToastType.Success); var newRating = picture.Votes.Select(x => x.Rating).Average(); return this.Json(new { stars = newRating }); } this.AddToastMessage(String.Empty, GlobalConstants.SomethingIsWrongMessage, ToastType.Error); return this.Json(""); }
public ActionResult Vote(int id) { var model = new VoteInput() { PictureId = id }; return this.PartialView("_Vote", model); }
public async Task <IActionResult> Vote([FromBody] VoteInput input) => (await Mediator.Send(new VoteForTeam(input.TeamId, CurrentUserId)) .MapAsync(_ => ToEmptyResourceAsync <VoteForTeamResource>())) .Match(unit => CreatedAtAction(nameof(Vote), unit), Error);
//TODO: User cannot vote when Event CurrentEpoch >= EpochNumber + 1 public override Empty Vote(VoteInput input) { input.Topic = input.Topic.Trim(); var votingEvent = AssertVotingEvent(input.Topic, input.Sponsor); Assert(votingEvent.Options.Contains(input.Option), $"Option {input.Option} not found."); if (votingEvent.Delegated) { Assert(input.Sponsor == Context.Sender, "Sender of delegated voting event must be the Sponsor."); Assert(input.Voter != null, "Voter cannot be null if voting event is delegated."); Assert(input.VoteId != null, "Vote Id cannot be null if voting event is delegated."); } else { input.Voter = Context.Sender; input.VoteId = Context.TransactionId; } var votingRecord = new VotingRecord { Topic = input.Topic, Sponsor = input.Sponsor, Amount = input.Amount, EpochNumber = votingEvent.CurrentEpoch, Option = input.Option, IsWithdrawn = false, VoteTimestamp = Context.CurrentBlockTime.ToTimestamp(), Voter = input.Voter, Currency = votingEvent.AcceptedCurrency }; // Update VotingResult based on this voting behaviour. var votingResultHash = Hash.FromMessage(new GetVotingResultInput { Sponsor = input.Sponsor, Topic = input.Topic, EpochNumber = votingEvent.CurrentEpoch }); var votingResult = State.VotingResults[votingResultHash]; if (!votingResult.Results.ContainsKey(input.Option)) { votingResult.Results.Add(input.Option, 0); } var currentVotes = votingResult.Results[input.Option]; votingResult.Results[input.Option] = currentVotes + input.Amount; // Update voting history var votingHistories = State.VotingHistoriesMap[votingRecord.Voter] ?? new VotingHistories { Voter = votingRecord.Voter }; var votingEventHash = votingEvent.GetHash().ToHex(); if (!votingHistories.Votes.ContainsKey(votingEventHash)) { votingHistories.Votes[votingEventHash] = new VotingHistory { ActiveVotes = { input.VoteId } }; votingResult.VotersCount += 1; } else { votingHistories.Votes[votingEventHash].ActiveVotes.Add(input.VoteId); } State.VotingRecords[input.VoteId] = votingRecord; State.VotingResults[votingResultHash] = votingResult; State.VotingHistoriesMap[votingRecord.Voter] = votingHistories; if (!votingEvent.Delegated) { // Lock voted token. State.TokenContract.Lock.Send(new LockInput { From = votingRecord.Voter, Symbol = votingEvent.AcceptedCurrency, LockId = input.VoteId, Amount = input.Amount, To = Context.Self, Usage = $"Voting for {input.Topic}" }); } return(new Empty()); }
public override Hash Vote(VoteInput input) { var candidatePublicKey = input.CandidatePublicKey; var amount = input.Amount; var lockTime = input.LockTime; Assert(lockTime.InRange(90, 1095), ContractErrorCode.GetErrorMessage(ContractErrorCode.InvalidOperation, "Lock days is illegal.")); // Cannot vote to non-candidate. var candidates = State.CandidatesField.Value; Assert(candidates != null, ContractErrorCode.GetErrorMessage(ContractErrorCode.NotFound, "No candidate.")); Assert(candidates != null && candidates.PublicKeys.Contains(candidatePublicKey), ContractErrorCode.GetErrorMessage(ContractErrorCode.InvalidOperation, "Target didn't announce election.")); var voterPublicKey = Context.RecoverPublicKey().ToHex(); // A candidate cannot vote to anybody. Assert(candidates != null && !candidates.PublicKeys.Contains(voterPublicKey), ContractErrorCode.GetErrorMessage(ContractErrorCode.InvalidOperation, "Candidate can't vote.")); // Transfer the tokens to Consensus Contract address. State.TokenContract.Lock.Send(new LockInput { From = Context.Sender, To = Context.Self, Symbol = Context.Variables.NativeSymbol, Amount = amount, LockId = Context.TransactionId, Usage = "Lock for getting tickets." }); var currentTermNumber = State.CurrentTermNumberField.Value; var currentRoundNumber = State.CurrentRoundNumberField.Value; // To make up a VotingRecord instance. TryToGetBlockchainStartTimestamp(out var blockchainStartTimestamp); var votingRecord = new VotingRecord { Count = amount, From = voterPublicKey, To = candidatePublicKey, RoundNumber = currentRoundNumber, TransactionId = Context.TransactionId, VoteAge = CurrentAge, UnlockAge = CurrentAge + (long)lockTime, TermNumber = currentTermNumber, VoteTimestamp = blockchainStartTimestamp.ToDateTime().AddMinutes(CurrentAge).ToTimestamp(), UnlockTimestamp = blockchainStartTimestamp.ToDateTime().AddMinutes(CurrentAge + (long)lockTime) .ToTimestamp() }; votingRecord.LockDaysList.Add(lockTime); // Add the transaction id of this voting record to the tickets information of the voter. var tickets = State.TicketsMap[voterPublicKey.ToStringValue()]; if (tickets != null) { tickets.VoteToTransactions.Add(votingRecord.TransactionId); } else { tickets = new Tickets { PublicKey = voterPublicKey }; tickets.VoteToTransactions.Add(votingRecord.TransactionId); } tickets.VotedTickets += votingRecord.Count; tickets.HistoryVotedTickets += votingRecord.Count; State.TicketsMap[voterPublicKey.ToStringValue()] = tickets; // Add the transaction id of this voting record to the tickets information of the candidate. var candidateTickets = State.TicketsMap[candidatePublicKey.ToStringValue()]; if (candidateTickets != null) { candidateTickets.VoteFromTransactions.Add(votingRecord.TransactionId); } else { candidateTickets = new Tickets { PublicKey = candidatePublicKey }; candidateTickets.VoteFromTransactions.Add(votingRecord.TransactionId); } candidateTickets.ObtainedTickets += votingRecord.Count; candidateTickets.HistoryObtainedTickets += votingRecord.Count; State.TicketsMap[candidatePublicKey.ToStringValue()] = candidateTickets; // Update the amount of votes (voting records of whole system). State.VotesCountField.Value += 1; // Update the amount of tickets. State.TicketsCountField.Value += votingRecord.Count; // Add this voting record to voting records map. State.VotingRecordsMap[votingRecord.TransactionId] = votingRecord; // Tell Dividends Contract to add weights for this voting record. State.DividendContract.AddWeights.Send(new Dividend.WeightsInfo() { TermNumber = currentTermNumber + 1, Weights = votingRecord.Weight }); Context.LogDebug(() => $"Weights of vote {votingRecord.TransactionId.ToHex()}: {votingRecord.Weight}"); return(Context.TransactionId); }