public async Task Execute(WithdrawInput input)
        {
            IAccount account;
            IDebit   debit;

            try
            {
                account = await _accountRepository.Get(input.AccountId);

                debit = account.Withdraw(_entityFactory, input.Amount);
            }
            catch (AccountNotFoundException notFoundEx)
            {
                _outputPort.NotFound(notFoundEx.Message);
                return;
            }
            catch (MoneyShouldBePositiveException outOfBalanceEx)
            {
                _outputPort.OutOfBalance(outOfBalanceEx.Message);
                return;
            }

            await _accountRepository.Update(account, debit);

            await _unitOfWork.Save();

            BuildOutput(debit, account);
        }
        public override Empty Withdraw(WithdrawInput input)
        {
            State.TokenContract.TransferToContract.Send(new TransferToContractInput
            {
                Symbol = State.Symbol.Value,
                Amount = input.Amount
            });

            State.TokenContract.Transfer.Send(new TransferInput
            {
                To     = Context.Sender,
                Symbol = input.Symbol,
                Amount = input.Amount
            });

            State.TokenHolderContract.RemoveBeneficiary.Send(new RemoveTokenHolderBeneficiaryInput
            {
                Beneficiary = Context.Sender,
                Amount      = input.Amount
            });

            // Update profile.
            var profile = State.Profiles[Context.Sender];

            profile.Records.Add(new Record
            {
                Type        = RecordType.Withdraw,
                Timestamp   = Context.CurrentBlockTime,
                Description = $"{State.Symbol.Value} -{input.Amount}"
            });
            State.Profiles[Context.Sender] = profile;

            return(new Empty());
        }
        public async Task Execute(WithdrawInput input)
        {
            IAccount account = await _accountRepository.Get(input.AccountId);

            if (account == null)
            {
                _outputHandler.Error($"The account {input.AccountId} does not exist or is already closed.");
                return;
            }

            IDebit debit = account.Withdraw(_entityFactory, input.Amount);

            if (debit == null)
            {
                _outputHandler.Error($"The account {input.AccountId} does not have enough funds to withdraw {input.Amount}.");
                return;
            }

            await _accountRepository.Update(account, debit);

            await _unitOfWork.Save();

            WithdrawOutput output = new WithdrawOutput(
                debit,
                account.GetCurrentBalance()
                );

            _outputHandler.Default(output);
        }
示例#4
0
        /// <summary>
        /// Withdraw the Votes.
        /// first,mark the related record IsWithdrawn.
        /// second,delete the vote form ActiveVotes and add the vote to withdrawnVotes.
        /// finally,unlock the token that Locked in the VotingItem
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override Empty Withdraw(WithdrawInput input)
        {
            var votingRecord = State.VotingRecords[input.VoteId];

            Assert(votingRecord != null, "Voting record not found.");
            var votingItem = State.VotingItems[votingRecord.VotingItemId];

            if (votingItem.IsLockToken)
            {
                Assert(votingRecord.Voter == Context.Sender, "No permission to withdraw votes of others.");
            }

            Assert(votingItem.CurrentSnapshotNumber > votingRecord.SnapshotNumber,
                   "Cannot withdraw votes of on-going voting item.");

            // Update VotingRecord.
            votingRecord.IsWithdrawn          = true;
            votingRecord.WithdrawTimestamp    = Context.CurrentBlockTime;
            State.VotingRecords[input.VoteId] = votingRecord;

            var votingResultHash = GetVotingResultHash(votingRecord.VotingItemId, votingRecord.SnapshotNumber);

            var votedItems = State.VotedItemsMap[votingRecord.Voter];

            votedItems.VotedItemVoteIds[votingItem.VotingItemId.ToHex()].ActiveVotes.Remove(input.VoteId);
            votedItems.VotedItemVoteIds[votingItem.VotingItemId.ToHex()].WithdrawnVotes.Add(input.VoteId);
            State.VotedItemsMap[votingRecord.Voter] = votedItems;

            var votingResult = State.VotingResults[votingResultHash];

            votingResult.Results[votingRecord.Option] =
                votingResult.Results[votingRecord.Option].Sub(votingRecord.Amount);
            if (!votedItems.VotedItemVoteIds[votingRecord.VotingItemId.ToHex()].ActiveVotes.Any())
            {
                votingResult.VotersCount = votingResult.VotersCount.Sub(1);
            }

            votingResult.VotesAmount = votingResult.VotesAmount.Sub(votingRecord.Amount);

            State.VotingResults[votingResultHash] = votingResult;

            if (votingItem.IsLockToken)
            {
                State.TokenContract.Unlock.Send(new UnlockInput
                {
                    Address = votingRecord.Voter,
                    Symbol  = votingItem.AcceptedCurrency,
                    Amount  = votingRecord.Amount,
                    LockId  = input.VoteId,
                    Usage   = $"Withdraw votes for {votingRecord.VotingItemId}"
                });
            }

            Context.Fire(new Withdrawn
            {
                VoteId = input.VoteId
            });

            return(new Empty());
        }
示例#5
0
        static async Task WithdrawTest()
        {
            try
            {
                HttpHelp      httpHelp = new HttpHelp();
                string        url      = host + "/api/v1/withdraw";
                WithdrawInput inputDto = new WithdrawInput
                {
                    Symbol  = "VHKD",
                    Address = "VBssvPs5ayEzYMfBxVN3Ux2uGzgBBVBR2S",
                    Amount  = 1
                };
                string input    = JsonConvert.SerializeObject(inputDto);
                var    response = httpHelp.HttpPost <OperateMessage <string> >(url,
                                                                               ApiKey,
                                                                               input,
                                                                               ApiSign.CreateSign(SecretKey, input)
                                                                               );

                Console.WriteLine($"code:{response.code}");
                Console.WriteLine($"result:{response.result}");
                Console.WriteLine($"data:{response.data.ToString()}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{nameof(GetTickerTest)}出错:{ex.Message}");
            }
        }
        public async Task Execute(WithdrawInput input)
        {
            IAccount account = await _accountRepository.Get(input.AccountId);

            if (account == null)
            {
                _outputHandler.Error($"The account {input.AccountId} does not exist or is already closed.");
                return;
            }

            IDebit debit = account.Withdraw(_entityFactory, input.Amount);

            if (debit == null)
            {
                _outputHandler.Error($"The account {input.AccountId} does not have enough funds to withdraw {input.Amount}.");
                return;
            }

            await _accountRepository.Update(account, debit);

            // Publish the event to the enterprice service bus
            await _serviceBus.PublishEventAsync(new Shared.Events.WithdrawCompleted()
            {
                AccountId = input.AccountId, Amount = input.Amount.ToMoney().ToDecimal()
            });

            await _unitOfWork.Save();

            WithdrawOutput output = new WithdrawOutput(
                debit,
                account.GetCurrentBalance()
                );

            _outputHandler.Default(output);
        }
示例#7
0
        /// <summary>
        ///     Executes the Use Case.
        /// </summary>
        /// <param name="input">Input Message.</param>
        /// <returns>Task.</returns>
        public async Task Execute(WithdrawInput input)
        {
            if (input is null)
            {
                this._outputPort.WriteError(Messages.InputIsNull);
                return;
            }

            try
            {
                var account = await this._accountRepository.GetAccount(input.AccountId)
                              .ConfigureAwait(false);

                var debit = await this._accountService.Withdraw(account, input.Amount)
                            .ConfigureAwait(false);

                await this._unitOfWork.Save()
                .ConfigureAwait(false);

                this.BuildOutput(debit, account);
            }
            catch (AccountNotFoundException notFoundEx)
            {
                this._outputPort.NotFound(notFoundEx.Message);
            }
            catch (MoneyShouldBePositiveException outOfBalanceEx)
            {
                this._outputPort.OutOfBalance(outOfBalanceEx.Message);
            }
        }
        public async Task <IActionResult> Withdraw([FromBody] WithdrawRequest message)
        {
            var request = new WithdrawInput(message.AccountId, message.Amount);

            await withdrawInput.Process(request);

            return(withdrawPresenter.ViewModel);
        }
示例#9
0
        public void GivenValidData_InputCreated()
        {
            var actual = new WithdrawInput(
                new AccountId(Guid.NewGuid()),
                new PositiveMoney(10));

            Assert.NotNull(actual);
        }
示例#10
0
        public async Task <IActionResult> Withdraw([FromForm][Required] WithdrawRequest request)
        {
            var input = new WithdrawInput(
                new AccountId(request.AccountId),
                new PositiveMoney(request.Amount));
            await _mediator.PublishAsync(input);

            return(_presenter.ViewModel);
        }
示例#11
0
        public void GivenValidData_InputCreated()
        {
            var actual = new WithdrawInput(
                Guid.NewGuid(),
                new PositiveAmount(10)
                );

            Assert.NotNull(actual);
        }
示例#12
0
        public override Empty Withdraw(WithdrawInput input)
        {
            var votingRecord = State.VotingRecords[input.VoteId];

            Assert(votingRecord != null, "Voting record not found.");

            var votingEventHash = new VotingEvent
            {
                Topic   = votingRecord.Topic,
                Sponsor = votingRecord.Sponsor
            }.GetHash();

            var votingEvent = State.VotingEvents[votingEventHash];

            Assert(votingEvent.CurrentEpoch > votingRecord.EpochNumber,
                   "Cannot withdraw votes of on-going voting event.");

            // Update VotingRecord.
            votingRecord.IsWithdrawn          = true;
            votingRecord.WithdrawTimestamp    = Context.CurrentBlockTime.ToTimestamp();
            State.VotingRecords[input.VoteId] = votingRecord;

            var votingGoingHash = new VotingResult
            {
                Sponsor     = votingRecord.Sponsor,
                Topic       = votingRecord.Topic,
                EpochNumber = votingRecord.EpochNumber
            }.GetHash();

            var votingHistories = UpdateHistoryAfterWithdrawing(votingRecord.Voter, votingEventHash, input.VoteId);

            var votingResult = State.VotingResults[votingGoingHash];

            votingResult.Results[votingRecord.Option] -= votingRecord.Amount;
            if (!votingHistories.Votes[votingEventHash.ToHex()].ActiveVotes.Any())
            {
                votingResult.VotersCount -= 1;
            }

            State.VotingResults[votingGoingHash] = votingResult;

            if (!State.VotingEvents[votingEventHash].Delegated)
            {
                State.TokenContract.Unlock.Send(new UnlockInput
                {
                    From   = votingRecord.Voter,
                    Symbol = votingRecord.Currency,
                    Amount = votingRecord.Amount,
                    LockId = input.VoteId,
                    To     = Context.Self,
                    Usage  = $"Withdraw votes for {votingRecord.Topic}"
                });
            }

            return(new Empty());
        }
示例#13
0
        public async Task <IActionResult> Withdraw([FromBody][Required] WithdrawRequest request)
        {
            var withdrawInput = new WithdrawInput(
                request.AccountId,
                new PositiveMoney(request.Amount)
                );
            await _withdrawUseCase.Execute(withdrawInput);

            return(_presenter.ViewModel);
        }
        public async Task Execute(WithdrawInput input)
        {
            var account = await _accountRepository.Get(input.AccountId);

            var debit = account.Withdraw(_entityFactory, input.Amount);
            await _accountRepository.Update(account, debit);

            await _unitOfWork.Save();

            BuildOutput(debit, account);
        }
示例#15
0
        private async Task <TransactionResult> WithdrawWithException(ECKeyPair owner, Hash voteId)
        {
            var voterStub = GetVoteContractTester(owner);
            var input     = new WithdrawInput
            {
                VoteId = voteId
            };

            var withdrawResult = (await voterStub.Withdraw.SendWithExceptionAsync(input)).TransactionResult;

            return(withdrawResult);
        }
        public async Task <IActionResult> Withdraw(
            [FromServices] IMediator mediator,
            [FromServices] WithdrawPresenter presenter,
            [FromForm][Required] WithdrawRequest request)
        {
            var input = new WithdrawInput(
                request.AccountId,
                request.Amount);
            await mediator.PublishAsync(input)
            .ConfigureAwait(false);

            return(presenter.ViewModel);
        }
示例#17
0
        public virtual async Task WithdrawAsync(Guid id, WithdrawInput input)
        {
            var account = await _repository.GetAsync(id);

            if (account.UserId != CurrentUser.GetId())
            {
                throw new AbpAuthorizationException();
            }

            var accountWithdrawalManager = ServiceProvider.GetRequiredService <IAccountWithdrawalManager>();

            await accountWithdrawalManager.StartWithdrawalAsync(account, input.WithdrawalMethod, input.Amount,
                                                                input.ExtraProperties);
        }
示例#18
0
        /// <summary>
        /// Executes the Use Case.
        /// </summary>
        /// <param name="input">Input Message.</param>
        /// <returns>Task.</returns>
        public async Task Execute(WithdrawInput input)
        {
            try
            {
                var account = await this._accountRepository.Get(input.AccountId);

                var debit = await this._accountService.Withdraw(account, input.Amount);

                await this._unitOfWork.Save();

                this.BuildOutput(debit, account);
            }
            catch (AccountNotFoundException notFoundEx)
            {
                this._outputPort.NotFound(notFoundEx.Message);
                return;
            }
            catch (MoneyShouldBePositiveException outOfBalanceEx)
            {
                this._outputPort.OutOfBalance(outOfBalanceEx.Message);
                return;
            }
        }
示例#19
0
 public void GivenValidData_InputCreated()
 {
     WithdrawInput actual = new WithdrawInput(Guid.NewGuid(), 10);
     Assert.NotNull(actual);
 }
示例#20
0
 public virtual Task WithdrawAsync(Guid id, WithdrawInput input)
 {
     return(_service.WithdrawAsync(id, input));
 }