Ejemplo n.º 1
0
        public IEnumerable <ValidationResult> Validate(ECurrency currency)
        {
            if (string.IsNullOrWhiteSpace(Checksum))
            {
                yield return(new ValidationResult($"{nameof(Checksum)} parameter is required.", new[] { nameof(Checksum) }));
            }
            if (MatchedOrders == null)
            {
                yield return(new ValidationResult($"{nameof(MatchedOrders)} is required.", new[] { nameof(MatchedOrders) }));
            }
            else
            {
                foreach (var matchedOrder in MatchedOrders)
                {
                    IEnumerable <ValidationResult> validation = matchedOrder.Validate(currency);

                    if (validation.Any())
                    {
                        foreach (var item in validation)
                        {
                            throw new ArgumentNullException(item.ErrorMessage);
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private async Task <Result <FeeResponse, ErrorResponse> > getFeeAsync(ECurrency currency)
        {
            var    result     = new Result <FeeResponse, ErrorResponse>();
            string requestUri = $"{mEnv.BaseUrl}/v1/{currency}/Fee";

            try
            {
                using (HttpClient httpClient = new HttpClient())
                    using (HttpResponseMessage response = await httpClient.GetAsync(requestUri))
                    {
                        FeeResponse feeResponse = await response.Content.ReadAsAsync <FeeResponse>();

                        if (response.IsSuccessStatusCode)
                        {
                            result.IsSuccess = true;
                            result.Data      = feeResponse;

                            return(result);
                        }

                        string contentString = await response.Content.ReadAsStringAsync();

                        result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString);
                    }
            }
            catch (HttpRequestException)
            {
                result.IsSuccess = false;
                result.Error     = ResponseHandler.GetExceptionError();
            }
            return(result);
        }
Ejemplo n.º 3
0
        private static void AssignValue(string input, ref ECurrency currency)
        {
            switch (input)
            {
            case "EUR": {
                currency = ECurrency.EUR;
                break;
            }

            case "USD": {
                currency = ECurrency.USD;
                break;
            }

            case "RON": {
                currency = ECurrency.RON;
                break;
            }

            default: {
                currency = ECurrency.NO_CURRENCY;
                break;
            }
            }
        }
Ejemplo n.º 4
0
        private Dictionary <ECurrency, Decimal> ParseCurrencies(
            XmlNodeList nodes)
        {
            Dictionary <ECurrency, Decimal> dictionary = new Dictionary <ECurrency, Decimal>()
            {
                {
                    ECurrency.RUR,
                    Decimal.One
                }
            };

            foreach (XmlElement node in nodes)
            {
                if (node["NumCode"] != null)
                {
                    string key = node["NumCode"].InnerText.Trim();
                    if (this._innerCurrencies.ContainsKey(key))
                    {
                        ECurrency innerCurrency = this._innerCurrencies[key];
                        dictionary.Add(innerCurrency, this.ExtractActualCurse(node));
                    }
                }
            }
            return(dictionary);
        }
Ejemplo n.º 5
0
        internal static string GetAddressSignature(string privateKey, ECurrency currency, Environment environment)
        {
            if (string.IsNullOrWhiteSpace(privateKey))
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            string signature = null;

            if (currency == ECurrency.BTC)
            {
                BitcoinSecret secret = new BitcoinSecret(privateKey, environment.Network);
                signature = secret.PrivateKey.SignMessage(timestamp);
            }
            else if (currency.IsGluwaCoinCurrency())
            {
                var signer = new EthereumMessageSigner();
                signature = signer.EncodeUTF8AndSign(timestamp, new EthECKey(privateKey));
            }
            else
            {
                throw new ArgumentOutOfRangeException($"Unsupported currency: {currency}");
            }

            string signatureToEncode = $"{timestamp}.{signature}";

            byte[] signatureByte = Encoding.UTF8.GetBytes(signatureToEncode);
            string encodedData   = Convert.ToBase64String(signatureByte);

            return(encodedData);
        }
Ejemplo n.º 6
0
 private static void ProcessInput(string fCurrency, ref ECurrency fromCurrency, string tCurrency, ref ECurrency toCurrency)
 {
     fCurrency = fCurrency.ToUpper().Trim();
     tCurrency = tCurrency.ToUpper().Trim();
     AssignValue(tCurrency, ref toCurrency);
     AssignValue(fCurrency, ref fromCurrency);
 }
        public void CacheOut(ECurrency toCurrency, double val)
        {
            KeyValuePair <double, int> usdPair;
            KeyValuePair <double, int> eurPair;
            double sumInRon;

            XmlReader.ExchangeRates.TryGetValue(ECurrency.USD.ToString(), out usdPair);
            XmlReader.ExchangeRates.TryGetValue(ECurrency.EUR.ToString(), out eurPair);
            sumInRon = (double)(val * eurPair.Key);

            switch (toCurrency)
            {
            case ECurrency.USD:
                money.TotalCacheValue = val;
                break;

            case ECurrency.EUR:
                money.TotalCacheValue = (double)(sumInRon / usdPair.Key);
                break;

            case ECurrency.RON:
                money.TotalCacheValue = (double)(val / usdPair.Key);
                break;
            }

            Console.WriteLine($"{money.TotalCacheValue} {ECurrency.USD}");
        }
Ejemplo n.º 8
0
 public Foo(string name, ECurrency currency, decimal amount)
 {
     Id       = Guid.NewGuid();
     Name     = name;
     Currency = currency;
     Amount   = amount;
 }
Ejemplo n.º 9
0
 public Decimal GetActualCurse(ECurrency currency)
 {
     if (!this.IsLoadedData || !this.LastLoadData.ContainsKey(currency))
     {
         return(Decimal.Zero);
     }
     return(this.LastLoadData[currency]);
 }
Ejemplo n.º 10
0
        public Currency GetCurrency(ECurrency currency)
        {
            var           request  = new RestRequest($"public/currency/{currency.ToString()}", Method.GET);
            IRestResponse response = client.Execute(request);
            var           content  = response.Content;

            return(JsonConvert.DeserializeObject <Currency>(content));
        }
Ejemplo n.º 11
0
        public Task <string> BuyListing(long id, ECurrency currency, double subtotal, double total, Proxy proxy = null)
        {
            var subtotalConverted = (long)(subtotal * 100);
            var totalConverted    = (long)(total * 100);
            var fee = totalConverted - subtotalConverted;

            return(BuyListing(id, currency, subtotalConverted, fee, totalConverted, proxy));
        }
Ejemplo n.º 12
0
        public Task <JListings> Listings(EApp app, string hashName, ECurrency currency, int count = 10, bool withAuth = false, Proxy proxy = null)
        {
            var request = new RestRequest($"/market/listings/{(int)app}/{hashName}/render");

            request.AddQueryParameter("currency", ((int)currency).ToString());
            request.AddQueryParameter("count", count.ToString());

            return(_client.SteamRequestAsync <JListings>(request, withAuth, proxy));
        }
        public string GetCurrency(ECurrency currency)
        {
            switch (currency)
            {
            case ECurrency.Euro: return("978");

            default: return("978");
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Get a list of accepted quotes.
        /// </summary>
        /// <param name="currency">The source currency of the quote.</param>
        /// <param name="address">The sending address of the quote.</param>
        /// <param name="privateKey">The privateKey of the sending address.</param>
        /// <response code="200">array of Quotes.</response>
        /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response>
        /// <response code="403_SignatureMissing">X-REQUEST-SIGNATURE header is missing.</response>
        /// <response code="403_SignatureExpired">X-REQUEST-SIGNATURE has expired.</response>
        /// <response code="403_InvalidSignature">Invalid X-REQUEST-SIGNATURE.</response>
        /// <response code="500">Server error.</response>
        /// <returns></returns>
        public async Task <Result <List <GetQuotesResponse>, ErrorResponse> > GetQuotesAsync(
            ECurrency currency,
            string address,
            string privateKey)
        {
            GetQuotesOptions options = new GetQuotesOptions();

            return(await GetQuotesAsync(currency, address, privateKey, options));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Constructs a Currency object from an ECurrency value.
        /// </summary>
        /// <param name="eCurrency"></param>
        public Currency(ECurrency eCurrency)
        {
            this.eCurrency = eCurrency;

            if (markets.Contains(eCurrency))
                significance = markets.IndexOf(eCurrency) + 1;
            else
                significance = 0;
        }
Ejemplo n.º 16
0
    public static int GetCurrency(ECurrency Currency)
    {
        string identifier = Currency.ToIdentifier();

        if (VirtualCurrency.ContainsKey(identifier) == true)
        {
            return(VirtualCurrency[identifier]);
        }
        return(0);
    }
        /// <summary>
        /// Returns a products list, where all producs have a price accourding to a currency.
        /// </summary>
        /// <param name="currency">Currency that determines each product price.</param>
        /// <returns>Products.</returns>
        public IEnumerable <Product> ListByCurrency(ECurrency currency)
        {
            var products = _repositorio.List();

            if (currency == ECurrency.Real)
            {
                products.ApplyExchangeRate(3.30M);
            }
            return(products);
        }
Ejemplo n.º 18
0
        public Task <JRecent> Recent(string country, ELanguage language, ECurrency currency, Proxy proxy = null)
        {
            var request = new RestRequest("/market/recent");

            request.AddQueryParameter("country", country);
            request.AddQueryParameter("language", language.ToString().ToLower());
            request.AddQueryParameter("currency", ((int)currency).ToString());

            return(_client.SteamRequestAsync <JRecent>(request, false, proxy));
        }
Ejemplo n.º 19
0
        public Task <JPriceOverview> PriceOverview(ECurrency currency, EApp app, string hashName, Proxy proxy = null)
        {
            var request = new RestRequest("/market/priceoverview/");

            request.AddQueryParameter("currency", ((int)currency).ToString());
            request.AddQueryParameter("appid", ((int)app).ToString());
            request.AddQueryParameter("market_hash_name", hashName);

            return(_client.SteamRequestAsync <JPriceOverview>(request, false, proxy));
        }
Ejemplo n.º 20
0
        public async Task <AppResult <Rate_vw> > GetRateAsync(ECurrency from, ECurrency to)
        {
            var result = await _requester.SendAsync <RatesData>(ERestCall.Get);

            return(new AppResult <Rate_vw>(new Rate_vw()
            {
                Date = result.Date,
                ExchangeRate = result.GetRate(from.ToString(), to.ToString()),
                From = from,
                To = to
            }));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Constructs a Currency object from an ECurrency value.
        /// </summary>
        /// <param name="eCurrency"></param>
        public Currency(ECurrency eCurrency)
        {
            this.eCurrency = eCurrency;

            if (markets.Contains(eCurrency))
            {
                significance = markets.IndexOf(eCurrency) + 1;
            }
            else
            {
                significance = 0;
            }
        }
Ejemplo n.º 22
0
        public Task <JCreateOrder> CreateOrder(string hashName, EApp app, ECurrency currency, double totalPrice, int quantity, Proxy proxy = null)
        {
            var request = new RestRequest("/market/createbuyorder/", Method.POST);

            request.AddHeader("Referer", $"https://steamcommunity.com/market/listings/{(int)app}/{hashName}");
            request.AddParameter("sessionid", _client.Auth.Session(), ParameterType.GetOrPost);
            request.AddParameter("currency", (int)currency, ParameterType.GetOrPost);
            request.AddParameter("appid", (int)app, ParameterType.GetOrPost);
            request.AddParameter("market_hash_name", HttpUtility.UrlDecode(hashName), ParameterType.GetOrPost);
            request.AddParameter("price_total", (totalPrice * 100 * quantity).ToString(CultureInfo.InvariantCulture), ParameterType.GetOrPost);
            request.AddParameter("quantity", quantity, ParameterType.GetOrPost);

            return(_client.SteamRequestAsync <JCreateOrder>(request, true, proxy));
        }
Ejemplo n.º 23
0
        public Task <string> BuyListing(long id, ECurrency currency, long subtotal, long fee, long total, Proxy proxy = null)
        {
            var request = new RestRequest($"/market/buylisting/{id}", Method.POST);

            request.AddHeader("Referer", "https://steamcommunity.com/market/");
            request.AddParameter("sessionid", _client.Auth.Session(), ParameterType.GetOrPost);
            request.AddParameter("currency", (int)currency, ParameterType.GetOrPost);
            request.AddParameter("quantity", 1, ParameterType.GetOrPost);
            request.AddParameter("subtotal", subtotal, ParameterType.GetOrPost);
            request.AddParameter("fee", fee, ParameterType.GetOrPost);
            request.AddParameter("total", total, ParameterType.GetOrPost);

            return(_client.SteamRequestRawAsync(request, true, proxy));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Get an accepted quote with ID.
        /// </summary>
        /// <param name="currency">The source currency of the quote.</param>
        /// <param name="privateKey">The privateKey of the sending address of the quote.</param>
        /// <param name="ID">ID of the accepted quote.</param>
        /// <response code="200">The quote with a specified ID.</response>
        /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response>
        /// <response code="403_SignatureMissing">X-REQUEST-SIGNATURE header is missing.</response>
        /// <response code="403_SignatureExpired">X-REQUEST-SIGNATURE has expired.</response>
        /// <response code="403_InvalidSignature">Invalid X-REQUEST-SIGNATURE.</response>
        /// <response code="404">Quote is not found.</response>
        /// <response code="500">Server error.</response>
        /// <returns></returns>
        public async Task <Result <GetQuoteResponse, ErrorResponse> > GetQuoteAsync(ECurrency currency, string privateKey, Guid?ID)
        {
            #region
            if (!currency.IsGluwaExchangeCurrency())
            {
                throw new ArgumentOutOfRangeException($"Unsupported currency: {currency}");
            }

            if (ID == null || ID == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(ID));
            }
            #endregion

            var    result     = new Result <GetQuoteResponse, ErrorResponse>();
            string requestUri = $"{mEnv.BaseUrl}/v1/Quotes/{ID}";

            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add(X_REQUEST_SIGNATURE, GluwaService.GetAddressSignature(privateKey, currency, mEnv));

                    using (HttpResponseMessage response = await httpClient.GetAsync(requestUri))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            GetQuoteResponse quoteResponse = await response.Content.ReadAsAsync <GetQuoteResponse>();

                            result.IsSuccess = true;
                            result.Data      = quoteResponse;

                            return(result);
                        }

                        string contentString = await response.Content.ReadAsStringAsync();

                        result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString);
                    }
                }
            }
            catch (HttpRequestException)
            {
                result.IsSuccess = false;
                result.Error     = ResponseHandler.GetExceptionError();
            }

            return(result);
        }
Ejemplo n.º 25
0
    private static void ConsumeCurrency(ECurrency _Currency, int _Amount)
    {
        SubtractUserVirtualCurrencyRequest request = new SubtractUserVirtualCurrencyRequest()
        {
            Amount          = _Amount,
            VirtualCurrency = _Currency.ToIdentifier()
        };

        PlayFabClientAPI.SubtractUserVirtualCurrency(request, OnTransactionResult,
                                                     (error) =>
        {
            Debug.Log("Got error substractin user currency :");
            Debug.Log(error.GenerateErrorReport());
        });
    }
Ejemplo n.º 26
0
        /// <summary>
        /// Get balance for specified currency.
        /// </summary>
        /// <param name="currency">Currency type.</param>
        /// <param name="address">Your public Address.</param>
        /// <param name="includeUnspentOutputs">(For BTC only) if "true", the response includes unspent outputs for the address. "false" by default.</param>
        /// <response code="200">Balance and associated currency.</response>
        /// <response code="400">Invalid address format.</response>
        /// <response code="500">Server error.</response>
        /// <response code="503">Service unavailable for the specified currency or temporarily.</response>
        public async Task <Result <BalanceResponse, ErrorResponse> > GetBalanceAsync(ECurrency currency, string address, bool includeUnspentOutputs = false)
        {
            if (string.IsNullOrWhiteSpace(address))
            {
                throw new ArgumentNullException(nameof(address));
            }

            var    result     = new Result <BalanceResponse, ErrorResponse>();
            string requestUri = $"{mEnv.BaseUrl}/v1/{currency}/Addresses/{address}";

            List <string> queryParams = new List <string>();

            queryParams.Add($"includeUnspentOutputs={includeUnspentOutputs}");

            if (queryParams.Any())
            {
                requestUri = $"{requestUri}?{string.Join("&", queryParams)}";
            }

            try
            {
                using (HttpClient httpClient = new HttpClient())
                    using (HttpResponseMessage response = await httpClient.GetAsync(requestUri))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            BalanceResponse balanceResponse = await response.Content.ReadAsAsync <BalanceResponse>();

                            result.IsSuccess = true;
                            result.Data      = balanceResponse;

                            return(result);
                        }

                        string contentString = await response.Content.ReadAsStringAsync();

                        result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString);
                    }
            }
            catch (HttpRequestException)
            {
                result.IsSuccess = false;
                result.Error     = ResponseHandler.GetExceptionError();
            }

            return(result);
        }
Ejemplo n.º 27
0
        private static void UpdateCurrency(
            EBookmakers bookmaker,
            Settings settings,
            ECurrency newCurrency)
        {
            Dictionary <EBookmakers, Bookmaker> dictionary = settings.UserSettings.BookmakersList.ToDictionary <Bookmaker, EBookmakers, Bookmaker>((Func <Bookmaker, EBookmakers>)(x => x.EBookmaker), (Func <Bookmaker, Bookmaker>)(x => x));

            if (!dictionary.ContainsKey(bookmaker))
            {
                Bookmaker bookmaker1 = AllBookmakersHelper.GetBookmaker(bookmaker);
                settings.UserSettings.BookmakersList.Add(bookmaker1);
            }
            else
            {
                dictionary[bookmaker].CurrentCurrency = newCurrency;
            }
        }
Ejemplo n.º 28
0
        internal static bool IsGluwaCoinCurrency(this ECurrency currency)
        {
            switch (currency)
            {
            case ECurrency.KRWG:
            case ECurrency.USDG:
            case ECurrency.NGNG:
            case ECurrency.sUSDCG:
            case ECurrency.sNGNG:
                return(true);

            case ECurrency.BTC:
                return(false);

            default:
                throw new ArgumentOutOfRangeException($"Unsupported currency: {currency}");
            }
        }
Ejemplo n.º 29
0
        private string getGluwacoinReserveTxnSignature(
            ECurrency currency,
            string address,
            string amount,
            string fee,
            string target,
            string executor,
            BigInteger nonce,
            BigInteger expiryBlockNumber,
            string privateKey)
        {
            BigInteger convertAmount = BigInteger.Zero;
            BigInteger convertFee    = BigInteger.Zero;

            if (currency.IsGluwacoinSideChainCurrency())
            {
                convertAmount = GluwacoinConverter.ConvertToGluwacoinSideChainBigInteger(amount, currency);
                convertFee    = GluwacoinConverter.ConvertToGluwacoinSideChainBigInteger(fee, currency);
            }
            else
            {
                convertAmount = GluwacoinConverter.ConvertToGluwacoinBigInteger(amount);
                convertFee    = GluwacoinConverter.ConvertToGluwacoinBigInteger(fee);
            }

            ABIEncode abiEncode = new ABIEncode();

            byte[] messageHash = abiEncode.GetSha3ABIEncodedPacked(
                new ABIValue("address", GluwaService.getGluwacoinContractAddress(currency, mEnv)),
                new ABIValue("address", address),
                new ABIValue("address", target),
                new ABIValue("address", executor),
                new ABIValue("uint256", convertAmount),
                new ABIValue("uint256", convertFee),
                new ABIValue("uint256", nonce),
                new ABIValue("uint256", expiryBlockNumber)
                );

            EthereumMessageSigner signer = new EthereumMessageSigner();
            string signature             = signer.Sign(messageHash, privateKey);

            return(signature);
        }
Ejemplo n.º 30
0
        public string GetParseNumber(ECurrency typeCurrency)
        {
            float _currencyRemain = GetCurrency(typeCurrency);

            switch (Mathf.Log10(GetCurrency(typeCurrency)))
            {
            case float _c when _c >= 6: return(SetNumber(6, "M"));

            case float _c when _c >= 3: return(SetNumber(3, "K"));

            default: return(_currencyRemain.ToString("N0"));
            }
            string SetNumber(int count, string formats)
            {
                StringBuilder _number = new StringBuilder().Append(_currencyRemain).Remove(((int)Mathf.Log10(_currencyRemain) - (count - 1)), count);

                return($"{_number}{formats}");
            }
        }
Ejemplo n.º 31
0
        public IEnumerable <ValidationResult> Validate(ECurrency currency)
        {
            if (OrderID == null || OrderID == Guid.Empty)
            {
                yield return(new ValidationResult($"{nameof(OrderID)} parameter is required.", new[] { nameof(OrderID) }));
            }
            else if (string.IsNullOrWhiteSpace(DestinationAddress))
            {
                yield return(new ValidationResult($"{nameof(DestinationAddress)} parameter is required.", new[] { nameof(DestinationAddress) }));
            }
            else if (string.IsNullOrWhiteSpace(SourceAmount))
            {
                yield return(new ValidationResult($"{nameof(SourceAmount)} parameter is required.", new[] { nameof(SourceAmount) }));
            }
            else if (string.IsNullOrWhiteSpace(Fee))
            {
                yield return(new ValidationResult($"{nameof(Fee)} parameter is required.", new[] { nameof(Fee) }));
            }

            if (currency == ECurrency.BTC)
            {
                if (string.IsNullOrWhiteSpace(ReservedFundsAddress))
                {
                    yield return(new ValidationResult($"{nameof(ReservedFundsAddress)} parameter is required for {currency}.", new[] { nameof(ReservedFundsAddress) }));
                }
                else if (string.IsNullOrWhiteSpace(ReservedFundsRedeemScript))
                {
                    yield return(new ValidationResult($"{nameof(ReservedFundsRedeemScript)} parameter is required for {currency}.", new[] { nameof(ReservedFundsRedeemScript) }));
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(ExpiryBlockNumber))
                {
                    yield return(new ValidationResult($"{nameof(ExpiryBlockNumber)} parameter is required for {currency}.", new[] { nameof(ExpiryBlockNumber) }));
                }
                else if (string.IsNullOrWhiteSpace((Executor)))
                {
                    yield return(new ValidationResult($"{nameof(Executor)} parameter is required for {currency}.", new[] { nameof(Executor) }));
                }
            }
        }