Ejemplo n.º 1
0
        public async Task <CryptoWallet> GetEthereumWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://api.ethplorer.io/getAddressInfo/0xb297cacf0f91c86dd9d2fb47c6d12783121ab780?apiKey=freekey
            string uri = $"{EthereumServiceProviders.Ethplorer.GetAddressInfoEndpointURL}/{address}?apiKey={APIKey}";

            _logger.LogDebug($"{nameof(GetEthereumWalletAsync)}");
            _logger.LogDebug(uri);

            try
            {
                var walletJSON = await ExternalWebAPIRequestor.GetAsync <WalletJSON>(uri);

                result.Balance = walletJSON.ETH.balance;

                foreach (var tokenJSON in walletJSON.tokens)
                {
                    result.Pockets.Add(new CryptoPocket
                    {
                        Name    = tokenJSON.tokenInfo.name,
                        Symbol  = tokenJSON.tokenInfo.symbol,
                        Address = tokenJSON.tokenInfo.address,
                        Balance = tokenJSON.CalculatedBalance
                    });
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotAcceptable)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.ETH);
            }

            return(result);
        }
Ejemplo n.º 2
0
        public async Task <CryptoWallet> GetBitcoinWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://api-r.bitcoinchain.com/v1/address/1Chain4asCYNnLVbvG6pgCLGBrtzh4Lx4b
            string uri = $"{BitcoinServiceProviders.BitcoinChain.AddressEndpointURL}/{address}";

            _logger.LogDebug($"{nameof(GetBitcoinWalletAsync)}");
            _logger.LogDebug(uri);

            try
            {
                var listWalletJSON = await ExternalWebAPIRequestor.GetAsync <List <WalletJSON> >(uri);

                var walletJSON = listWalletJSON.FirstOrDefault();

                result.Balance = walletJSON.balance;
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Conflict)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.BTC);
            }

            return(result);
        }
Ejemplo n.º 3
0
        public async Task <CryptoWallet> GetDogecoinWalletAsync(string address)
        {
            var response = new CryptoWallet();

            //https://dogechain.info/api/v1/address/balance/DBXu2kgc3xtvCUWFcxFE3r9hEYgmuaaCyD
            string uri = $"{DogecoinServiceProviders.DogeChain.BalanceEndpointURL}/{address}";

            _logger.LogDebug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name}: {uri}");

            try
            {
                var walletJSON = await ExternalWebAPIRequestor.GetAsync <WalletJSON>(uri);

                if (walletJSON.success == 1)
                {
                    response.Balance = walletJSON.balance;
                }
                else
                {
                    throw new InvalidOperationException(walletJSON.error);
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.DOGE);
            }

            return(response);
        }
 private static void HandleWalletChanged(CryptoWallet wallet)
 {
     Log.Information($"Wallet '{wallet.Type}' " +
                     $"Balance: {wallet.Balance} {wallet.Currency}, " +
                     $"Available: {wallet.BalanceAvailable} {wallet.Currency}, " +
                     $"Pnl: {wallet.RealizedPnl:#.#####}/{wallet.UnrealizedPnl:#.#####}");
 }
        public async Task <SyncPersonalWalletResponse> Handle(SyncPersonalWalletRequest request, CancellationToken cancellationToken)
        {
            var result = new SyncPersonalWalletResponse();

            var wallet = await _context.Wallets
                         .Where(x => x.WalletID == request.WalletID)
                         .Include(x => x.Blockchain)
                         .SingleOrDefaultAsync(cancellationToken);

            if (wallet == null)
            {
                throw new NotFoundException(nameof(Wallet), request.WalletID);
            }

            var cryptoWallet = new CryptoWallet();
            var walletDTO    = new WalletDTO();

            if (wallet.Blockchain.Symbol == CurrencySymbol.BTC)
            {
                cryptoWallet = await _bitcoinService.GetBitcoinWalletAsync(wallet.Address);

                walletDTO = await WalletSynchronizer.ImportBalance(_context, _dateTimeOffset.Now, wallet, cryptoWallet, cancellationToken);
            }
            else if (wallet.Blockchain.Symbol == CurrencySymbol.ETH)
            {
                if (wallet.IsSynchronized)
                {
                    walletDTO = await WalletSynchronizer.ImportEthereumTransactions(_context, _ethereumService, wallet, cancellationToken);
                }
                else
                {
                    cryptoWallet = await _ethereumService.GetEthereumWalletAsync(wallet.Address);

                    walletDTO = await WalletSynchronizer.ImportBalance(_context, _dateTimeOffset.Now, wallet, cryptoWallet, cancellationToken);
                }
            }
            else if (wallet.Blockchain.Symbol == CurrencySymbol.DOGE)
            {
                cryptoWallet = await _dogecoinService.GetDogecoinWalletAsync(wallet.Address);

                walletDTO = await WalletSynchronizer.ImportBalance(_context, _dateTimeOffset.Now, wallet, cryptoWallet, cancellationToken);
            }
            else if (wallet.Blockchain.Symbol == CurrencySymbol.STEEM)
            {
                cryptoWallet = await _steemService.GetSteemWalletAsync(wallet.Address);

                walletDTO = await WalletSynchronizer.ImportBalance(_context, _dateTimeOffset.Now, wallet, cryptoWallet, cancellationToken);
            }
            else if (wallet.Blockchain.Symbol == CurrencySymbol.HIVE)
            {
                cryptoWallet = await _hiveService.GetHiveWalletAsync(wallet.Address);

                walletDTO = await WalletSynchronizer.ImportBalance(_context, _dateTimeOffset.Now, wallet, cryptoWallet, cancellationToken);
            }

            result.IsSuccessful = true;
            result.Wallet       = walletDTO;

            return(result);
        }
        public async Task <CryptoWallet> GetBitcoinWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://blockexplorer.com/api/addr/19SokJG7fgk8iTjemJ2obfMj14FM16nqzj
            string uri = $"{BitcoinServiceProviders.BlockExplorer.AddrEndpointURL}/{address}";

            var walletJSON = await ExternalWebAPIRequestor.GetAsync <WalletJSON>(uri);

            result.Balance = walletJSON.balance;

            return(result);
        }
Ejemplo n.º 7
0
        public async Task <CryptoWallet> GetBitcoinWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://fakechain.vioren.com/api/btc/getAddressInfo/0xb297cacf0f91c86dd9d2fb47c6d12783121ab780
            string uri = $"{BitcoinServiceProviders.FakeChain.GetAddressInfoEndpointURL}/{address}";

            var walletJSON = await ExternalWebAPIRequestor.GetAsync <WalletJSON>(uri);

            result.Balance = walletJSON.balance;

            return(result);
        }
        private CryptoWallet ConvertWallet(WalletResponse response)
        {
            var id = response.Currency;

            var wallet = new CryptoWallet
            {
                Type             = "Exchange",
                Currency         = CryptoPairsHelper.Clean(response.Currency),
                Balance          = Math.Abs(response.Balance),
                BalanceAvailable = response.Available
            };

            _lastWallet = wallet;
            return(wallet);
        }
        private CryptoWallet ConvertWallet(Wallet response)
        {
            //var currency = response.Currency ?? "XBt";

            var wallet = new CryptoWallet
            {
                Currency = CryptoPairsHelper.Clean(response.Currency),
                Balance  = response.Balance,
                //?? _lastWallet?.Balance ?? 0,
                BalanceAvailable = response.BalanceAvailable ?? _lastWallet?.BalanceAvailable ?? 0,
                Type             = response.Type.ToString()
            };

            _lastWallet = wallet;
            return(wallet);
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Create(CryptoWalletViewModel m)
        {
            if (ModelState.IsValid)
            {
                var user = await GetCurrentUserAsync();

                var cryptoWallet = new CryptoWallet(m.Label, m.Quantidade, m.ValorDeAquisicao, m.CriptoCurrencyId, user.Id);
                _db.CryptoWallets.Add(cryptoWallet);
                await _db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            await GetCryptoCurrenciesAsync(m.CriptoCurrencyId);

            return(View(m));
        }
        private CryptoWallet ConvertWallet(Margin margin)
        {
            var currency = margin.Currency ?? "XBt";

            var wallet = new CryptoWallet()
            {
                Currency         = "BTC",
                Balance          = ConvertToBtc(currency, margin.WalletBalance) ?? _lastWallet?.Balance ?? 0,
                BalanceAvailable = ConvertToBtc(currency, margin.AvailableMargin) ?? _lastWallet?.BalanceAvailable ?? 0,
                Leverage         = margin.MarginLeverage ?? _lastWallet?.Leverage,
                RealizedPnl      = ConvertToBtc(currency, margin.RealisedPnl) ?? _lastWallet?.RealizedPnl,
                UnrealizedPnl    = ConvertToBtc(currency, margin.UnrealisedPnl) ?? _lastWallet?.UnrealizedPnl,
                Type             = margin.Account.ToString()
            };

            _lastWallet = wallet;
            return(wallet);
        }
        public async Task <SyncAllPersonalWalletsResponse> Handle(SyncAllPersonalWalletsRequest request, CancellationToken cancellationToken)
        {
            var result = new SyncAllPersonalWalletsResponse();

            var synchronizedWallets = await _context.Wallets
                                      .Where(x => x.IsSynchronized)
                                      .Include(x => x.Blockchain)
                                      .ToListAsync(cancellationToken);

            foreach (var wallet in synchronizedWallets)
            {
                var cryptoWallet = new CryptoWallet();

                if (wallet.Blockchain.Symbol == CurrencySymbol.BTC)
                {
                    cryptoWallet = await _bitcoinService.GetBitcoinWalletAsync(wallet.Address);
                }
                else if (wallet.Blockchain.Symbol == CurrencySymbol.ETH)
                {
                    cryptoWallet = await _ethereumService.GetEthereumWalletAsync(wallet.Address);
                }
                else if (wallet.Blockchain.Symbol == CurrencySymbol.DOGE)
                {
                    cryptoWallet = await _dogecoinService.GetDogecoinWalletAsync(wallet.Address);
                }
                else if (wallet.Blockchain.Symbol == CurrencySymbol.STEEM)
                {
                    cryptoWallet = await _steemService.GetSteemWalletAsync(wallet.Address);
                }
                else if (wallet.Blockchain.Symbol == CurrencySymbol.HIVE)
                {
                    cryptoWallet = await _hiveService.GetHiveWalletAsync(wallet.Address);
                }

                var walletDTO = await WalletSynchronizer.ImportBalance(_context, _dateTimeOffset.Now, wallet, cryptoWallet, cancellationToken);

                result.Wallets.Add(walletDTO);
            }

            return(result);
        }
Ejemplo n.º 13
0
        public async Task <CryptoWallet> GetSteemWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://api.openhive.network
            string uri = $"{SteemServiceProviders.Steemit.BaseAPIEndpointURL}";

            _logger.LogDebug($"{nameof(GetSteemWalletAsync)}");
            _logger.LogDebug(uri);

            try
            {
                var getAccountsRequest        = new GetAccountsRequestJSON(address);
                var getAccountsRequestJSON    = JsonConvert.SerializeObject(getAccountsRequest);
                var getAccountsRequestContent = new StringContent(getAccountsRequestJSON, Encoding.UTF8, "application/json");

                var getAccountsResponseMessage = await client.PostAsync(uri, getAccountsRequestContent);

                var getAccountsResponseString = await getAccountsResponseMessage.Content.ReadAsStringAsync();

                var getAccountsResponseJSON = JsonConvert.DeserializeObject <GetAccountsResponseJSON>(getAccountsResponseString);

                var responseResult = getAccountsResponseJSON.result.FirstOrDefault();

                if (responseResult != null)
                {
                    var balanceText = responseResult.balance.Replace($" {CurrencySymbol.STEEM}", string.Empty);
                    result.Balance = Convert.ToDecimal(balanceText);
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Conflict)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.STEEM);
            }
            catch
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.STEEM);
            }

            return(result);
        }
Ejemplo n.º 14
0
        public async Task <CryptoWallet> GetEthereumWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://api.etherscan.io/api?module=account&action=balance&address=0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a&tag=latest&apikey=CVMMDNQRGURVWCGMBUTEF14V4VM1K147VP
            string uri = $"{EthereumServiceProviders.Etherscan.AccountBalanceEndpointURL}&address={address}&apikey={APIKey}";

            _logger.LogDebug($"{nameof(GetEthereumWalletAsync)}");
            _logger.LogDebug(uri);

            try
            {
                var walletJSON = await ExternalWebAPIRequestor.GetAsync <WalletJSON>(uri);

                result.Balance = Convert.ToDecimal(walletJSON.result) * Convert.ToDecimal(Math.Pow(10, -18));
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotAcceptable)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.ETH);
            }

            return(result);
        }
Ejemplo n.º 15
0
        public async Task <CryptoWallet> GetBitcoinWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://blockchain.info/q/addressbalance/1FKtFQ7Ti9vo7W3hskxZ1nXJpJtSixBdJc
            string uri = $"{BitcoinServiceProviders.Blockchain.AddressBalanceEndpointURL}/{address}";

            _logger.LogDebug($"{nameof(GetBitcoinWalletAsync)}");
            _logger.LogDebug(uri);

            try
            {
                var listWalletJSON = await ExternalWebAPIRequestor.GetAsync(uri);

                result.Balance = Convert.ToDecimal(listWalletJSON) / 100000000;
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Conflict)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.BTC);
            }

            return(result);
        }
Ejemplo n.º 16
0
        public async Task <CryptoWallet> GetEthereumWalletAsync(string address)
        {
            var result = new CryptoWallet();

            //https://fakechain.vioren.com/api/eth/getAddressInfo/0xb297cacf0f91c86dd9d2fb47c6d12783121ab780
            string uri = $"{EthereumServiceProviders.FakeChain.GetAddressInfoEndpointURL}/{address}";

            var walletJSON = await ExternalWebAPIRequestor.GetAsync <WalletJSON>(uri);

            result.Balance = walletJSON.balance;

            foreach (var tokenJSON in walletJSON.tokens)
            {
                result.Pockets.Add(new CryptoPocket
                {
                    Name    = tokenJSON.name,
                    Symbol  = tokenJSON.symbol,
                    Address = tokenJSON.address,
                    Balance = tokenJSON.balance
                });
            }

            return(result);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Загрузка информации о счетах, карточках, кошельках и т.д. из файла
        /// </summary>
        public static void Init()
        {
            if (!File.Exists(Properties.Resources.AccountsFile))
            {
                StreamWriter fileWriter = File.CreateText(Properties.Resources.AccountsFile);
                fileWriter.WriteLine("<?xml version=\"1.0\"?>\n<accounts>\n</accounts>  ");
                fileWriter.Close();
            }

            XmlAccountsDocument.Load(Properties.Resources.AccountsFile);

            foreach (XmlNode node in XmlAccountsDocument.DocumentElement)
            {
                switch (node.Attributes["type"].Value)
                {
                case "Bank":
                {
                    BankAccount newAccount = new BankAccount();
                    newAccount.AccountName   = node.ChildNodes[0].InnerText;
                    newAccount.AccountNumber = node.ChildNodes[1].InnerText;
                    Enum.TryParse(node.ChildNodes[2].InnerText, out newAccount.Currency);
                    newAccount.AccountAmount = decimal.Parse(node.ChildNodes[3].InnerText);

                    List_BankAccounts.Add(newAccount);


                    TileManager.BankAccountsTab.AddTile(newAccount.AccountName);
                    break;
                }

                case "PlasticCard":
                {
                    PlasticCard newCard = new PlasticCard();
                    newCard.Name             = node.ChildNodes[0].InnerText;
                    newCard.BankAccount      = node.ChildNodes[1].InnerText;
                    newCard.CardHolder       = node.ChildNodes[2].InnerText;
                    newCard.CardNumber       = node.ChildNodes[3].InnerText;
                    newCard.Date             = node.ChildNodes[4].InnerText;
                    newCard.PlasticCardInXml = node;
                    Enum.TryParse(node.ChildNodes[5].InnerText, out newCard.Currency);
                    newCard.AccountAmount = decimal.Parse(node.ChildNodes[6].InnerText);

                    List_PlasticCards.Add(newCard);
                    TileManager.PlasticCardsTab.AddTile(newCard.Name);
                    break;
                }

                case "Crypto":
                {
                    CryptoWallet newCryptoWallet = new CryptoWallet();
                    newCryptoWallet.Name           = node.ChildNodes[0].InnerText;
                    newCryptoWallet.WalletID       = node.ChildNodes[1].InnerText;
                    newCryptoWallet.WalletAddress  = node.ChildNodes[2].InnerText;
                    newCryptoWallet.WalletPassword = node.ChildNodes[3].InnerText;
                    Enum.TryParse(node.ChildNodes[4].InnerText, out newCryptoWallet.CryptoCurrency);

                    List_CryptoWallets.Add(newCryptoWallet);
                    break;
                }

                case "Other":
                {
                    OtherAccount newOtherAccount = new OtherAccount();
                    newOtherAccount.AccountName = node.ChildNodes[0].InnerText;
                    Enum.TryParse(node.ChildNodes[1].InnerText, out newOtherAccount.Currency);
                    newOtherAccount.AccountAmount = decimal.Parse(node.ChildNodes[2].InnerText);

                    List_OtherAccounts.Add(newOtherAccount);
                    break;
                }
                }
            }
        }
Ejemplo n.º 18
0
        public static async Task <WalletDTO> ImportBalance(IFortifex4DBContext _context, DateTimeOffset now, Wallet wallet, CryptoWallet cryptoWallet, CancellationToken cancellationToken)
        {
            WalletDTO walletDTO = new WalletDTO
            {
                WalletID         = wallet.WalletID,
                BlockchainID     = wallet.BlockchainID,
                Name             = wallet.Name,
                Address          = wallet.Address,
                Balance          = cryptoWallet.Balance,
                BlockchainSymbol = wallet.Blockchain.Symbol,
                BlockchainName   = wallet.Blockchain.Name,
            };

            var existingPockets = await _context.Pockets
                                  .Where(x => x.WalletID == wallet.WalletID)
                                  .Include(a => a.Currency)
                                  .Include(a => a.Transactions)
                                  .ThenInclude(b => b.FromInternalTransfers)
                                  .ThenInclude(c => c.ToTransaction)
                                  .Include(a => a.Transactions)
                                  .ThenInclude(b => b.ToInternalTransfers)
                                  .ThenInclude(c => c.FromTransaction)
                                  .ToListAsync(cancellationToken);

            /// 1) Remove all Transactions
            foreach (Pocket existingPocket in existingPockets)
            {
                foreach (var transaction in existingPocket.Transactions)
                {
                    _context.InternalTransfers.RemoveRange(transaction.FromInternalTransfers);
                    _context.Transactions.RemoveRange(transaction.FromInternalTransfers.Select(x => x.ToTransaction));
                    _context.InternalTransfers.RemoveRange(transaction.ToInternalTransfers);
                    _context.Transactions.RemoveRange(transaction.ToInternalTransfers.Select(x => x.FromTransaction));
                }

                _context.Transactions.RemoveRange(existingPocket.Transactions);
            }

            /// 2) Remove all Pockets except the Main Pocket
            _context.Pockets.RemoveRange(existingPockets.Where(x => !x.IsMain));
            await _context.SaveChangesAsync(cancellationToken);

            var mainPocket = existingPockets.Single(x => x.IsMain);

            /// 3) Add Balance Import Transaction to the Main Pocket
            mainPocket.Transactions.Add(new Transaction
            {
                TransactionHash     = string.Empty,
                Amount              = cryptoWallet.Balance,
                UnitPriceInUSD      = mainPocket.Currency.UnitPriceInUSD,
                TransactionType     = TransactionType.SyncBalanceImport,
                PairWalletName      = wallet.Name,
                PairWalletAddress   = mainPocket.Address,
                TransactionDateTime = now
            });

            /// 4) Set Wallet's flag IsSynchronized to true
            wallet.IsSynchronized = true;
            await _context.SaveChangesAsync(cancellationToken);

            //=====================================

            /// 5) Repopulate the Token Pockets (if any), including their own Balance Import Transaction
            var validCryptoPockets = cryptoWallet.Pockets.Where(x => !string.IsNullOrEmpty(x.Name));

            foreach (var cryptoPocket in validCryptoPockets)
            {
                /// Check if this is new Token Currency, based on its Symbol and Name property
                var tokenCurrency = await _context.Currencies
                                    .Where(x =>
                                           x.Symbol == cryptoPocket.Symbol &&
                                           x.Name == cryptoPocket.Name &&
                                           x.CurrencyType == CurrencyType.Token)
                                    .FirstOrDefaultAsync(cancellationToken);

                /// If this is new Token Currency, add it to the Currencies table
                if (tokenCurrency == null)
                {
                    tokenCurrency = new Currency
                    {
                        BlockchainID = wallet.BlockchainID,
                        Symbol       = cryptoPocket.Symbol,
                        Name         = cryptoPocket.Name,
                        CurrencyType = CurrencyType.Token
                    };

                    _context.Currencies.Add(tokenCurrency);
                    await _context.SaveChangesAsync(cancellationToken);
                }

                Pocket tokenPocket = new Pocket
                {
                    CurrencyID   = tokenCurrency.CurrencyID,
                    CurrencyType = CurrencyType.Token,
                    Address      = cryptoPocket.Address
                };

                wallet.Pockets.Add(tokenPocket);

                tokenPocket.Transactions.Add(new Transaction
                {
                    Amount              = cryptoPocket.Balance,
                    UnitPriceInUSD      = tokenCurrency.UnitPriceInUSD,
                    TransactionHash     = string.Empty,
                    PairWalletName      = wallet.Name,
                    PairWalletAddress   = cryptoPocket.Address,
                    TransactionType     = TransactionType.SyncBalanceImport,
                    TransactionDateTime = now
                });

                await _context.SaveChangesAsync(cancellationToken);

                walletDTO.Pockets.Add(new PocketDTO
                {
                    PocketID       = tokenPocket.PocketID,
                    CurrencyID     = tokenPocket.CurrencyID,
                    Address        = tokenPocket.Address,
                    Balance        = cryptoPocket.Balance,
                    CurrencySymbol = tokenCurrency.Symbol,
                    CurrencyName   = tokenCurrency.Name
                });
            }

            return(walletDTO);
        }