コード例 #1
0
ファイル: FixerFiatService.cs プロジェクト: hasmbly/Fortifex4
        public async Task <FiatExchangeRateCollection> GetFiatExchangeRateCollectionAsync(string baseCurrencySymbol)
        {
            var result = new FiatExchangeRateCollection();

            string uri = $"{FiatServiceProviders.Fixer.LatestEndpointURL}?access_key={AccessKey}&base={baseCurrencySymbol}";

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

            var latestResultJSON = await ExternalWebAPIRequestor.GetAsync <LatestResultJSON>(uri);

            if (latestResultJSON.success)
            {
                result.IsSuccessful       = true;
                result.CollectionDateTime = DateTimeOffset.FromUnixTimeSeconds(latestResultJSON.timestamp);

                foreach (PropertyInfo property in latestResultJSON.rates.GetType().GetProperties())
                {
                    string  fiatSymbol = property.Name;
                    decimal fiatValue  = Convert.ToDecimal(property.GetValue(latestResultJSON.rates));

                    result.ExchangeRates.Add(new FiatExchangeRate
                    {
                        Symbol = fiatSymbol,
                        Value  = fiatValue
                    });
                }
            }
            else
            {
                result = null;
            }

            return(result);
        }
コード例 #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);
        }
コード例 #3
0
ファイル: FixerFiatService.cs プロジェクト: hasmbly/Fortifex4
        public async Task <FiatCurrencyCollection> GetFiatCurrencyCollectionAsync()
        {
            var result = new FiatCurrencyCollection();

            string uri = $"{FiatServiceProviders.Fixer.SymbolsEndpointURL}?access_key={AccessKey}";

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

            var symbolsResultJSON = await ExternalWebAPIRequestor.GetAsync <SymbolsResultJSON>(uri);

            if (symbolsResultJSON.success)
            {
                foreach (PropertyInfo property in symbolsResultJSON.symbols.GetType().GetProperties())
                {
                    string fiatSymbol = property.Name;
                    string fiatName   = property.GetValue(symbolsResultJSON.symbols).ToString();

                    result.Currencies.Add(new FiatCurrency
                    {
                        Symbol = fiatSymbol,
                        Name   = fiatName
                    });
                }
            }
            else
            {
                result = null;
            }

            return(result);
        }
コード例 #4
0
        public async Task <EthereumTransactionCollection> GetEthereumTransactionCollectionAsync(string address)
        {
            var result = new EthereumTransactionCollection();

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

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

            try
            {
                var listTransactionJSON = await ExternalWebAPIRequestor.GetAsync <List <TransactionJSON> >(uri);

                foreach (var transactionJSON in listTransactionJSON)
                {
                    result.Transactions.Add(new EthereumTransaction
                    {
                        FromAddress = transactionJSON.from,
                        ToAddress   = transactionJSON.to,
                        Amount      = transactionJSON.value,
                        Hash        = transactionJSON.hash,
                        TimeStamp   = transactionJSON.timestamp
                    });
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotAcceptable)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.ETH);
            }

            return(result);
        }
コード例 #5
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);
        }
コード例 #6
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);
        }
コード例 #7
0
        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);
        }
コード例 #8
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);
        }
コード例 #9
0
        public async Task <decimal> ConvertAsync(string fromCurrencySymbol, string toCurrencySymbol, decimal amount)
        {
            if (amount == 0m)
            {
                return(0m);
            }

            decimal convertedAmount = 0m;

            bool isMinus = amount < 0;

            string uri = $"{CryptoServiceProviders.CoinMarketCap.ToolsPriceConversionEndpointURL}?symbol={fromCurrencySymbol}&convert={toCurrencySymbol}&amount={Math.Abs(amount)}";

            // TODO: Cek with Hasbi
            // sementara pake ini, karena ada error jika amount nya mengandung comma dan masih blum bisa solve
            //string uri = $"{CryptoServiceProviders.CoinMarketCap.ToolsPriceConversionEndpointURL}?symbol={fromCurrencySymbol}&convert={toCurrencySymbol}&amount=1";

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

            IDictionary <string, string> additionalHttpHeaders = new Dictionary <string, string>
            {
                { "X-CMC_PRO_API_KEY", APIKey }
            };

            try
            {
                var priceConversionResultJSON = await ExternalWebAPIRequestor.GetAsync <PriceConversionResultJSON>(uri, additionalHttpHeaders);

                if (priceConversionResultJSON.status.error_code == 0)
                {
                    foreach (var quote in priceConversionResultJSON.data.quote)
                    {
                        if (quote.Key == toCurrencySymbol)
                        {
                            convertedAmount = quote.Value.price;
                            break;
                        }
                    }
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.BadRequest)
            {
                convertedAmount = 0m;
            }

            return(isMinus ? -convertedAmount : convertedAmount);
        }
コード例 #10
0
ファイル: FixerFiatService.cs プロジェクト: hasmbly/Fortifex4
        public async Task <decimal> ConvertAsync(string fromCurrencySymbol, string toCurrencySymbol, decimal amount)
        {
            var convertedAmount = 0m;

            string uri = $"{FiatServiceProviders.Fixer.ConvertEndpointURL}?access_key={AccessKey}&from={fromCurrencySymbol}&to={toCurrencySymbol}&amount={Math.Abs(amount)}";

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

            var convertResultJSON = await ExternalWebAPIRequestor.GetAsync <ConvertResultJSON>(uri);

            if (convertResultJSON.success)
            {
                convertedAmount = convertResultJSON.result;
            }

            return(convertedAmount);
        }
コード例 #11
0
        public async Task <BitcoinTransactionCollection> GetBitcoinTransactionCollectionAsync(string address)
        {
            var result = new BitcoinTransactionCollection();

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

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

            try
            {
                var listListTransactionContainerJSON = await ExternalWebAPIRequestor.GetAsync <List <List <TransactionContainerJSON> > >(uri);

                var firstListTransactionContainerJSON = listListTransactionContainerJSON.FirstOrDefault();

                if (firstListTransactionContainerJSON != null)
                {
                    foreach (var transactionContainer in firstListTransactionContainerJSON)
                    {
                        result.Transactions.Add(new BitcoinTransaction
                        {
                            FromAddress = transactionContainer.tx.inputs[0].sender,
                            ToAddress   = transactionContainer.tx.outputs[0].receiver,
                            Amount      = transactionContainer.tx.total_output,
                            Hash        = transactionContainer.tx.self_hash,
                            TimeStamp   = transactionContainer.tx.block_time
                        });
                    }
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Conflict)
            {
                throw new InvalidWalletAddressException(address, CurrencySymbol.BTC);
            }

            return(result);
        }
コード例 #12
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);
        }
コード例 #13
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);
        }
コード例 #14
0
        public async Task <BitcoinTransactionCollection> GetBitcoinTransactionCollectionAsync(string address)
        {
            var result = new BitcoinTransactionCollection();

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

            var transactionCollectionJSON = await ExternalWebAPIRequestor.GetAsync <TransactionCollectionJSON>(uri);

            foreach (var transactionJSON in transactionCollectionJSON.transactions)
            {
                result.Transactions.Add(new BitcoinTransaction
                {
                    FromAddress = transactionJSON.fromAddress,
                    ToAddress   = transactionJSON.toAddress,
                    Amount      = transactionJSON.amount,
                    Hash        = transactionJSON.hash,
                    TimeStamp   = transactionJSON.timeStamp
                });
            }

            return(result);
        }
コード例 #15
0
        public async Task <decimal> GetUnitPriceAsync(string fromCurrencySymbol, string toCurrencySymbol)
        {
            decimal unitPrice = 0m;

            string uri = $"{CryptoServiceProviders.CoinMarketCap.ToolsPriceConversionEndpointURL}?symbol={fromCurrencySymbol}&convert={toCurrencySymbol}&amount=1";

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

            IDictionary <string, string> additionalHttpHeaders = new Dictionary <string, string>
            {
                { "X-CMC_PRO_API_KEY", APIKey }
            };

            try
            {
                var priceConversionResultJSON = await ExternalWebAPIRequestor.GetAsync <PriceConversionResultJSON>(uri, additionalHttpHeaders);

                if (priceConversionResultJSON.status.error_code == 0)
                {
                    foreach (var quote in priceConversionResultJSON.data.quote)
                    {
                        if (quote.Key == toCurrencySymbol)
                        {
                            unitPrice = quote.Value.price;
                            break;
                        }
                    }
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.BadRequest)
            {
                unitPrice = 0m;
            }

            return(unitPrice);
        }
コード例 #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);
        }
コード例 #17
0
        public async Task <CryptoLatestQuotesResult> GetLatestQuoteAsync(string fromCurrencySymbol, string toCurrencySymbol)
        {
            var result = new CryptoLatestQuotesResult();

            string uri = $"{CryptoServiceProviders.CoinMarketCap.CryptoCurrencyQuotesLatestEndpointURL}?symbol={fromCurrencySymbol}&convert={toCurrencySymbol}";

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

            IDictionary <string, string> additionalHttpHeaders = new Dictionary <string, string>
            {
                { "X-CMC_PRO_API_KEY", APIKey }
            };

            try
            {
                var cryptoCurrencyQuotesLatestResultJSON = await ExternalWebAPIRequestor.GetAsync <CryptoCurrencyQuotesLatestResultJSON>(uri, additionalHttpHeaders);

                if (cryptoCurrencyQuotesLatestResultJSON.status.error_code == 0)
                {
                    foreach (var data in cryptoCurrencyQuotesLatestResultJSON.data)
                    {
                        if (data.Key == fromCurrencySymbol)
                        {
                            foreach (var quote in data.Value.quote)
                            {
                                if (quote.Key == toCurrencySymbol)
                                {
                                    result = new CryptoLatestQuotesResult
                                    {
                                        Rank             = data.Value.cmc_rank ?? 0,
                                        Price            = quote.Value.price,
                                        Volume24h        = quote.Value.volume_24h ?? 0m,
                                        PercentChange1h  = quote.Value.percent_change_1h ?? 0f,
                                        PercentChange24h = quote.Value.percent_change_24h ?? 0f,
                                        PercentChange7d  = quote.Value.percent_change_7d ?? 0f,
                                        LastUpdated      = quote.Value.last_updated,
                                    };
                                }
                            }
                        }
                    }
                }
                else
                {
                    result = null;
                }
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.BadRequest)
            {
                //result = null;
                throw;
            }
            catch (WebException ex) when((ex.Response as HttpWebResponse)?.StatusCode != HttpStatusCode.OK)
            {
                //result = null;
                throw;
            }

            return(result);
        }
コード例 #18
0
        public async Task <CryptoBlockchainCollection> GetCryptoBlockchainCollectionAsync()
        {
            var result = new CryptoBlockchainCollection();

            string uri = $"{CryptoServiceProviders.CoinMarketCap.CryptoCurrencyListingsLatestEndpointURL}";

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

            IDictionary <string, string> additionalHttpHeaders = new Dictionary <string, string>
            {
                { "X-CMC_PRO_API_KEY", APIKey }
            };

            var cryptoCurrencyListingLatestResultJSON = await ExternalWebAPIRequestor.GetAsync <CryptoCurrencyListingsLatestResultJSON>(uri, additionalHttpHeaders);

            if (cryptoCurrencyListingLatestResultJSON.status.error_code == 0)
            {
                #region Process Coin Currencies
                var coinCurrencies = cryptoCurrencyListingLatestResultJSON.data.Where(x => x.platform == null);

                foreach (var coinCurrencyJSON in coinCurrencies)
                {
                    CryptoBlockchain cryptoBlockchain = result.Blockchains
                                                        .SingleOrDefault(x => x.BlockchainID == coinCurrencyJSON.id);

                    if (cryptoBlockchain == null)
                    {
                        cryptoBlockchain = new CryptoBlockchain
                        {
                            BlockchainID = coinCurrencyJSON.id,
                            Name         = coinCurrencyJSON.name,
                            Symbol       = coinCurrencyJSON.symbol,
                            Slug         = coinCurrencyJSON.slug,
                            Rank         = coinCurrencyJSON.cmc_rank,
                        };

                        result.Blockchains.Add(cryptoBlockchain);
                    }

                    cryptoBlockchain.Currencies.Add(new CryptoCurrency
                    {
                        CurrencyID       = coinCurrencyJSON.id,
                        BlockchainID     = cryptoBlockchain.BlockchainID,
                        Name             = coinCurrencyJSON.name,
                        Symbol           = coinCurrencyJSON.symbol,
                        Slug             = coinCurrencyJSON.slug,
                        Rank             = coinCurrencyJSON.cmc_rank,
                        UnitPriceInUSD   = coinCurrencyJSON.quote.USD.price ?? 0m,
                        Volume24h        = coinCurrencyJSON.quote.USD.volume_24h ?? 0m,
                        PercentChange1h  = coinCurrencyJSON.quote.USD.percent_change_1h ?? 0f,
                        PercentChange24h = coinCurrencyJSON.quote.USD.percent_change_24h ?? 0f,
                        PercentChange7d  = coinCurrencyJSON.quote.USD.percent_change_7d ?? 0f,
                        LastUpdated      = coinCurrencyJSON.quote.USD.last_updated,
                        CurrencyType     = CurrencyType.Coin
                    });
                }
                #endregion

                #region Process Token Currencies
                var tokenCurrencies = cryptoCurrencyListingLatestResultJSON.data.Where(x => x.platform != null);

                foreach (var tokenCurrencyJSON in tokenCurrencies)
                {
                    CryptoBlockchain cryptoBlockchain = result.Blockchains.SingleOrDefault(x => x.BlockchainID == tokenCurrencyJSON.platform.id);

                    if (cryptoBlockchain == null)
                    {
                        _logger.LogDebug($"tokenCurrencyJSON.id: {tokenCurrencyJSON.id}");
                        _logger.LogDebug($"tokenCurrencyJSON.platform.id: {tokenCurrencyJSON.platform.id}");
                    }
                    else
                    {
                        cryptoBlockchain.Currencies.Add(new CryptoCurrency
                        {
                            CurrencyID       = tokenCurrencyJSON.id,
                            BlockchainID     = cryptoBlockchain.BlockchainID,
                            Name             = tokenCurrencyJSON.name,
                            Symbol           = tokenCurrencyJSON.symbol,
                            Slug             = tokenCurrencyJSON.slug,
                            Rank             = tokenCurrencyJSON.cmc_rank,
                            UnitPriceInUSD   = tokenCurrencyJSON.quote.USD.price ?? 0m,
                            Volume24h        = tokenCurrencyJSON.quote.USD.volume_24h ?? 0m,
                            PercentChange1h  = tokenCurrencyJSON.quote.USD.percent_change_1h ?? 0f,
                            PercentChange24h = tokenCurrencyJSON.quote.USD.percent_change_24h ?? 0f,
                            PercentChange7d  = tokenCurrencyJSON.quote.USD.percent_change_7d ?? 0f,
                            LastUpdated      = tokenCurrencyJSON.quote.USD.last_updated,
                            CurrencyType     = CurrencyType.Token
                        });
                    }
                }
                #endregion
            }
            else
            {
                result = null;
            }

            return(result);
        }