Example #1
0
        public new static CryptocurrencyMoney Parse(string amount, CryptocurrencyType type)
        {
            if (amount == null)
            {
                throw new ArgumentNullException();
            }
            if (amount == "")
            {
                return(null);
            }

            amount = amount.Replace(",", ".");
            Decimal ParsedAmount;

            try
            {
                ParsedAmount = Decimal.Parse(TrimEndWhitespaceAndZeros(amount), new System.Globalization.CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Can't parse " + TrimEndWhitespaceAndZeros(amount) + "; Are you sure it has correct CryptocurrencyMoney value?");
            }

            return(new CryptocurrencyMoney(type, ParsedAmount));
        }
Example #2
0
 private CryptocurrencyWithdrawalAddress(int userId, string address, CryptocurrencyType cryptocurrenyType)
 {
     this.CryptocurrencyCode = cryptocurrenyType.ToString();
     this.UserId             = userId;
     this.Address            = address;
     this.DateAdded          = AppSettings.ServerTime;
     this.IsNew = true;
 }
Example #3
0
        public static void Remove(int userId, CryptocurrencyMoney amount, CryptocurrencyType code)
        {
            var userBalance = GetObject(userId, code);
            if (userBalance.Balance - amount < new CryptocurrencyMoney(code, 0))
                throw new Exception(String.Format(U6010.ERRORREMOVECRYPTOCURRENCYBALANCE, amount, userId, userBalance.Balance));

            userBalance.Balance -= amount;
            userBalance.Save(); 
        }
Example #4
0
        private void ValidateWithdrawal(Member user, string userAddress, decimal amount, WithdrawalSourceBalance withdrawalSource)
        {
            if (!WithdrawalEnabled)
            {
                throw new MsgException("Withdrawal is currently disabled by the administrator");
            }

            if (CryptocurrencyApi.IsAdministratorAddress(userAddress, WithdrawalApiProcessor))
            {
                throw new MsgException("You can't withdraw to administrator-generated address.");
            }

            Money  amountInCorrectType = Money.Zero;
            string errorMessage        = String.Empty;

            //General validation
            PayoutManager.ValidatePayoutNotConnectedToAmount(user);

            //Amounts & Balances
            if (withdrawalSource == WithdrawalSourceBalance.MainBalance)
            {
                amountInCorrectType = new Money(amount);

                //Check the balance
                if (amountInCorrectType > user.MainBalance)
                {
                    throw new MsgException(L1.NOTENOUGHFUNDS);
                }

                PayoutManager.ValidatePayout(user, amountInCorrectType);
                PayoutManager.CheckMaxPayout(CryptocurrencyTypeHelper.ConvertToPaymentProcessor(CryptocurrencyType), user, amountInCorrectType);
            }
            else //Wallets
            {
                amountInCorrectType = new CryptocurrencyMoney(this.Type, amount);

                //Check the balance
                if (amountInCorrectType > user.GetCryptocurrencyBalance(CryptocurrencyType))
                {
                    throw new MsgException(string.Format(U6012.NOFUNDSINWALLET, CryptocurrencyType.ToString()));
                }
            }

            //Check MIN withdrawal
            if (amountInCorrectType < GetMinimumWithdrawalAmount(user, withdrawalSource))
            {
                throw new MsgException(U5003.WITHDRAWALMUSTBEHIGHER);
            }

            //Check MAX withdrawals
            if (amountInCorrectType > GetMaximumWithdrawalAmount(user, withdrawalSource, out errorMessage))
            {
                throw new MsgException(errorMessage);
            }
        }
 /// <summary>
 /// Get a paginated list of all cryptocurrencies with latest market data.
 /// <para>You can configure this call to sort by market cap or another market ranking field. Use the "convert" option to return market values in multiple fiat and cryptocurrency conversions in the same call.</para>
 /// </summary>
 /// <param name="start">>=1, Default=1. Optionally offset the start (1-based index) of the paginated list of items to return.</param>
 /// <param name="limit">[1 ... 5000] Default=100. Optionally specify the number of results to return. Use this parameter and the "start" parameter to determine your own pagination size.</param>
 /// <param name="convert">Optionally calculate market quotes in up to 32 currencies at once by passing a comma-separated list of cryptocurrency or fiat currency symbols. Each additional convert option beyond the first requires an additional call credit. A list of supported fiat options can be found here. Each conversion is returned in its own "quote" object.</param>
 /// <param name="sort">What field to sort the list of cryptocurrencies by.</param>
 /// <param name="sort_dir">The direction in which to order cryptocurrencies against the specified sort.</param>
 /// <param name="cryptocurrency_type">The type of cryptocurrency to include.</param>
 /// <returns></returns>
 public Pro.Model.Cryptocurrency.ListingsData CryptocurrencyListingsLatest(
     int?start              = 1,
     int?limit              = 100,
     FiatCurrency convert   = FiatCurrency.USD,
     SortBy sort            = SortBy.market_cap,
     SortDirection sort_dir = SortDirection.desc,
     CryptocurrencyType cryptocurrency_type = CryptocurrencyType.all
     )
 {
     return(this.CryptocurrencyListingsLatestAsync(start, limit, convert, sort, sort_dir, cryptocurrency_type).Result);
 }
Example #6
0
        public static CryptocurrencyType GetCryptocurrencyType(string cryptocurrencyCode)
        {
            CryptocurrencyType result = CryptocurrencyType.ERC20Token;

            try
            {
                result = (CryptocurrencyType)Enum.Parse(typeof(CryptocurrencyType), cryptocurrencyCode);
            }
            catch (Exception ex) { }
            return(result);
        }
Example #7
0
    public static string GetPaymentButton(BaseButtonGenerator bg, CryptocurrencyType t)
    {
        var cryptocurrency = CryptocurrencyFactory.Get(t);
        var sb             = new StringBuilder();

        if (cryptocurrency.DepositEnabled && CryptocurrencyApiFactory.Get(cryptocurrency.DepositApiProcessor).AllowToUsePaymentButtons())
        {
            sb.Append(GetBtcButton(bg));
        }

        return(string.IsNullOrEmpty(sb.ToString()) ? U6011.NOACTIVEPAYMENTPROCESSORS : sb.ToString());
    }
Example #8
0
        public static Cryptocurrency Get(CryptocurrencyType cryptocurrencyType)
        {
            var cache      = new CryptocurrenciesCache();
            var dictionary = (Dictionary <CryptocurrencyType, Cryptocurrency>)cache.Get();

            //ERCFreezed is basically ERC20Token when it comes to token properties
            if (cryptocurrencyType == CryptocurrencyType.ERCFreezed)
            {
                cryptocurrencyType = CryptocurrencyType.ERC20Token;
            }

            return(dictionary[cryptocurrencyType]);
        }
Example #9
0
        private static List <CryptocurrencyApi> GetEnabledApis(CryptocurrencyType cryptocurrencyType, string columnToCheck)
        {
            var query = String.Format("SELECT TypeInt FROM CryptocurrencyApis WHERE Enabled = 1 AND TypeInt IN " +
                                      "(SELECT TypeInt FROM CryptocurrencyApiOperations WHERE {1} = 1 AND CryptocurrencyTypeId = {0})", (int)cryptocurrencyType, columnToCheck);
            var list = TableHelper.GetStringListFromRawQuery(query);

            var result = new List <CryptocurrencyApi>();

            foreach (var api in list)
            {
                result.Add(CryptocurrencyApiFactory.Get((CryptocurrencyAPIProvider)Convert.ToInt32(api)));
            }

            return(result);
        }
Example #10
0
        public async Task <Pro.Model.Cryptocurrency.ListingsData> CryptocurrencyListingsHistoricalAsync(
            DateTime timestamp,
            int?start              = 1,
            int?limit              = 100,
            FiatCurrency convert   = FiatCurrency.USD,
            SortBy sort            = SortBy.market_cap,
            SortDirection sort_dir = SortDirection.desc,
            CryptocurrencyType cryptocurrency_type = CryptocurrencyType.all
            )
        {
            HttpClient _httpClient = new HttpClient {
                BaseAddress = new Uri(Pro.Config.Cryptocurrency.CoinMarketCapProApiUrl)
            };

            _httpClient.DefaultRequestHeaders.Add("X-CMC_PRO_API_KEY", this.ProApiKey);

            var url = QueryStringService.AppendQueryString(Pro.Config.Cryptocurrency.CryptocurrencyListingsHistorical, new Dictionary <string, string>
            {
                { "timestamp", timestamp.ToUnixTimeSeconds().ToString() },
                { "start", start.HasValue && start.Value >= 1 ? start.Value.ToString() : null },
                { "limit", limit.HasValue && limit.Value >= 1 ? limit.Value.ToString() : null },
                { "convert", convert.ToString() },
                { "sort", sort.ToString() },
                { "sort_dir", sort_dir.ToString() },
                { "cryptocurrency_type", cryptocurrency_type.ToString() },
            });
            var response = await _httpClient.GetAsync(url);

            Pro.Model.Cryptocurrency.ListingsData data = await JsonParserService.ParseResponse <Pro.Model.Cryptocurrency.ListingsData>(response);

            if (data == null)
            {
                data = new Pro.Model.Cryptocurrency.ListingsData
                {
                    Data   = null,
                    Status = new Status {
                        ErrorCode = int.MinValue
                    },
                    Success = false
                };
            }
            data.Success = data.Status.ErrorCode == 0;

            // Add to Status List
            this.statusList.Add(data.Status);

            return(data);
        }
Example #11
0
    public static void AddIfNotExists(int userId, string address, CryptocurrencyType cryptocurrenyType)
    {
        var currentAddresses = GetAddress(userId, cryptocurrenyType);

        if (currentAddresses == null)
        {
            var newAddress = new CryptocurrencyWithdrawalAddress(userId, address, cryptocurrenyType);
            newAddress.Save();
        }
        else if (currentAddresses.Address != address)
        {
            currentAddresses.Address   = address;
            currentAddresses.DateAdded = AppSettings.ServerTime;
            currentAddresses.IsNew     = false;
            currentAddresses.Save();
        }
    }
Example #12
0
        //  public async Task<CurrencyListings> GetCurrencyListingsHistoricalAsync(string timestamp, int start = 1, int limit = 100,
        //   List<string> convert = null, SortBy sort = SortBy.Market_Cap, SortDirection sort_dir = SortDirection.Desc,
        //   CryptocurrencyType cryptocurrency_type = CryptocurrencyType.All)
        //  {

        //throw new CoinMarketCapException("Not implemented by CoinMarketCap");

        //   //var response = await Request<CurrencyListings>("cryptocurrency/listings/historical",
        //   // new QueryParams(timestamp.ToQueryParam("timestamp"), start.ToQueryParam("start"), limit.ToQueryParam("limit"),
        //	  //  convert.ToQueryParam("convert"), sort.ToQueryParam("sort"),
        //	  //  sort_dir.ToQueryParam("sort_dir"), cryptocurrency_type.ToQueryParam("cryptocurrency_type")));

        //   //return response;
        //  }

        public async Task <CurrencyListings> GetCurrencyListingsAsync(int start             = 1, int limit = 100,
                                                                      List <string> convert = null, SortBy sort = SortBy.Market_Cap, SortDirection sort_dir = SortDirection.Desc,
                                                                      CryptocurrencyType cryptocurrency_type = CryptocurrencyType.All)
        {
            if (convert == null || convert.Count == 0)
            {
                convert = new List <string> {
                    "USD"
                }
            }
            ;
            var response = await Request <CurrencyListings>("cryptocurrency/listings/latest",
                                                            new QueryParams(start.ToQueryParam("start"), limit.ToQueryParam("limit"), convert.ToQueryParam("convert"),
                                                                            sort.ToQueryParam("sort"), sort_dir.ToQueryParam("sort_dir"),
                                                                            cryptocurrency_type.ToQueryParam("cryptocurrency_type")));

            return(response);
        }
Example #13
0
        private static UserCryptocurrencyBalance GetObject(int userId, CryptocurrencyType code)
        {
            var result = TableHelper.GetListFromRawQuery<UserCryptocurrencyBalance>
                (String.Format("SELECT * FROM UserCryptocurrencyBalances WHERE UserId = {0} AND CurrencyCode = '{1}'", userId, code));

            if (result.Count > 0)
            {
                result[0].Balance.cryptocurrencyType = code; //CryptocurrenyMoney class fix
                return result[0];
            }

            UserCryptocurrencyBalance userCryptocurrencyBalance = new UserCryptocurrencyBalance();
            userCryptocurrencyBalance.Balance = new CryptocurrencyMoney(code, 0);
            userCryptocurrencyBalance.CurrencyCode = code.ToString();
            userCryptocurrencyBalance.UserId = userId;
            userCryptocurrencyBalance.Save();

            return userCryptocurrencyBalance;
        }
Example #14
0
        public static int GetDecimalPlaces(CryptocurrencyType type)
        {
            switch (type)
            {
            case CryptocurrencyType.BTC:
                return(8);

            case CryptocurrencyType.ETH:
                return(18);

            case CryptocurrencyType.XRP:
                return(6);

            case CryptocurrencyType.ERC20Token:
                return(CoreSettings.GetMaxDecimalPlaces(CurrencyType.Crypto));

            default:
                return(8);
            }
        }
Example #15
0
        public static PaymentProcessor ConvertToPaymentProcessor(CryptocurrencyType type)
        {
            switch (type)
            {
            case CryptocurrencyType.BTC:
                return(PaymentProcessor.BTC);

            case CryptocurrencyType.ETH:
                return(PaymentProcessor.ETH);

            case CryptocurrencyType.XRP:
                return(PaymentProcessor.ETH);

            case CryptocurrencyType.ERC20Token:
                return(PaymentProcessor.Null);

            default:
                return(PaymentProcessor.BTC);
            }
        }
Example #16
0
        public static BalanceType ConvertToBalanceType(CryptocurrencyType type)
        {
            switch (type)
            {
            case CryptocurrencyType.BTC:
                return(BalanceType.BTC);

            case CryptocurrencyType.ETH:
                return(BalanceType.ETH);

            case CryptocurrencyType.XRP:
                return(BalanceType.XRP);

            case CryptocurrencyType.ERC20Token:
                return(BalanceType.Token);

            case CryptocurrencyType.ERCFreezed:
                return(BalanceType.FreezedToken);

            default:
                return(BalanceType.BTC);
            }
        }
Example #17
0
 /// <summary>
 /// Do NOT require Save() on member
 /// </summary>
 /// <param name="cryptocurrencyType"></param>
 /// <param name="value"></param>
 /// <param name="note"></param>
 /// <param name="logType"></param>
 public void SubtractFromCryptocurrencyBalance(CryptocurrencyType cryptocurrencyType, decimal value, string note, BalanceLogType logType = BalanceLogType.Other)
 {
     SubtractFromCryptocurrencyBalance(cryptocurrencyType, new CryptocurrencyMoney(cryptocurrencyType, value), note, logType);
 }
Example #18
0
 public static string ToValue(this CryptocurrencyType value)
 {
     return(value.ToString().ToLower());
 }
Example #19
0
 public static QueryParam ToQueryParam(this CryptocurrencyType value, string param_name)
 {
     return(new QueryParam(param_name, value));
 }
 public CryptocurrencyWithdrawRequest(int userId, string address, Money amount, Money amountWithFee, CryptocurrencyType cryptocurrency, WithdrawalSourceBalance sourceBalance)
 {
     this.CryptocurrencyCode      = cryptocurrency.ToString();
     this.UserId                  = userId;
     this.Address                 = address;
     this.RequestDate             = AppSettings.ServerTime;
     this.Status                  = WithdrawRequestStatus.Pending;
     this.Amount                  = amount;
     this.AmountWithFee           = amountWithFee;
     this.WithdrawalSourceBalance = sourceBalance;
     this.CryptocurrencyObject    = CryptocurrencyFactory.Get(Cryptocurrency);
 }
Example #21
0
 public static void Add(int userId, CryptocurrencyMoney amount, CryptocurrencyType code)
 {
     var userBalance = GetObject(userId, code);
     userBalance.Balance += amount;
     userBalance.Save();
 }
Example #22
0
 public static void Set(int userId, CryptocurrencyType code, CryptocurrencyMoney value)
 {
     var userBalance = GetObject(userId, code);
     userBalance.Balance = value;
     userBalance.Save();
 }
Example #23
0
 public static Money GetMoneyValue(int userId, CryptocurrencyType code)
 {
     var balance = GetObject(userId, code).Balance;
     return new CryptocurrencyMoney(code, balance.ToDecimal());
 }
Example #24
0
        public static void TryPurchaseTokens(Member user, ICOStage stage, int numberOfTokens, BalanceType targetBalance)
        {
            var TokenCryprocurrency = CryptocurrencyFactory.Get(CryptocurrencyType.ERC20Token);

            if (numberOfTokens <= 0)
            {
                throw new MsgException(U5006.AMOUNTEQUALZERO);
            }

            if (numberOfTokens > stage.GetAvailableTokens())
            {
                throw new MsgException(U6012.NOTOKENSLEFT);
            }

            int userPurchasesInLast15min = ICOPurchase.GetUserPurchasesInLast15Min(stage.Id, user.Id);

            if (userPurchasesInLast15min + numberOfTokens > AppSettings.ICO.ICOPurchaseLimitPerUserPer15mins)
            {
                throw new MsgException(String.Format(U6012.COINSEXCEED15MIN, "<b>" + userPurchasesInLast15min + "</b>", TokenCryprocurrency.Code));
            }

            //All OK, let's charge the balance
            //If freeze system is enabled, purchased tokens are freezed
            CryptocurrencyType TypeOfPurchasedCoins = AppSettings.Ethereum.ERC20TokensFreezeSystemEnabled ? CryptocurrencyType.ERCFreezed : CryptocurrencyType.ERC20Token;
            Money totalAmount = numberOfTokens * stage.TokenPrice;

            if (targetBalance == BalanceType.PurchaseBalance)
            {
                if (totalAmount > user.PurchaseBalance)
                {
                    throw new MsgException(L1.NOTENOUGHFUNDS);
                }

                user.SubtractFromPurchaseBalance(totalAmount, TokenCryprocurrency.Code + " purchase", BalanceLogType.CoinPurchase);
                user.SaveBalances();
            }
            else if (targetBalance == BalanceType.BTC)
            {
                decimal amountInBTC = (totalAmount.ToDecimal() /
                                       CryptocurrencyFactory.Get(CryptocurrencyType.BTC).GetValue().ToDecimal()).TruncateDecimals(8);

                if (amountInBTC > user.GetCryptocurrencyBalance(CryptocurrencyType.BTC).ToDecimal())
                {
                    throw new MsgException(L1.NOTENOUGHFUNDS);
                }

                user.SubtractFromCryptocurrencyBalance(CryptocurrencyType.BTC, amountInBTC,
                                                       TokenCryprocurrency.Code + " purchase", BalanceLogType.CoinPurchase);
            }
            else
            {
                throw new ArgumentException("Invalid argument: " + targetBalance.ToString(), "targetBalance");
            }

            //Add history entry
            History.AddPurchase(user.Name, totalAmount, TokenCryprocurrency.Code);

            //Credit coins to Referrer
            decimal tokensCreditedToReferrer = 0;

            if (user.HasReferer)
            {
                var Referer = new Member(user.ReferrerId);
                tokensCreditedToReferrer = (Referer.Membership.ICOPurchasePercent / 100) * numberOfTokens;

                if (tokensCreditedToReferrer > 0)
                {
                    Referer.AddToCryptocurrencyBalance(TypeOfPurchasedCoins, tokensCreditedToReferrer, TokenCryprocurrency.Code + " purchase /ref/"
                                                       + user.Name, BalanceLogType.CoinPurchase);

                    if (TypeOfPurchasedCoins == CryptocurrencyType.ERCFreezed)
                    {
                        UserFreezedToken.Add(Referer.Id, tokensCreditedToReferrer);
                    }

                    user.IncreaseERC20TokensEarningsForDRef(tokensCreditedToReferrer);
                    user.SaveStatistics();
                }
            }

            //Add purchase entry
            ICOPurchase.Add(user.Id, numberOfTokens, tokensCreditedToReferrer + (decimal)numberOfTokens, stage.Id);

            //Add coins to balance
            user.AddToCryptocurrencyBalance(TypeOfPurchasedCoins, numberOfTokens, TokenCryprocurrency.Code + " purchase", BalanceLogType.CoinPurchase);
            if (TypeOfPurchasedCoins == CryptocurrencyType.ERCFreezed)
            {
                UserFreezedToken.Add(user.Id, Decimal.Parse(numberOfTokens.ToString()));
            }
        }
Example #25
0
 public abstract void TryWithDrawCryptocurrencyFromWallet(decimal amountInCryptocurrency, string userAddress, CryptocurrencyType cryptocurrencyType);
Example #26
0
 public QueryParam(string name, CryptocurrencyType value)
 {
     Name  = name;
     Value = value.ToValue();
 }
Example #27
0
 public Money GetCryptocurrencyBalanceInMoney(CryptocurrencyType cryptocurrencyType)
 {
     return(UserCryptocurrencyBalance.GetMoneyValue(Id, cryptocurrencyType));
 }
Example #28
0
 public CryptocurrencyMoney GetCryptocurrencyBalance(CryptocurrencyType cryptocurrencyType)
 {
     return(UserCryptocurrencyBalance.Get(this.Id, cryptocurrencyType));
 }
    public override void TryWithDrawCryptocurrencyFromWallet(decimal amountInCryptocurrency, string userAddress, CryptocurrencyType cryptocurrencyType)
    {
        string cmd = "create_withdrawal";

        using (WebClient client = new WebClient())
        {
            var values = new NameValueCollection();
            values["version"]      = "1";
            values["key"]          = AppSettings.Cryptocurrencies.CoinPaymentsApiKey;
            values["format"]       = "json";
            values["cmd"]          = cmd;
            values["amount"]       = amountInCryptocurrency.ToString();
            values["currency"]     = cryptocurrencyType.ToString();
            values["address"]      = userAddress;
            values["auto_confirm"] = "1";

            string SpecialParams = String.Format("{0}&amount={1}&currency={3}&address={2}&auto_confirm=1", cmd, amountInCryptocurrency.ToString(), userAddress,
                                                 cryptocurrencyType.ToString());

            client.Headers.Add("HMAC", GetSHA512HMAC(SpecialParams));

            try
            {
                var     response       = client.UploadValues(baseUrl, values);
                string  responseString = Encoding.Default.GetString(response);
                JObject o = JObject.Parse(responseString);

                if (o["error"].ToString() != "ok")
                {
                    throw new MsgException(o["error"].ToString());
                }
            }
            catch (Exception ex)
            {
                throw new MsgException(ex.Message);
            }
        }
    }
Example #30
0
 private void SubtractFromCryptocurrencyBalance(CryptocurrencyType cryptocurrencyType, CryptocurrencyMoney value, string note, BalanceLogType logType = BalanceLogType.Other)
 {
     UserCryptocurrencyBalance.Remove(this.Id, value, cryptocurrencyType);
     //Works on ONE crypto balance at the moment
     BalanceLog.Add(this, CryptocurrencyTypeHelper.ConvertToBalanceType(cryptocurrencyType), value.ToDecimal() * -1, note, logType);
 }