Example #1
0
        private void AddComponentStats(StringBuilder benchLog)
        {
            IEnumerable <string> walletNames = this.coldStakingManager.GetWalletsNames();

            if (walletNames.Any())
            {
                benchLog.AppendLine();
                benchLog.AppendLine("======Wallets======");

                foreach (string walletName in walletNames)
                {
                    // Get all the accounts, including the ones used for cold staking.
                    // TODO: change GetAccounts to accept a filter.
                    foreach (HdAccount account in this.coldStakingManager.GetAccounts(walletName))
                    {
                        AccountBalance accountBalance = this.coldStakingManager.GetBalances(walletName, account.Name).Single();
                        benchLog.AppendLine(($"{walletName}/{account.Name}" + ",").PadRight(LoggingConfiguration.ColumnLength + 20)
                                            + (" Confirmed balance: " + accountBalance.AmountConfirmed.ToString()).PadRight(LoggingConfiguration.ColumnLength + 20)
                                            + " Unconfirmed balance: " + accountBalance.AmountUnconfirmed.ToString());
                    }

                    HdAccount coldStakingAccount = this.coldStakingManager.GetColdStakingAccount(this.coldStakingManager.GetWallet(walletName), true);
                    if (coldStakingAccount != null)
                    {
                        AccountBalance accountBalance = this.coldStakingManager.GetBalances(walletName, coldStakingAccount.Name).Single();
                        benchLog.AppendLine(($"{walletName}/{coldStakingAccount.Name}" + ",").PadRight(LoggingConfiguration.ColumnLength + 20)
                                            + (" Confirmed balance: " + accountBalance.AmountConfirmed.ToString()).PadRight(LoggingConfiguration.ColumnLength + 20)
                                            + " Unconfirmed balance: " + accountBalance.AmountUnconfirmed.ToString());
                    }

                    HdAccount hotStakingAccount = this.coldStakingManager.GetColdStakingAccount(this.coldStakingManager.GetWallet(walletName), false);
                    if (hotStakingAccount != null)
                    {
                        AccountBalance accountBalance = this.coldStakingManager.GetBalances(walletName, hotStakingAccount.Name).Single();
                        benchLog.AppendLine(($"{walletName}/{hotStakingAccount.Name}" + ",").PadRight(LoggingConfiguration.ColumnLength + 20)
                                            + (" Confirmed balance: " + accountBalance.AmountConfirmed.ToString()).PadRight(LoggingConfiguration.ColumnLength + 20)
                                            + " Unconfirmed balance: " + accountBalance.AmountUnconfirmed.ToString());
                    }
                }
            }
        }
        public static AccountBalance DataRowToObject(DataRow dr)
        {
            AccountBalance TheAccountBalance = new AccountBalance();

            TheAccountBalance.AccountsYearID            = int.Parse(dr["AccountsYearID"].ToString());
            TheAccountBalance.FinYearStartDate          = (dr["FinYearStartDate"].ToString());
            TheAccountBalance.FinYearCloseDate          = (dr["FinYearCloseDate"].ToString());
            TheAccountBalance.AccountsID                = int.Parse(dr["AccountsID"].ToString());
            TheAccountBalance.AccountDescription        = dr["AccountDescription"].ToString();
            TheAccountBalance.FinYearOpeningBalance     = decimal.Parse(dr["FinYearOpeningBalance"].ToString());
            TheAccountBalance.FinYearOpeningBalanceType = dr["FinYearOpeningBalanceType"].ToString();
            TheAccountBalance.Total_DB_Balance_Month_04 = dr["Total_DB_Balance_Month_04"] != DBNull.Value ? decimal.Parse(dr["Total_DB_Balance_Month_04"].ToString()) : 0;
            TheAccountBalance.Total_CR_Balance_Month_04 = dr["Total_CR_Balance_Month_04"] != DBNull.Value ? decimal.Parse(dr["Total_CR_Balance_Month_04"].ToString()) : 0;
            TheAccountBalance.Total_DEBIT_Transactions  = dr["Total_DEBIT_Transactions"] != DBNull.Value ? decimal.Parse(dr["Total_DEBIT_Transactions"].ToString()) : 0;
            TheAccountBalance.Total_CREDIT_Transactions = dr["Total_CREDIT_Transactions"] != DBNull.Value ? decimal.Parse(dr["Total_CREDIT_Transactions"].ToString()) : 0;
            TheAccountBalance.AuthorisationID           = dr["AuthorisationID"] != DBNull.Value ? int.Parse(dr["AuthorisationID"].ToString()) : 0;
            TheAccountBalance.SocietyID = int.Parse(dr["SocietyID"].ToString());
            TheAccountBalance.OfficeID  = int.Parse(dr["OfficeID"].ToString());

            return(TheAccountBalance);
        }
        public IActionResult GetBalance([FromQuery] WalletBalanceRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                WalletBalanceModel model = new WalletBalanceModel();

                var accounts = this.walletManager.GetAccounts(request.WalletName).ToList();
                foreach (var account in accounts)
                {
                    var result = account.GetSpendableAmount();

                    AccountBalance balance = new AccountBalance
                    {
                        CoinType          = this.coinType,
                        Name              = account.Name,
                        HdPath            = account.HdPath,
                        AmountConfirmed   = result.ConfirmedAmount,
                        AmountUnconfirmed = result.UnConfirmedAmount,
                    };

                    model.AccountsBalances.Add(balance);
                }

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult GetBalance([FromQuery] WalletBalanceRequest request)
        {
            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                WalletBalanceModel model = new WalletBalanceModel {
                    AccountsBalances = new List <AccountBalance>()
                };

                var accounts = this.walletManager.GetAccountsByCoinType(request.WalletName, this.coinType).ToList();
                foreach (var account in accounts)
                {
                    var allTransactions = account.ExternalAddresses.SelectMany(a => a.Transactions)
                                          .Concat(account.InternalAddresses.SelectMany(i => i.Transactions)).ToList();

                    AccountBalance balance = new AccountBalance
                    {
                        CoinType          = this.coinType,
                        Name              = account.Name,
                        HdPath            = account.HdPath,
                        AmountConfirmed   = allTransactions.Sum(t => t.SpendableAmount(true)),
                        AmountUnconfirmed = allTransactions.Sum(t => t.SpendableAmount(false)),
                    };

                    model.AccountsBalances.Add(balance);
                }

                return(this.Json(model));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #5
0
        // method to view current balance account typewise
        public double[] ViewCurrentBalance(string accountType)
        {
            double[] balance = new double[2];

            // call repository method
            AccountBalance accountBalance = _AccountBalanceRepo.ViewCurrentBalance();

            // if at least one record is in the db records in the database
            if (accountBalance != null)
            {
                balance[0] = 0;
                if (accountType == "rnd")
                {
                    balance[1] = (double)accountBalance.rnd;
                }
                else if (accountType == "canteen")
                {
                    balance[1] = (double)accountBalance.canteen;
                }
                else if (accountType == "ceocar")
                {
                    balance[1] = (double)accountBalance.ceocar;
                }
                else if (accountType == "marketing")
                {
                    balance[1] = (double)accountBalance.marketing;
                }
                else if (accountType == "parking")
                {
                    balance[1] = (double)accountBalance.parking;
                }
            }
            else
            {
                balance[0] = 1;
            }

            // return the result
            return(balance);
        }
        public async Task <bool> PostEntryToAccounts(Entry entry, bool rollBack = false)
        {
            var accountsId = entry.Items.Select(a => a.AccountId).Distinct();
            var accounts   = _accountRepo.NativeGetAll().Where(e => accountsId.Contains(e.Id));

            foreach (var item in accounts)
            {
                var accountEntryItems = entry.Items.Where(e => e.AccountId == item.Id);
                var totalDebit        = accountEntryItems.Sum(e => e.Debit);
                var totalCredit       = accountEntryItems.Sum(e => e.Credit);
                var accountBalance    = await _accountBalanceRepo.GetAccountBalanceAsync(item.Id);

                if (rollBack)
                {
                    totalDebit  = totalDebit * -1;
                    totalCredit = totalCredit * -1;
                }

                if (!rollBack && accountBalance == null)
                {
                    accountBalance = new AccountBalance {
                        AccountId = item.Id, Debit = totalDebit, Credit = totalCredit
                    };
                    await _accountBalanceRepo.AddAsync(accountBalance, false);
                }
                else
                {
                    accountBalance.Debit  += totalDebit;
                    accountBalance.Credit += totalCredit;
                    _accountBalanceRepo.Edit(accountBalance, false);
                }
            }

            if (!rollBack)
            {
                entry.IsPosted = true;
            }

            return(await Task.FromResult(true));
        }
        public void HasQuoteBaseBalance()
        {
            // Arrange
            var exchangeApi     = ExchangeServiceHelper.GetExchangeService();
            var exchangeService = new WpfExchangeService(exchangeApi);
            var tradeViewModel  = new TradeViewModel(exchangeService, new DebugLogger());

            var quoteBalance = new AccountBalance {
                Free = 299m
            };
            var baseBalance = new AccountBalance {
                Free = 0.000123m
            };

            // Act
            tradeViewModel.QuoteAccountBalance = quoteBalance;
            tradeViewModel.BaseAccountBalance  = baseBalance;

            // Assert
            Assert.IsTrue(tradeViewModel.HasBaseBalance);
            Assert.IsTrue(tradeViewModel.HasQuoteBalance);
        }
Example #8
0
        public int UpdateFinyearOpeningBalance(AccountBalance theAccountBalance)
        {
            int ReturnValue = 0;

            using (SqlCommand InsertCommand = new SqlCommand())
            {
                InsertCommand.CommandType = CommandType.StoredProcedure;
                InsertCommand.Parameters.Add(GetParameter("@ReturnValue", SqlDbType.Int, ReturnValue)).Direction = ParameterDirection.Output;
                InsertCommand.Parameters.Add(GetParameter("@AccountsYearID", SqlDbType.Int, theAccountBalance.AccountsYearID));
                InsertCommand.Parameters.Add(GetParameter("@FinYearStartDate", SqlDbType.VarChar, theAccountBalance.FinYearStartDate));
                InsertCommand.Parameters.Add(GetParameter("@AccountsID", SqlDbType.Int, theAccountBalance.AccountsID));
                InsertCommand.Parameters.Add(GetParameter("@FinYearOpeningBalance", SqlDbType.Decimal, theAccountBalance.FinYearOpeningBalance));
                InsertCommand.Parameters.Add(GetParameter("@FinYearOpeningBalanceType", SqlDbType.VarChar, theAccountBalance.FinYearOpeningBalanceType));
                InsertCommand.Parameters.Add(GetParameter("@SocietyID", SqlDbType.Int, theAccountBalance.SocietyID));
                InsertCommand.Parameters.Add(GetParameter("@OfficeID", SqlDbType.Int, theAccountBalance.OfficeID));

                InsertCommand.CommandText = "pAccounts_Balance_FinYearOpeningBalance_Update";
                ExecuteStoredProcedure(InsertCommand);
                ReturnValue = int.Parse(InsertCommand.Parameters[0].Value.ToString());
                return(ReturnValue);
            }
        }
Example #9
0
        public void ViewBalance_Balance_Not_Exists_In_Db()
        {
            AccountBalance expected = new AccountBalance();

            expected.year      = 0;
            expected.month     = 0;
            expected.rnd       = 0;
            expected.canteen   = 0;
            expected.ceocar    = 0;
            expected.marketing = 0;
            expected.parking   = 0;

            var mockAccountBalanceRepo = new Mock <IAccountBalanceRepo>();

            mockAccountBalanceRepo.Setup(x => x.ViewBalance(It.IsAny <int>(), It.IsAny <int>())).Returns((accountbalance)null);
            AccountBalanceService accountBalanceService = new AccountBalanceService(mockAccountBalanceRepo.Object);


            AccountBalance actual = accountBalanceService.ViewBalance(2016, 1);

            AssertObjects.PropertyValuesAreEquals(actual, expected);
        }
Example #10
0
        public static AccountHistoryDto Map(Account account, AccountBalance startBalance, decimal currentBalance, IEnumerable <Transfer> incomingTrasnfers, IEnumerable <Transfer> outgoingTransfers)
        {
            if (account == null)
            {
                return(null);
            }
            AccountHistoryDto accountDto = new AccountHistoryDto();

            accountDto.Id   = account.Id;
            accountDto.Name = account.Name;
            accountDto.AccountStartBalance   = startBalance.Balance;
            accountDto.AccountCurrentBalance = currentBalance;
            foreach (var transfer in incomingTrasnfers)
            {
                accountDto.IncomingTransfers.Add(TransferMapper.Map(transfer));
            }
            foreach (var transfer in outgoingTransfers)
            {
                accountDto.OutgoingTransfers.Add(TransferMapper.Map(transfer));
            }
            int      numberOfDays = (int)Math.Ceiling((DateTime.Now - startBalance.StartDate).TotalDays);
            DateTime accountBalanceHistoryDate = startBalance.StartDate;
            decimal  historyBalance            = startBalance.Balance;

            for (int i = 0; i < numberOfDays; i++)
            {
                historyBalance = historyBalance
                                 + incomingTrasnfers.Where(t => t.TransferDate.Date == accountBalanceHistoryDate.Date).Sum(t => t.Amount)
                                 - outgoingTransfers.Where(t => t.TransferDate.Date == accountBalanceHistoryDate.Date).Sum(t => t.Amount);
                accountDto.AccountBalanceHistory.Add(new AccountBalanceHistoryDto
                {
                    BalanceDate = accountBalanceHistoryDate,
                    Balance     = historyBalance
                });
                accountBalanceHistoryDate = accountBalanceHistoryDate.AddDays(1);
            }
            return(accountDto);
        }
        private string SendMail(string email, AccountBalance accountBalance, EmailTemplate emailTemplate, string note)
        {
            try
            {
                using (var mail = new MailMessage())
                {
                    mail.From = new MailAddress(_appSetting.EmailAddress);
                    mail.To.Add(email);
                    mail.Subject = emailTemplate.Subject;

                    var    mailBodyFile = _mailFileProvider.GetFileInfo(emailTemplate.Body);
                    string strMailBody  = "";
                    using (var fileReader = new StreamReader(mailBodyFile.PhysicalPath))
                    {
                        strMailBody = fileReader.ReadToEnd();
                    }
                    strMailBody     = strMailBody.Replace("@Model.AccountName", accountBalance.AccountName1);
                    strMailBody     = strMailBody.Replace("@Model.DateTime", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    strMailBody     = strMailBody.Replace("@Model.Account", accountBalance.AccountId);
                    strMailBody     = strMailBody.Replace("@Model.ActualBalance", accountBalance.ActualBalance);
                    strMailBody     = strMailBody.Replace("@Model.Note", note);
                    mail.Body       = strMailBody;
                    mail.IsBodyHtml = true;

                    using (var SmtpServer = new SmtpClient(_appSetting.EmailHost, _appSetting.EmailPort))
                    {
                        SmtpServer.Credentials = new System.Net.NetworkCredential(_appSetting.EmailAddress, _appSetting.EmailPassword);
                        SmtpServer.EnableSsl   = true;
                        SmtpServer.Send(mail);
                    }
                }
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #12
0
        /// <summary>
        /// Adds the item.
        /// </summary>
        /// <param name="aggregateId">The aggregate identifier.</param>
        /// <param name="profitAbsolute">The profit absolute.</param>
        private void AddItem(Guid aggregateId, decimal profitAbsolute)
        {
            if (_modelRepository.GetById(aggregateId) != null)
            {
                return;
            }

            //Get date from transaction
            var balanceDate = _transactionRepository.GetById(aggregateId).OrderDate;

            //Get previous balance
            var lastBalance = _modelRepository.GetAll().OrderByDescending(a => a.Date).FirstOrDefault(a => a.Date < balanceDate);

            //Add new balance
            var item = new AccountBalance(aggregateId, lastBalance?.Balance + profitAbsolute ?? profitAbsolute, profitAbsolute, balanceDate);

            _modelRepository.Add(item);

            //Get future balances
            var futureAccountBalances = _modelRepository.GetAll().OrderBy(a => a.Date).Where(a => a.Date > balanceDate);

            using (var enumerator = futureAccountBalances.GetEnumerator())
            {
                var oldBalance = item.Balance;
                while (enumerator.MoveNext())
                {
                    var newBalance = new AccountBalance(
                        enumerator.Current.TransactionId,
                        oldBalance + enumerator.Current.BalanceChange,
                        enumerator.Current.BalanceChange,
                        enumerator.Current.Date);

                    _modelRepository.Update(newBalance);

                    oldBalance = newBalance.Balance;
                }
            }
        }
Example #13
0
        public async Task <ServiceResponse <AccountBalance> > DepositAccountBalance(AccountBalance accountBalance)
        {
            try
            {
                var depositAccountDetails = await _bankDbContext.AccountBalances.Include(x => x.Customer)
                                            .ThenInclude(x => x.Account)
                                            .FirstOrDefaultAsync(x => x.AccountNumber == accountBalance.AccountNumber && x.AccountId == accountBalance.AccountId);

                if (depositAccountDetails != null)
                {
                    accountBalance.AccountBalanceId = 0; //Identity column
                    //Adding data into transaction table to capture transaction history
                    TransactionAudit audit = new TransactionAudit();
                    audit.ActionId    = 2; //Deposit
                    audit.CustomerId  = depositAccountDetails.CustomerId;
                    audit.Balance     = accountBalance.Balance;
                    audit.CreatedDate = DateTime.Now;
                    await _bankDbContext.TransactionAudits.AddAsync(audit);

                    depositAccountDetails.Balance = (depositAccountDetails.Balance + accountBalance.Balance);
                    _bankDbContext.AccountBalances.Update(depositAccountDetails);
                    await _bankDbContext.SaveChangesAsync();

                    serviceResponse.Data    = depositAccountDetails;
                    serviceResponse.Message = $"Amount {accountBalance.Balance} deposited successfully..Total available balance is {depositAccountDetails.Balance}";
                    return(serviceResponse);
                }
                serviceResponse.Success = false;
                serviceResponse.Message = $"Invalid account number (or) AccountId... Please enter valid account details to deposit.";
                return(serviceResponse);
            }
            catch (Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
                return(serviceResponse);
            }
        }
Example #14
0
        public void HasQuoteBaseBalance_Zero()
        {
            // Arrange
            var cxlToken        = new CancellationToken();
            var exchangeApi     = ExchangeServiceHelper.GetExchangeService();
            var exchangeService = new WpfExchangeService(exchangeApi);
            var tradeViewModel  = new TradeViewModel(exchangeService);

            var quoteBalance = new AccountBalance {
                Free = 0m
            };
            var baseBalance = new AccountBalance {
                Free = 0m
            };

            // Act
            tradeViewModel.QuoteAccountBalance = quoteBalance;
            tradeViewModel.BaseAccountBalance  = baseBalance;

            // Assert
            Assert.IsFalse(tradeViewModel.HasBaseBalance);
            Assert.IsFalse(tradeViewModel.HasQuoteBalance);
        }
        public void AddJourneyTransaction(AccountBalance accB, string action, Transaction tr)
        {
            AccountBLL     abll     = new AccountBLL(_unit);
            AccountSummary aSummary = abll.GetAccountSummary(accB.AccountId);

            AccountBalanceJourney abj = new AccountBalanceJourney
            {
                FundAmount    = aSummary.Balance.FundAmount,
                AvailableFund = aSummary.Balance.AvailableFund,
                Margin        = aSummary.PositionMarginSum,
                Reserve       = aSummary.OrderReserveSum,
                FeeSum        = aSummary.Balance.FeeSum,
                PositionValue = aSummary.PositionValueSum,
                TotalBalance  = aSummary.Balance.TotalBalance,
                Action        = action,
                AccountId     = accB.AccountId,

                UpdateDT = DateTime.Now
            };

            if (tr != null)
            {
                abj.TransactionId = tr.Id;
                abj.TradingDate   = tr.TradingDate;
            }



            if (aSummary != null)
            {
                string aSummaryString = XMLHelper.SerializeObject(aSummary);

                abj.AccountSummaryXML = aSummaryString;
            }

            base.Create(abj);
        }
Example #16
0
        public AccountBalance GetAccountBalance(Common.StockExchange.Types.StockExchange stockExchange, string currency)
        {
            AccountBalance accountBalance = new AccountBalance(stockExchange.ToString());

            BaseRequest baseRequest = new BaseRequest("/v1/balances", GetNonce());
            string      response    = SendRequest(baseRequest, "POST");

            JArray resultsJson = JsonConvert.DeserializeObject <JArray>(response);

            foreach (JToken ticker in resultsJson)
            {
                string  account          = ticker["type"].ToString();
                string  currencyTicker   = ticker["currency"].ToString().ToUpper();
                decimal availableBalance = Convert.ToDecimal(ticker["available"]);
                decimal amountBalance    = Convert.ToDecimal(ticker["amount"]);

                if (currencyTicker.Equals(currency))
                {
                    accountBalance.Balances.Add(new Balance(account, currencyTicker, availableBalance, amountBalance));
                }
            }

            return(accountBalance);
        }
        public void InitCreate(AccountBalance ab)
        {
            AccountBalanceJourney abj = new AccountBalanceJourney
            {
                AvailableFund = 0,
                Margin        = 0,
                PositionValue = 0,
                TotalBalance  = 0,
                Action        = "AccountInit",
                AccountId     = ab.AccountId,
                UpdateDT      = DateTime.Now
            };

            AccountSummary aSummary = new AccountBLL(_unit).GetAccountSummary(ab.AccountId);

            if (aSummary != null)
            {
                string aSummaryString = XMLHelper.SerializeObject(aSummary);

                abj.AccountSummaryXML = aSummaryString;
            }

            base.Create(abj);
        }
Example #18
0
        public ActionResult Pay(SalaryPaid salarypaid)
        {
            var  userinfo = new UserInfo();
            User user     = userinfo.GetUser(salarypaid.UserID);

            if (user != null)
            {
                salarypaid.PaidDate = DateTime.UtcNow;
                salarypaid.Salary   = user.Salary;

                if (ModelState.IsValid)
                {
                    db.SalaryPaids.Add(salarypaid);
                    // add expense
                    Category categorySalary = db.Categories.FirstOrDefault(n => n.Category1 == "Salary");
                    if (categorySalary != null)
                    {
                        var expenseController = new ExpenseController();
                        var accountBalance    = new AccountBalance {
                            AccountOf = salarypaid.UserID, Amount = salarypaid.Paid, CategoryProduct = categorySalary.CategoryID
                        };
                        expenseController.CreateExpense(accountBalance);

                        db.SaveChanges();
                    }
                    else
                    {
                        goto Error;
                    }
                    return(RedirectToAction("Index"));
                }
            }
Error:
            ViewBag.UserID = new SelectList(db.Users, "UserID", "LogName", salarypaid.UserID);
            return(View(salarypaid));
        }
Example #19
0
        public override void OnReceive(Context context, Intent intent)
        {
            var accountBalance = App.GetAccountBalanceForNotification();

            if (accountBalance == null)
            {
                return;
            }

            if (_accountBalance == null)
            {
                _accountBalance = accountBalance;
                return;
            }

            Fill(accountBalance, out var title, out var text);
            _accountBalance = accountBalance;

            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }
            SendNotification(context, intent, title, text);
        }
        /// <summary>
        /// Parse data from account balance box
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private AccountBalance ResolveBalanceBox(HtmlNode node)
        {
            var accountBalance = new AccountBalance();

            foreach (var tr in node.SelectNodes(".//table[@class='data']/tr"))
            {
                var td = tr.SelectNodes(".//td");

                switch (td[0].InnerText.Trim())
                {
                case var name when name.Equals("Available Funds", StringComparison.InvariantCultureIgnoreCase):
                    accountBalance.AvailableFunds = ParserHelpers.ParseDecimal(td[1].InnerText);

                    break;

                case var name when name.Equals("Invested Funds", StringComparison.InvariantCultureIgnoreCase):
                    accountBalance.InvestedFunds = ParserHelpers.ParseDecimal(td[1].InnerText);

                    break;
                }
            }

            return(accountBalance);
        }
Example #21
0
        public OutAccount GetOutAccountFromObjs(Account account, AccountBalance balance)
        {
            OutAccount outAcc = null;

            if (account != null)
            {
                outAcc = new OutAccount
                {
                    Name        = account.Name,
                    Description = account.Description,
                    Owner       = account.Owner,
                    Id          = account.Id,
                    Status      = account.Status,
                    CreateDate  = account.CreateDate,
                    CreatedBy   = account.CreatedBy,
                    ZoneId      = account.ZoneId,
                    BrokerId    = account.BrokerId
                };

                if (balance != null)
                {
                    outAcc.TotalBalance    = balance.TotalBalance;
                    outAcc.FundAmount      = balance.FundAmount;
                    outAcc.AvailableFund   = balance.AvailableFund;
                    outAcc.Reserve         = balance.Reserve;
                    outAcc.Margin          = balance.Margin;
                    outAcc.FeeSum          = balance.FeeSum;
                    outAcc.PositionValue   = balance.PositionValue;
                    outAcc.TradingDate     = balance.TradingDate;
                    outAcc.BalanceUpdateDT = balance.UpdateDT;
                    outAcc.AccountId       = balance.AccountId;
                }
            }

            return(outAcc);
        }
Example #22
0
        public static void VerifyAccountBalance(
            AccountBalance toVerify,
            ExchangeType source,
            ImmutableHashSet <Currency> supported)
        {
            ResponseVerification.VerifyApiResult(toVerify, source);

            CollectionAssert.IsNotEmpty(toVerify.BalanceByCurrency);

            foreach (var c in supported)
            {
                Assert.That(toVerify.BalanceByCurrency.ContainsKey(c));

                var individualBalance = toVerify.BalanceByCurrency[c];

                ResponseVerification.VerifyApiResult(individualBalance, source);

                Assert.That(individualBalance.BalanceCurrency == c);
                Assert.That(individualBalance.AvailableToTrade >= 0);
                Assert.That(individualBalance.TotalBalance >= 0);
                Assert.That(individualBalance.AvailableToTrade + individualBalance.Reserved ==
                            individualBalance.TotalBalance);
            }
        }
Example #23
0
        private static void Fill(AccountBalance accountBalance, out string title, out string text)
        {
            title = string.Empty;
            text  = string.Empty;
            if (_accountBalance.Balance != accountBalance.Balance)
            {
                decimal.TryParse(_accountBalance.Balance, out var oldBalance);
                decimal.TryParse(accountBalance.Balance, out var currentBalance);
                var diff = currentBalance - oldBalance;
                text  = $"{(diff > 0 ? "Пополнение на" : "Списание")} {diff} рублей.";
                title = "М11 - Изменение баланса";
            }
            else
            {
                if (_accountBalance.Tickets != null)
                {
                    foreach (var ticket in _accountBalance.Tickets)
                    {
                        var currentTicket = accountBalance.Tickets?.FirstOrDefault(x => x.StartDate == ticket.StartDate);
                        if (currentTicket == null)
                        {
                            text  = $"Закончились поездки по абонементу {ticket.ShortDescription}.";
                            title = "М11 - Абонемент";
                            break;
                        }

                        if (ticket.RemainingTripsCount != currentTicket.RemainingTripsCount)
                        {
                            text  = $"Произошло списание поездки по абонементу {ticket.ShortDescription}, осталось {currentTicket.RemainingTripsCount} (из {ticket.TotalTripsCount}).";
                            title = "М11 - Абонемент";
                            break;
                        }
                    }
                }
            }
        }
 public ActionResult Create(AccountBalance accountbalance)
 {
     if (User.Identity.IsAuthenticated)
     {
         accountbalance.Dated = DateTime.UtcNow;
         accountbalance.AddBy = _Userinfo.GetUserSession()
                                .UserID;
         accountbalance.IsBoughtProduct = false;
         accountbalance.IsAddedMoney    = true;
         accountbalance.IsExpense       = false;
         if (accountbalance.Amount < 0)
         {
             ModelState.AddModelError("Amount", "Amount can't be negative.");
         }
         if (ModelState.IsValid)
         {
             _Db.AccountBalances.Add(accountbalance);
             _Db.SaveChanges();
             return(RedirectToAction("Index"));
         }
     }
     GetUsers();
     return(View(accountbalance));
 }
        public void ProcessTransactionWithValidColdStakingSetupLoadsTransactionsIntoWalletIfMatching()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            Directory.CreateDirectory(dataFolder.WalletPath);

            Wallet.Wallet wallet = this.walletFixture.GenerateBlankWallet("myWallet", "password");
            (ExtKey ExtKey, string ExtPubKey)accountKeys = WalletTestsHelpers.GenerateAccountKeys(wallet, "password", "m/44'/0'/0'");

            (PubKey PubKey, BitcoinPubKeyAddress Address)spendingKeys = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/0");
            (PubKey PubKey, BitcoinPubKeyAddress Address)changeKeys   = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "1/0");

            Wallet.Wallet coldWallet = this.walletFixture.GenerateBlankWallet("myColdWallet", "password");
            (ExtKey ExtKey, string ExtPubKey)accountColdKeys = WalletTestsHelpers.GenerateAccountKeys(coldWallet, "password", $"m/44'/0'/{ColdStakingManager.ColdWalletAccountIndex}'");

            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationColdKeys = WalletTestsHelpers.GenerateAddressKeys(coldWallet, accountColdKeys.ExtPubKey, "0/0");

            Wallet.Wallet hotWallet = this.walletFixture.GenerateBlankWallet("myHotWallet", "password");
            (ExtKey ExtKey, string ExtPubKey)accountHotKeys = WalletTestsHelpers.GenerateAccountKeys(hotWallet, "password", $"m/44'/0'/{ColdStakingManager.HotWalletAccountIndex}'");

            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationHotKeys = WalletTestsHelpers.GenerateAddressKeys(hotWallet, accountHotKeys.ExtPubKey, "0/0");

            var spendingAddress = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/0'/0/0",
                Address      = spendingKeys.Address.ToString(),
                Pubkey       = spendingKeys.PubKey.ScriptPubKey,
                ScriptPubKey = spendingKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            var destinationColdAddress = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/{ColdStakingManager.ColdWalletAccountIndex}'/0/0",
                Address      = destinationColdKeys.Address.ToString(),
                Pubkey       = destinationColdKeys.PubKey.ScriptPubKey,
                ScriptPubKey = destinationColdKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            var destinationHotAddress = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/{ColdStakingManager.HotWalletAccountIndex}'/0/0",
                Address      = destinationHotKeys.Address.ToString(),
                Pubkey       = destinationHotKeys.PubKey.ScriptPubKey,
                ScriptPubKey = destinationHotKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            var changeAddress = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/0'/1/0",
                Address      = changeKeys.Address.ToString(),
                Pubkey       = changeKeys.PubKey.ScriptPubKey,
                ScriptPubKey = changeKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            // Generate a spendable transaction
            (ChainIndexer chain, uint256 blockhash, Block block)chainInfo = WalletTestsHelpers.CreateChainAndCreateFirstBlockWithPaymentToAddress(wallet.Network, spendingAddress);
            TransactionData spendingTransaction = WalletTestsHelpers.CreateTransactionDataFromFirstBlock(chainInfo);

            spendingAddress.Transactions.Add(spendingTransaction);

            wallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
            {
                Index             = 0,
                Name              = "account 0",
                HdPath            = "m/44'/0'/0'",
                ExtendedPubKey    = accountKeys.ExtPubKey,
                ExternalAddresses = new List <HdAddress> {
                    spendingAddress
                },
                InternalAddresses = new List <HdAddress> {
                    changeAddress
                }
            });

            coldWallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
            {
                Index             = ColdStakingManager.ColdWalletAccountIndex,
                Name              = ColdStakingManager.ColdWalletAccountName,
                HdPath            = $"m/44'/0'/{ColdStakingManager.ColdWalletAccountIndex}'",
                ExtendedPubKey    = accountColdKeys.ExtPubKey,
                ExternalAddresses = new List <HdAddress> {
                    destinationColdAddress
                },
                InternalAddresses = new List <HdAddress> {
                }
            });

            hotWallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
            {
                Index             = ColdStakingManager.HotWalletAccountIndex,
                Name              = ColdStakingManager.HotWalletAccountName,
                HdPath            = $"m/44'/0'/{ColdStakingManager.HotWalletAccountIndex}'",
                ExtendedPubKey    = accountHotKeys.ExtPubKey,
                ExternalAddresses = new List <HdAddress> {
                    destinationHotAddress
                },
                InternalAddresses = new List <HdAddress> {
                }
            });

            var walletFeePolicy = new Mock <IWalletFeePolicy>();

            walletFeePolicy.Setup(w => w.GetMinimumFee(258, 50))
            .Returns(new Money(5000));

            var walletSettings = new WalletSettings(new NodeSettings(network: this.Network));

            var coldWalletManager = new ColdStakingManager(this.Network, chainInfo.chain, walletSettings, dataFolder, walletFeePolicy.Object,
                                                           new Mock <IAsyncProvider>().Object, new NodeLifetime(), new ScriptAddressReader(), this.LoggerFactory.Object, DateTimeProvider.Default, new Mock <ISignals>().Object, new Mock <IBroadcasterManager>().Object);

            coldWalletManager.Wallets.Add(wallet);
            coldWalletManager.Wallets.Add(coldWallet);
            coldWalletManager.LoadKeysLookupLock();

            // Create another instance for the hot wallet as it is not allowed to have both wallets on the same instance.
            var hotWalletManager = new ColdStakingManager(this.Network, chainInfo.chain, walletSettings, dataFolder, walletFeePolicy.Object,
                                                          new Mock <IAsyncProvider>().Object, new NodeLifetime(), new ScriptAddressReader(), this.LoggerFactory.Object, DateTimeProvider.Default, new Mock <ISignals>().Object, new Mock <IBroadcasterManager>().Object);

            hotWalletManager.Wallets.Add(hotWallet);
            hotWalletManager.LoadKeysLookupLock();

            // Create a cold staking setup transaction.
            Transaction transaction = this.CreateColdStakingSetupTransaction(wallet, "password", spendingAddress, destinationColdKeys.PubKey, destinationHotKeys.PubKey,
                                                                             changeAddress, new Money(7500), new Money(5000));

            coldWalletManager.ProcessTransaction(transaction);
            hotWalletManager.ProcessTransaction(transaction);

            HdAddress spentAddressResult = wallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0);

            Assert.Equal(1, spendingAddress.Transactions.Count);
            Assert.Equal(transaction.GetHash(), spentAddressResult.Transactions.ElementAt(0).SpendingDetails.TransactionId);
            Assert.Equal(transaction.Outputs[1].Value, spentAddressResult.Transactions.ElementAt(0).SpendingDetails.Payments.ElementAt(0).Amount);
            Assert.Equal(transaction.Outputs[1].ScriptPubKey, spentAddressResult.Transactions.ElementAt(0).SpendingDetails.Payments.ElementAt(0).DestinationScriptPubKey);

            Assert.Equal(1, wallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).InternalAddresses.ElementAt(0).Transactions.Count);
            TransactionData changeAddressResult = wallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).InternalAddresses.ElementAt(0).Transactions.ElementAt(0);

            Assert.Equal(transaction.GetHash(), changeAddressResult.Id);
            Assert.Equal(transaction.Outputs[0].Value, changeAddressResult.Amount);
            Assert.Equal(transaction.Outputs[0].ScriptPubKey, changeAddressResult.ScriptPubKey);

            // Verify that the transaction has been recorded in the cold wallet.
            Assert.Equal(1, coldWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.Count);
            TransactionData destinationColdAddressResult = coldWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.ElementAt(0);

            Assert.Equal(transaction.GetHash(), destinationColdAddressResult.Id);
            Assert.Equal(transaction.Outputs[1].Value, destinationColdAddressResult.Amount);
            Assert.Equal(transaction.Outputs[1].ScriptPubKey, destinationColdAddressResult.ScriptPubKey);

            // Verify that the transaction has been recorded in the hot wallet.
            Assert.Equal(1, hotWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.Count);
            TransactionData destinationHotAddressResult = hotWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.ElementAt(0);

            Assert.Equal(transaction.GetHash(), destinationHotAddressResult.Id);
            Assert.Equal(transaction.Outputs[1].Value, destinationHotAddressResult.Amount);
            Assert.Equal(transaction.Outputs[1].ScriptPubKey, destinationHotAddressResult.ScriptPubKey);

            // Try withdrawing from the cold staking setup.
            Wallet.Wallet withdrawalWallet = this.walletFixture.GenerateBlankWallet("myWithDrawalWallet", "password");
            (ExtKey ExtKey, string ExtPubKey)withdrawalAccountKeys = WalletTestsHelpers.GenerateAccountKeys(wallet, "password", "m/44'/0'/0'");

            (PubKey PubKey, BitcoinPubKeyAddress Address)withdrawalKeys = WalletTestsHelpers.GenerateAddressKeys(withdrawalWallet, withdrawalAccountKeys.ExtPubKey, "0/0");

            // Withdrawing to this address.
            var withdrawalAddress = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/0'/0/0",
                Address      = withdrawalKeys.Address.ToString(),
                Pubkey       = withdrawalKeys.PubKey.ScriptPubKey,
                ScriptPubKey = withdrawalKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            withdrawalWallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
            {
                Index             = 0,
                Name              = "account 0",
                HdPath            = "m/44'/0'/0'",
                ExtendedPubKey    = accountKeys.ExtPubKey,
                ExternalAddresses = new List <HdAddress> {
                    withdrawalAddress
                },
                InternalAddresses = new List <HdAddress> {
                }
            });

            // Will spend from the cold stake address and send the change back to the same address.
            var         coldStakeAddress      = coldWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0);
            Transaction withdrawalTransaction = this.CreateColdStakingWithdrawalTransaction(coldWallet, "password", coldStakeAddress,
                                                                                            withdrawalKeys.PubKey, ColdStakingScriptTemplate.Instance.GenerateScriptPubKey(destinationColdKeys.PubKey.Hash, destinationHotKeys.PubKey.Hash),
                                                                                            new Money(750), new Money(262));

            // Wallet manager for the wallet receiving the funds.
            var receivingWalletManager = new ColdStakingManager(this.Network, chainInfo.chain, walletSettings, dataFolder, walletFeePolicy.Object,
                                                                new Mock <IAsyncProvider>().Object, new NodeLifetime(), new ScriptAddressReader(), this.LoggerFactory.Object, DateTimeProvider.Default, new Mock <ISignals>().Object, new Mock <IBroadcasterManager>().Object);

            receivingWalletManager.Wallets.Add(withdrawalWallet);
            receivingWalletManager.LoadKeysLookupLock();

            // Process the transaction in the cold wallet manager.
            coldWalletManager.ProcessTransaction(withdrawalTransaction);

            // Process the transaction in the hot wallet manager.
            hotWalletManager.ProcessTransaction(withdrawalTransaction);

            // Process the transaction in the receiving wallet manager.
            receivingWalletManager.ProcessTransaction(withdrawalTransaction);

            // Verify that the transaction has been recorded in the withdrawal wallet.
            Assert.Equal(1, withdrawalWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.Count);
            TransactionData withdrawalAddressResult = withdrawalWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.ElementAt(0);

            Assert.Equal(withdrawalTransaction.GetHash(), withdrawalAddressResult.Id);
            Assert.Equal(withdrawalTransaction.Outputs[1].Value, withdrawalAddressResult.Amount);
            Assert.Equal(withdrawalTransaction.Outputs[1].ScriptPubKey, withdrawalAddressResult.ScriptPubKey);

            // Verify that the transaction has been recorded in the cold wallet.
            Assert.Equal(2, coldWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.Count);
            TransactionData coldAddressResult = coldWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.ElementAt(1);

            Assert.Equal(withdrawalTransaction.GetHash(), coldAddressResult.Id);
            Assert.Equal(withdrawalTransaction.Outputs[0].Value, coldAddressResult.Amount);
            Assert.Equal(withdrawalTransaction.Outputs[0].ScriptPubKey, coldAddressResult.ScriptPubKey);

            // Verify that the transaction has been recorded in the hot wallet.
            Assert.Equal(2, hotWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.Count);
            TransactionData hotAddressResult = hotWallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0).Transactions.ElementAt(1);

            Assert.Equal(withdrawalTransaction.GetHash(), hotAddressResult.Id);
            Assert.Equal(withdrawalTransaction.Outputs[0].Value, hotAddressResult.Amount);
            Assert.Equal(withdrawalTransaction.Outputs[0].ScriptPubKey, hotAddressResult.ScriptPubKey);

            // Verify the hot amount returned by GetBalances.
            AccountBalance hotBalance = hotWalletManager.GetBalances("myHotWallet", ColdStakingManager.HotWalletAccountName).FirstOrDefault();

            Assert.Equal(hotBalance.AmountUnconfirmed, hotAddressResult.Amount);

            // Verify the cold amount returned by GetBalances.
            AccountBalance coldBalance = coldWalletManager.GetBalances("myColdWallet", ColdStakingManager.ColdWalletAccountName).FirstOrDefault();

            Assert.Equal(coldBalance.AmountUnconfirmed, coldAddressResult.Amount);
        }
Example #26
0
 public AccountBalanceFull(Address account, AccountBalance accountBalance)
 {
     Account        = account;
     AccountBalance = accountBalance;
 }
Example #27
0
 private void OnSelectedAsset(AccountBalance selectedAsset)
 {
     AccountNotification(new AccountEventArgs {
         Value = Account, SelectedAsset = selectedAsset, AccountEventType = AccountEventType.SelectedAsset
     });
 }
 public AccountEntity() : base()
 {
     Balance = AccountBalance.CreateWithZeroAmount();
     Status  = AccountStatus.CreateWithUnverifiedValue();
 }
Example #29
0
 public async Task <ServiceResponse <AccountBalance> > WithdrawAmount(AccountBalance accountBalance)
 {
     return(await _accontBalance.WithdrawAccountBalance(accountBalance));
 }
Example #30
0
 public async Task <ServiceResponse <AccountBalance> > DepositAmount(AccountBalance accountBalance)
 {
     return(await _accontBalance.DepositAccountBalance(accountBalance));
 }
        protected AccountBalance GetObject(DataRow dr)
        {
            AccountBalance objAccountBalance = new AccountBalance();
            objAccountBalance.Id = (dr["Id"] == DBNull.Value) ? 0 : (Decimal)dr["Id"];
            objAccountBalance.TransDate = (dr["TransDate"] == DBNull.Value) ? DateTime.MinValue : (DateTime)dr["TransDate"];
            objAccountBalance.TenantId = (dr["TenantId"] == DBNull.Value) ? 0 : (Int64)dr["TenantId"];
            objAccountBalance.VoucherTypeId = (dr["VoucherTypeId"] == DBNull.Value) ? 0 : Int64.Parse(dr["VoucherTypeId"].ToString());
            objAccountBalance.VoucherNo = (dr["VoucherNo"] == DBNull.Value) ? "" : (String)dr["VoucherNo"];
            objAccountBalance.AgainstVoucherTypeId = (dr["AgainstVoucherTypeId"] == DBNull.Value) ? 0 : (Int32)dr["AgainstVoucherTypeId"];
            objAccountBalance.AgainstVoucherNo = (dr["AgainstVoucherNo"] == DBNull.Value) ? 0 : (Int64)dr["AgainstVoucherNo"];
            objAccountBalance.ReferenceType = (dr["ReferenceType"] == DBNull.Value) ? "" : (String)dr["ReferenceType"];
            objAccountBalance.OpeningBalance = (dr["OpeningBalance"] == DBNull.Value) ? 0 : (Decimal)dr["OpeningBalance"];
            objAccountBalance.Debit = (dr["Debit"] == DBNull.Value) ? 0 : (Decimal)dr["Debit"];
            objAccountBalance.Credit = (dr["Credit"] == DBNull.Value) ? 0 : (Decimal)dr["Credit"];
            objAccountBalance.ClosingBalance = (dr["ClosingBalance"] == DBNull.Value) ? 0 : (Decimal)dr["ClosingBalance"];
            objAccountBalance.LastModified = (dr["LastModified"] == DBNull.Value) ? DateTime.MinValue : (DateTime)dr["LastModified"];
            objAccountBalance.ModifiedBy = (dr["ModifiedBy"] == DBNull.Value) ? 0 : (Int32)dr["ModifiedBy"];

            return objAccountBalance;
        }