public async Task <IActionResult> GetBalance([FromQuery] WalletBalanceRequest request,
                                              CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await this.Execute(request, cancellationToken,
                               async (req, token) => this.Json(await this.walletService.GetBalance(req.WalletName, req.AccountName,
                                                                                                   req.IncludeBalanceByAddress, token))
                               ));
 }
        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()));
            }
        }
        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()));
            }
        }
Beispiel #4
0
        /// <summary>
        /// Gets the balance of a wallet.
        /// </summary>
        /// <param name="request">The request parameters.</param>
        /// <returns></returns>
        public WalletBalanceModel GetBalance(WalletBalanceRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            //if (!this.ModelState.IsValid)
            //{
            //    return BuildErrorResponse(this.ModelState);
            //}

            try
            {
                WalletBalanceModel model = new WalletBalanceModel();

                IEnumerable <AccountBalance> balances = this.walletManager.GetBalances(request.WalletName, request.AccountName);

                foreach (AccountBalance balance in balances)
                {
                    HdAccount account = balance.Account;
                    model.AccountsBalances.Add(new AccountBalanceModel
                    {
                        CoinType          = this.coinType,
                        Name              = account.Name,
                        HdPath            = account.HdPath,
                        AmountConfirmed   = balance.AmountConfirmed,
                        AmountUnconfirmed = balance.AmountUnconfirmed
                    });
                }

                return(model);
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                //return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString());
                throw;
            }
        }
Beispiel #5
0
        private async Task <bool> CheckWalletRequirementsAsync(NodeType nodeType, int apiPort)
        {
            var chainName     = nodeType == NodeType.MainChain ? "STRAX" : "CIRRUS";
            var amountToCheck = nodeType == NodeType.MainChain ? CollateralRequirement : FeeRequirement;
            var chainTicker   = nodeType == NodeType.MainChain ? this.mainchainNetwork.CoinTicker : this.sidechainNetwork.CoinTicker;

            Console.WriteLine($"Please enter the name of the {chainName} wallet that contains the required collateral of {amountToCheck} {chainTicker}:");

            var walletName = Console.ReadLine();

            WalletInfoModel walletInfoModel = await $"http://localhost:{apiPort}/api".AppendPathSegment("Wallet/list-wallets").GetJsonAsync <WalletInfoModel>();

            if (walletInfoModel.WalletNames.Contains(walletName))
            {
                Console.WriteLine($"SUCCESS: Wallet with name '{chainName}' found.");
            }
            else
            {
                Console.WriteLine($"{chainName} wallet with name '{walletName}' does not exist.");

                ConsoleKeyInfo key;
                do
                {
                    Console.WriteLine($"Would you like to restore you {chainName} wallet that holds the required amount of {amountToCheck} {chainTicker} now? Enter (Y) to continue or (N) to exit.");
                    key = Console.ReadKey();
                    if (key.Key == ConsoleKey.Y || key.Key == ConsoleKey.N)
                    {
                        break;
                    }
                } while (true);

                if (key.Key == ConsoleKey.N)
                {
                    Console.WriteLine($"You have chosen to exit the registration script.");
                    return(false);
                }

                if (!await RestoreWalletAsync(apiPort, chainName, walletName))
                {
                    return(false);
                }
            }

            // Check wallet height (sync) status.
            do
            {
                var walletNameRequest = new WalletName()
                {
                    Name = walletName
                };
                WalletGeneralInfoModel walletInfo = await $"http://localhost:{apiPort}/api".AppendPathSegment("wallet/general-info").SetQueryParams(walletNameRequest).GetJsonAsync <WalletGeneralInfoModel>();
                StatusModel            blockModel = await $"http://localhost:{apiPort}/api".AppendPathSegment("node/status").GetJsonAsync <StatusModel>();

                if (walletInfo.LastBlockSyncedHeight > (blockModel.ConsensusHeight - 50))
                {
                    Console.WriteLine($"{chainName} wallet is synced.");
                    break;
                }

                Console.WriteLine($"Syncing {chainName} wallet, current height {walletInfo.LastBlockSyncedHeight}...");
                await Task.Delay(TimeSpan.FromSeconds(3));
            } while (true);

            // Check wallet balance.
            try
            {
                var walletBalanceRequest = new WalletBalanceRequest()
                {
                    WalletName = walletName
                };
                WalletBalanceModel walletBalanceModel = await $"http://localhost:{apiPort}/api"
                                                        .AppendPathSegment("wallet/balance")
                                                        .SetQueryParams(walletBalanceRequest)
                                                        .GetJsonAsync <WalletBalanceModel>();

                if (walletBalanceModel.AccountsBalances[0].SpendableAmount / 100000000 > amountToCheck)
                {
                    Console.WriteLine($"SUCCESS: The {chainName} wallet contains the required amount of {amountToCheck} {chainTicker}.");
                    return(true);
                }

                Console.WriteLine($"ERROR: The {chainName} wallet does not contain the required amount of {amountToCheck} {chainTicker}.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR: An exception occurred trying to check the wallet balance: {ex}");
            }

            return(false);
        }