Exemple #1
0
        private static void ParseCurrencyValueFromNode(ref CurrencyValue newCurrency, XmlNode childnode)
        {
            String nodeValue = childnode.InnerText;

            Int32.TryParse(nodeValue, out Int32 intValue);
            Single.TryParse(nodeValue, out Single floatValue);
            switch (childnode.Name)
            {
            case "NumCode":
                newCurrency.CurrencyInfo.NumCode = intValue;
                break;

            case "CharCode":
                newCurrency.CurrencyInfo.CharCode = nodeValue.ToUpper();
                newCurrency.CurrencyInfoId        = nodeValue.ToUpper();
                break;

            case "Nominal":
                newCurrency.CurrencyInfo.Nominal = intValue;
                break;

            case "Name":
                newCurrency.CurrencyInfo.Name = nodeValue;
                break;

            case "Value":
                newCurrency.Value = floatValue;
                break;
            }
        }
Exemple #2
0
        public override async Task <string> IsPaymentMethodAllowedBasedOnInvoiceAmount(StoreBlob storeBlob,
                                                                                       Dictionary <CurrencyPair, Task <RateResult> > rate, Money amount, PaymentMethodId paymentMethodId)
        {
            Func <Money, Money, bool> compare    = null;
            CurrencyValue             limitValue = null;
            string errorMessage = null;

            if (storeBlob.LightningMaxValue != null)
            {
                compare      = (value, limit) => value > limit;
                limitValue   = storeBlob.LightningMaxValue;
                errorMessage = "The amount of the invoice is too high to be paid with lightning";
            }


            if (compare != null)
            {
                var currentRateToCrypto = await rate[new CurrencyPair(paymentMethodId.CryptoCode, limitValue.Currency)];

                if (currentRateToCrypto.BidAsk != null)
                {
                    var limitValueCrypto = Money.Coins(limitValue.Value / currentRateToCrypto.BidAsk.Bid);
                    if (compare(amount, limitValueCrypto))
                    {
                        return(errorMessage);
                    }
                }
            }

            return(string.Empty);
        }
Exemple #3
0
    public static void Main()
    {
        // Display the currency value.
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
        Decimal value = 16039.47m;

        Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
        Console.WriteLine("Currency Value: {0:C2}", value);

        // Serialize the currency data.
        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      fw   = new FileStream("currency.dat", FileMode.Create);
        CurrencyValue   data = new CurrencyValue(value, CultureInfo.CurrentCulture.Name);

        bf.Serialize(fw, data);
        fw.Close();
        Console.WriteLine();

        // Change the current thread culture.
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
        Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);

        // Deserialize the data.
        FileStream    fr           = new FileStream("currency.dat", FileMode.Open);
        CurrencyValue restoredData = (CurrencyValue)bf.Deserialize(fr);

        fr.Close();

        // Display the original value.
        CultureInfo culture = CultureInfo.CreateSpecificCulture(restoredData.CultureName);

        Console.WriteLine("Currency Value: {0}", restoredData.Amount.ToString("C2", culture));
    }
Exemple #4
0
        public void Write(CurrencyValue currencyObject)
        {
            var currencyValuesContext = new CurrencyValuesContext();

            currencyValuesContext.CurrencyValues.Add(currencyObject);
            currencyValuesContext.SaveChanges();
        }
Exemple #5
0
        private static void SaveValueDbWork(CurrencyValue value)
        {
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Para"].ConnectionString))
            {
                using (var cmd = new SqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = @"IF NOT EXISTS (SELECT * 
			                                           FROM [CurrencyValue] 
                                                       WHERE [Day] = @day
					                                         AND [Source] = @source
					                                         AND [Target] = @target
					                                         AND [ValueSource] = @valueSource
					                                         AND [ValueType] = @valueType
					                                         AND [Value] = @value)
                                        BEGIN
	                                        INSERT INTO [CurrencyValue] ([Day],[Source],[Target],[ValueSource],[ValueType],[Value])
	                                        VALUES (@day,@source,@target,@valueSource,@valueType,@value)                                            
                                        END";

                    cmd.Parameters.AddWithValue("@day", value.Day);
                    cmd.Parameters.AddWithValue("@source", value.Source.ToString());
                    cmd.Parameters.AddWithValue("@target", value.Target.ToString());
                    cmd.Parameters.AddWithValue("@valueSource", value.ValueSoruce.ToString());
                    cmd.Parameters.AddWithValue("@valueType", value.ValueType.ToString());
                    cmd.Parameters.AddWithValue("@value", value.Value);

                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
        public void Test_TwoEqualValues_DifferentSymbols_AreNotEqual()
        {
            var value1 = new CurrencyValue("£123.45");
            var value2 = new CurrencyValue("$123.45");

            Check.That(value1.Equals(value2)).IsFalse();
        }
        public void Test_TwoEqualValues_AreEqual()
        {
            var value1 = new CurrencyValue("£123.45");
            var value2 = new CurrencyValue("123.45 £");

            Check.That(value1.Equals(value2)).IsTrue();
        }
Exemple #8
0
 private void WriteInternal(CurrencyValue currencyObject)
 {
     using (StreamWriter outputFile = new StreamWriter(File.Open(Bootstrapper.FilePath + currencyObject.Type.ToString() + ".txt", FileMode.Append)))
     {
         outputFile.Write($"{currencyObject.Date.ToShortDateString()};{currencyObject.Type.ToString()};{currencyObject.Value};{currencyObject.ReferenceNumber}\r\n");
     }
 }
Exemple #9
0
        public async Task <IActionResult> CheckoutExperience(CheckoutExperienceViewModel model)
        {
            CurrencyValue lightningMaxValue = null;

            if (!string.IsNullOrWhiteSpace(model.LightningMaxValue))
            {
                if (!CurrencyValue.TryParse(model.LightningMaxValue, out lightningMaxValue))
                {
                    ModelState.AddModelError(nameof(model.LightningMaxValue), "Invalid lightning max value");
                }
            }

            CurrencyValue onchainMinValue = null;

            if (!string.IsNullOrWhiteSpace(model.OnChainMinValue))
            {
                if (!CurrencyValue.TryParse(model.OnChainMinValue, out onchainMinValue))
                {
                    ModelState.AddModelError(nameof(model.OnChainMinValue), "Invalid on chain min value");
                }
            }
            bool needUpdate = false;
            var  blob       = StoreData.GetStoreBlob();

            if (StoreData.GetDefaultCrypto() != model.DefaultCryptoCurrency)
            {
                needUpdate = true;
                StoreData.SetDefaultCrypto(model.DefaultCryptoCurrency);
            }
            model.SetCryptoCurrencies(_ExplorerProvider, model.DefaultCryptoCurrency);
            model.SetLanguages(_LangService, model.DefaultLang);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            blob.DefaultLang         = model.DefaultLang;
            blob.AllowCoinConversion = model.AllowCoinConversion;
            blob.RequiresRefundEmail = model.RequiresRefundEmail;
            blob.LightningMaxValue   = lightningMaxValue;
            blob.OnChainMinValue     = onchainMinValue;
            blob.CustomLogo          = string.IsNullOrWhiteSpace(model.CustomLogo) ? null : new Uri(model.CustomLogo, UriKind.Absolute);
            blob.CustomCSS           = string.IsNullOrWhiteSpace(model.CustomCSS) ? null : new Uri(model.CustomCSS, UriKind.Absolute);
            blob.HtmlTitle           = string.IsNullOrWhiteSpace(model.HtmlTitle) ? null : model.HtmlTitle;
            if (StoreData.SetStoreBlob(blob))
            {
                needUpdate = true;
            }
            if (needUpdate)
            {
                await _Repo.UpdateStore(StoreData);

                StatusMessage = "Store successfully updated";
            }

            return(RedirectToAction(nameof(CheckoutExperience), new
            {
                storeId = StoreData.Id
            }));
        }
        public static decimal GetOrDefault(this CurrencyValue value)
        {
            if (!value.IsDefined())
            {
                return(default(decimal));
            }

            return(value.Value);
        }
Exemple #11
0
        /// <summary>
        /// Saves <see cref="CurrencyModel"/> into database
        /// </summary>
        /// <param name="result"><see cref="CurrencyModel"/></param>
        /// <returns></returns>
        public async Task SaveAsync(CurrencyResultResponse result)
        {
            using (var transaction = await _dbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    var currencyValue = await _dbContext.CurrencyValues.Include(c => c.Currency)
                                        .FirstOrDefaultAsync(c =>
                                                             c.DailyDataOfCurrency == result.DailyDataOfCurrency &&
                                                             c.Currency.CurrencyBeingMeasured == result.CurrencyBeingMeasured &&
                                                             c.Currency.CurrencyMatched == result.CurrencyMatched);

                    if (currencyValue != null)
                    {
                        return;
                    }

                    var currency = await _dbContext.Currencies.FirstOrDefaultAsync(c =>
                                                                                   c.CurrencyBeingMeasured == result.CurrencyBeingMeasured && c.CurrencyMatched == result.CurrencyMatched);

                    if (currency == null)
                    {
                        currency = new Currency
                        {
                            CurrencyBeingMeasured = result.CurrencyBeingMeasured,
                            CurrencyMatched       = result.CurrencyMatched
                        };

                        var currencyEntity = await _dbContext.Currencies.AddAsync(currency);

                        currency = currencyEntity.Entity;
                    }

                    currencyValue = new CurrencyValue
                    {
                        Value = result.CurrencyValue,
                        DailyDataOfCurrency = result.DailyDataOfCurrency,
                        Currency            = currency
                    };

                    await _dbContext.CurrencyValues.AddAsync(currencyValue);

                    await _dbContext.SaveChangesAsync();

                    await transaction.CommitAsync();
                }
                catch
                {
                    await transaction.RollbackAsync();

                    throw;
                }
            }
        }
Exemple #12
0
 public Revenue(CurrencyValue gross, DateTimeWithTimeZone accepted = null, CurrencyValue notTaxable = null, TaxRateItem lowerTaxRate = null, TaxRateItem reducedTaxRate = null, TaxRateItem standardTaxRate = null, CurrencyValue travelServices = null, CurrencyValue deposit = null, CurrencyValue usedDeposit = null)
 {
     Accepted        = accepted ?? DateTimeProvider.Now;
     Gross           = gross;
     NotTaxable      = notTaxable;
     LowerTaxRate    = lowerTaxRate;
     ReducedTaxRate  = reducedTaxRate;
     StandardTaxRate = standardTaxRate;
     TravelServices  = travelServices;
     Deposit         = deposit;
     UsedDeposit     = usedDeposit;
 }
Exemple #13
0
 public void ToLists()
 {
     CurrencyName.Add("polski złoty");
     CurrencyValue.Add(1);
     CurrencySignature.Add("PLN");
     foreach (var value in CurrencyCalculatorApiJsonVariable[0].Rates)
     {
         CurrencyName.Add(value.Currency);
         CurrencyValue.Add(value.Mid);
         CurrencySignature.Add(value.Code);
     }
 }
Exemple #14
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     try
     {
         return(reader.TokenType == JsonToken.Null ? null :
                CurrencyValue.TryParse((string)reader.Value, out var result) ? result :
                throw new JsonObjectException("Invalid Currency value", reader));
     }
     catch (InvalidCastException)
     {
         throw new JsonObjectException("Invalid Currency value", reader);
     }
 }
        /// <summary>
        /// Gets current price information for all items.
        /// </summary>
        /// <param name="value">The type(s) of price values desired to be included in the response.</param>
        /// <param name="since">If set, only items with prices newer than this <see cref="DateTimeOffset"/> will be returned.</param>
        public async Task <ItemPrices> GetItemPricesAsync(CurrencyValue value  = CurrencyValue.None,
                                                          DateTimeOffset?since = null)
        {
            var dto = (since ?? UnixEpoch).ToUniversalTime();

            if (dto < UnixEpoch)
            {
                throw new ArgumentOutOfRangeException(nameof(since),
                                                      "The specified value must be greater than the value of the UNIX epoch.");
            }

            return(await GetAsync <ItemPrices>("IGetPrices/v4",
                                               ("raw", (int)value),
                                               ("since", (dto - UnixEpoch).TotalSeconds)).ConfigureAwait(false));
        }
        public async Task <IActionResult> CheckoutExperience(string storeId, CheckoutExperienceViewModel model)
        {
            CurrencyValue currencyValue = null;

            if (!string.IsNullOrWhiteSpace(model.LightningMaxValue))
            {
                if (!CurrencyValue.TryParse(model.LightningMaxValue, out currencyValue))
                {
                    ModelState.AddModelError(nameof(model.LightningMaxValue), "Invalid currency value");
                }
            }
            var store = await _Repo.FindStore(storeId, GetUserId());

            if (store == null)
            {
                return(NotFound());
            }
            bool needUpdate = false;
            var  blob       = store.GetStoreBlob();

            if (store.GetDefaultCrypto() != model.DefaultCryptoCurrency)
            {
                needUpdate = true;
                store.SetDefaultCrypto(model.DefaultCryptoCurrency);
            }
            model.SetCryptoCurrencies(_ExplorerProvider, model.DefaultCryptoCurrency);
            model.SetLanguages(_LangService, model.DefaultLang);
            blob.DefaultLang         = model.DefaultLang;
            blob.AllowCoinConversion = model.AllowCoinConversion;
            blob.LightningMaxValue   = currencyValue;
            blob.CustomLogo          = model.CustomLogo;
            blob.CustomCSS           = model.CustomCSS;
            if (store.SetStoreBlob(blob))
            {
                needUpdate = true;
            }
            if (needUpdate)
            {
                await _Repo.UpdateStore(store);

                StatusMessage = "Store successfully updated";
            }

            return(RedirectToAction(nameof(CheckoutExperience), new
            {
                storeId = storeId
            }));
        }
Exemple #17
0
        public TaxData(
            CurrencyValue standartRate     = null,
            CurrencyValue reducedRate      = null,
            CurrencyValue lowerReducedRate = null,
            CurrencyValue zeroRate         = null,
            CurrencyValue specialRate      = null
            )
        {
            var fallback = new CurrencyValue(0);

            StandardRate     = standartRate ?? fallback;
            ReducedRate      = reducedRate ?? fallback;
            LowerReducedRate = lowerReducedRate ?? fallback;
            ZeroRate         = zeroRate ?? fallback;
            SpecialRate      = specialRate ?? fallback;
        }
Exemple #18
0
        private async Task MigratePaymentMethodCriteria()
        {
            using var ctx = _DBContextFactory.CreateContext();
            foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
            {
                var blob = store.GetStoreBlob();

                CurrencyValue onChainMinValue   = null;
                CurrencyValue lightningMaxValue = null;
                if (blob.AdditionalData.TryGetValue("onChainMinValue", out var onChainMinValueJToken))
                {
                    CurrencyValue.TryParse(onChainMinValueJToken.Value <string>(), out onChainMinValue);
                    blob.AdditionalData.Remove("onChainMinValue");
                }
                if (blob.AdditionalData.TryGetValue("lightningMaxValue", out var lightningMaxValueJToken))
                {
                    CurrencyValue.TryParse(lightningMaxValueJToken.Value <string>(), out lightningMaxValue);
                    blob.AdditionalData.Remove("lightningMaxValue");
                }
                blob.PaymentMethodCriteria = store.GetEnabledPaymentIds(_NetworkProvider).Select(paymentMethodId =>
                {
                    var matchedFromBlob =
                        blob.PaymentMethodCriteria?.SingleOrDefault(criteria => criteria.PaymentMethod == paymentMethodId && criteria.Value != null);
                    return(matchedFromBlob switch
                    {
                        null when paymentMethodId.PaymentType == LightningPaymentType.Instance &&
                        lightningMaxValue != null => new PaymentMethodCriteria()
                        {
                            Above = false,
                            PaymentMethod = paymentMethodId,
                            Value = lightningMaxValue
                        },
                        null when paymentMethodId.PaymentType == BitcoinPaymentType.Instance &&
                        onChainMinValue != null => new PaymentMethodCriteria()
                        {
                            Above = true,
                            PaymentMethod = paymentMethodId,
                            Value = onChainMinValue
                        },
                        _ => new PaymentMethodCriteria()
                        {
                            PaymentMethod = paymentMethodId,
                            Above = matchedFromBlob?.Above ?? true,
                            Value = matchedFromBlob?.Value
                        }
                    });
                }).ToList();
Exemple #19
0
        private static List <CurrencyValue> GetCurrencyValuesFromXmlRoot(XmlElement root, DateTime forDate)
        {
            List <CurrencyValue> result = new List <CurrencyValue>();

            foreach (XmlNode node in root)
            {
                CurrencyValue newCurrency = new CurrencyValue()
                {
                    Date = forDate.Date
                };
                foreach (XmlNode childnode in node.ChildNodes)
                {
                    ParseCurrencyValueFromNode(ref newCurrency, childnode);
                }
                result.Add(newCurrency);
            }
            return(result);
        }
        public override CurrencyValue[] GetCosts(ItemStack itemStack)
        {
            List <CurrencyValue> validCosts = new List <CurrencyValue>();

            if (!m_UseItemValues)
            {
                foreach (CurrencyValue cost in m_Costs)
                {
                    if (cost.Currency.ConsistencyCheck())
                    {
                        validCosts.Add(cost);
                    }
                }
            }
            else
            {
                validCosts.Add(itemStack.Item.CurrencyValue);
            }

            float multiplier = 1.0f;

            if (m_ScaleByExplicitCount)
            {
                multiplier += itemStack.ExplicitMods.Length;
            }
            if (m_ScaleByImplicitCount)
            {
                multiplier += itemStack.ImplicitMods.Length;
            }
            if (m_ScaleByPowerLevel)
            {
                multiplier += itemStack.PowerLevel;
            }
            multiplier *= m_Multiplier;
            for (int i = 0; i < validCosts.Count; i++)
            {
                CurrencyValue cv = validCosts[i];
                cv.Value      = (long)(cv.Value * multiplier);
                validCosts[i] = cv;
            }
            return(validCosts.ToArray());
        }
        public override bool OnBeforeSerialize()
        {
            if (!m_WalletIdentifier.ConsistencyCheck())
            {
                return(false);
            }
            var currencyList = m_WalletIdentifier.Object.CurrencyList;

            m_Currencies = new CurrencyValue[currencyList.Count];
            int i = 0;

            foreach (var currency in currencyList)
            {
                m_Currencies[i] = new CurrencyValue();
                m_Currencies[i].Currency.Identifier = currency.Key;
                m_Currencies[i].Value = currency.Value;
                i++;
            }
            return(true);
        }
Exemple #22
0
        public JsonResult SaveCurrencyValue(CurrencyValue ObjToSave)
        {
            MsgUnit Msg = new MsgUnit();

            try
            {
                var userId   = User.Identity.GetUserId();
                var UserInfo = _unitOfWork.User.GetMyInfo(userId);
                ObjToSave.InsDateTime = DateTime.Now;
                ObjToSave.InsUserID   = userId;
                ObjToSave.CompanyID   = UserInfo.fCompanyId;

                if (!ModelState.IsValid)
                {
                    string Err    = " ";
                    var    errors = ModelState.Values.SelectMany(v => v.Errors);
                    foreach (ModelError error in errors)
                    {
                        Err = Err + error.ErrorMessage + " * ";
                    }

                    Msg.Msg  = Resources.Resource.SomthingWentWrong + " : " + Err;
                    Msg.Code = 0;
                    return(Json(Msg, JsonRequestBehavior.AllowGet));
                }
                _unitOfWork.CurrencyValue.Add(ObjToSave);
                _unitOfWork.Complete();
                Msg.Code = 1;
                Msg.Msg  = Resources.Resource.AddedSuccessfully;
                return(Json(Msg, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Msg.Msg  = Resources.Resource.SomthingWentWrong + " : " + ex.Message.ToString();
                Msg.Code = 0;
                return(Json(Msg, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #23
0
        private static Dictionary <string, CurrencyValue> PrepareCrossRate(List <CurrencyValue> values)
        {
            var crossRate = new Dictionary <string, CurrencyValue>();

            foreach (var currencyValue in values)
            {
                foreach (var value in values.Where(value => currencyValue.ValueType == value.ValueType))
                {
                    var key = string.Format("{0}-{1}-{2}", currencyValue.Source, value.Source, value.ValueType);

                    crossRate[key] = new CurrencyValue
                    {
                        Day         = value.Day,
                        Source      = currencyValue.Source,
                        Target      = value.Source,
                        ValueSoruce = value.ValueSoruce,
                        ValueType   = value.ValueType,
                        Value       = Convert.ToDecimal((currencyValue.Value / value.Value).ToString("##.####"))
                    };
                }
            }
            return(crossRate);
        }
Exemple #24
0
    public GameCurrencySystem(UserInterfaceSystem ui)
    {
        map     = new Dictionary <GameCurrency, CurrencyValue>();
        buffers = new Dictionary <GameCurrency, CurrencyValue>();

        var currencies = (GameCurrency[])System.Enum.GetValues(typeof(GameCurrency));

        System.Action <GameCurrency, int> onSetMainCurrencyValueCallback = null;
        onSetMainCurrencyValueCallback += (currency, value) => PersistentData.SetIntEncoded(GetType(), (int)currency, value);
        onSetMainCurrencyValueCallback += ui.DisplayCurrency;

        System.Action <GameCurrency, int> onSetBufferCurrencyValueCallback = ui.DisplayBufferCurrency;

        foreach (var currency in currencies)
        {
            var persistentCurrencyValue = new CurrencyValue(true, currency, onSetMainCurrencyValueCallback);
            persistentCurrencyValue.Value = PersistentData.GetIntDecoded(GetType(), (int)currency);
            map.Add(currency, persistentCurrencyValue);

            var bufferCurrencyValue = new CurrencyValue(true, currency, onSetBufferCurrencyValueCallback);
            buffers.Add(currency, bufferCurrencyValue);
        }
    }
Exemple #25
0
        public override async Task <string> IsPaymentMethodAllowedBasedOnInvoiceAmount(StoreBlob storeBlob,
                                                                                       Dictionary <CurrencyPair, Task <RateResult> > rate, Money amount, PaymentMethodId paymentMethodId)
        {
            Func <Money, Money, bool> compare    = null;
            CurrencyValue             limitValue = null;
            string errorMessage = null;

            if (paymentMethodId.PaymentType == PaymentTypes.LightningLike &&
                storeBlob.LightningMaxValue != null)
            {
                compare      = (a, b) => a > b;
                limitValue   = storeBlob.LightningMaxValue;
                errorMessage = "The amount of the invoice is too high to be paid with lightning";
            }
            else if (paymentMethodId.PaymentType == PaymentTypes.BTCLike &&
                     storeBlob.OnChainMinValue != null)
            {
                compare      = (a, b) => a < b;
                limitValue   = storeBlob.OnChainMinValue;
                errorMessage = "The amount of the invoice is too low to be paid on chain";
            }

            if (compare != null)
            {
                var limitValueRate = await rate[new CurrencyPair(paymentMethodId.CryptoCode, storeBlob.OnChainMinValue.Currency)];
                if (limitValueRate.BidAsk != null)
                {
                    var limitValueCrypto = Money.Coins(limitValue.Value / limitValueRate.BidAsk.Bid);
                    if (compare(amount, limitValueCrypto))
                    {
                        return(errorMessage);
                    }
                }
            }
            return(string.Empty);
        }
Exemple #26
0
        public async Task <IActionResult> CheckoutExperience(CheckoutExperienceViewModel model)
        {
            bool needUpdate             = false;
            var  blob                   = CurrentStore.GetStoreBlob();
            var  defaultPaymentMethodId = model.DefaultPaymentMethod == null ? null : PaymentMethodId.Parse(model.DefaultPaymentMethod);

            if (CurrentStore.GetDefaultPaymentId(_NetworkProvider) != defaultPaymentMethodId)
            {
                needUpdate = true;
                CurrentStore.SetDefaultPaymentId(defaultPaymentMethodId);
            }
            SetCryptoCurrencies(model, CurrentStore);
            model.SetLanguages(_LangService, model.DefaultLang);
            model.PaymentMethodCriteria ??= new List <PaymentMethodCriteriaViewModel>();
            for (var index = 0; index < model.PaymentMethodCriteria.Count; index++)
            {
                var methodCriterion = model.PaymentMethodCriteria[index];
                if (!string.IsNullOrWhiteSpace(methodCriterion.Value))
                {
                    if (!CurrencyValue.TryParse(methodCriterion.Value, out var value))
                    {
                        model.AddModelError(viewModel => viewModel.PaymentMethodCriteria[index].Value,
                                            $"{methodCriterion.PaymentMethod}: invalid format (1.0 USD)", this);
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            blob.PaymentMethodCriteria = model.PaymentMethodCriteria
                                         .Where(viewModel => !string.IsNullOrEmpty(viewModel.Value)).Select(viewModel =>
            {
                CurrencyValue.TryParse(viewModel.Value, out var cv);
                return(new PaymentMethodCriteria()
                {
                    Above = viewModel.Type == PaymentMethodCriteriaViewModel.CriteriaType.GreaterThan, Value = cv, PaymentMethod = PaymentMethodId.Parse(viewModel.PaymentMethod)
                });
            }).ToList();

            blob.RequiresRefundEmail          = model.RequiresRefundEmail;
            blob.LazyPaymentMethods           = model.LazyPaymentMethods;
            blob.LightningAmountInSatoshi     = model.LightningAmountInSatoshi;
            blob.LightningPrivateRouteHints   = model.LightningPrivateRouteHints;
            blob.OnChainWithLnInvoiceFallback = model.OnChainWithLnInvoiceFallback;
            blob.RedirectAutomatically        = model.RedirectAutomatically;
            blob.ShowRecommendedFee           = model.ShowRecommendedFee;
            blob.RecommendedFeeBlockTarget    = model.RecommendedFeeBlockTarget;

            blob.CustomLogo  = model.CustomLogo;
            blob.CustomCSS   = model.CustomCSS;
            blob.HtmlTitle   = string.IsNullOrWhiteSpace(model.HtmlTitle) ? null : model.HtmlTitle;
            blob.DefaultLang = model.DefaultLang;

            if (CurrentStore.SetStoreBlob(blob))
            {
                needUpdate = true;
            }
            if (needUpdate)
            {
                await _Repo.UpdateStore(CurrentStore);

                TempData[WellKnownTempData.SuccessMessage] = "Store successfully updated";
            }

            return(RedirectToAction(nameof(CheckoutExperience), new
            {
                storeId = CurrentStore.Id
            }));
        }
Exemple #27
0
        private async Task <PaymentMethod> CreatePaymentMethodAsync(Dictionary <CurrencyPair, Task <RateResult> > fetchingByCurrencyPair, IPaymentMethodHandler handler, ISupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network, InvoiceEntity entity, StoreData store, InvoiceLogs logs)
        {
            try
            {
                var logPrefix      = $"{handler.ToPrettyString(supportedPaymentMethod.PaymentId)}:";
                var storeBlob      = store.GetStoreBlob();
                var preparePayment = handler.PreparePayment(supportedPaymentMethod, store, network);
                var rate           = await fetchingByCurrencyPair[new CurrencyPair(network.CryptoCode, entity.ProductInformation.Currency)];
                if (rate.BidAsk == null)
                {
                    return(null);
                }
                PaymentMethod paymentMethod = new PaymentMethod();
                paymentMethod.ParentEntity = entity;
                paymentMethod.Network      = network;
                paymentMethod.SetId(supportedPaymentMethod.PaymentId);
                paymentMethod.Rate        = rate.BidAsk.Bid;
                paymentMethod.PreferOnion = this.Request.IsOnion();

                using (logs.Measure($"{logPrefix} Payment method details creation"))
                {
                    var paymentDetails = await handler.CreatePaymentMethodDetails(supportedPaymentMethod, paymentMethod, store, network, preparePayment);

                    paymentMethod.SetPaymentMethodDetails(paymentDetails);
                }

                Func <Money, Money, bool> compare    = null;
                CurrencyValue             limitValue = null;
                string errorMessage = null;
                if (supportedPaymentMethod.PaymentId.PaymentType == PaymentTypes.LightningLike &&
                    storeBlob.LightningMaxValue != null)
                {
                    compare      = (a, b) => a > b;
                    limitValue   = storeBlob.LightningMaxValue;
                    errorMessage = "The amount of the invoice is too high to be paid with lightning";
                }
                else if (supportedPaymentMethod.PaymentId.PaymentType == PaymentTypes.BTCLike &&
                         storeBlob.OnChainMinValue != null)
                {
                    compare      = (a, b) => a < b;
                    limitValue   = storeBlob.OnChainMinValue;
                    errorMessage = "The amount of the invoice is too low to be paid on chain";
                }

                if (compare != null)
                {
                    var limitValueRate = await fetchingByCurrencyPair[new CurrencyPair(network.CryptoCode, limitValue.Currency)];
                    if (limitValueRate.BidAsk != null)
                    {
                        var limitValueCrypto = Money.Coins(limitValue.Value / limitValueRate.BidAsk.Bid);
                        if (compare(paymentMethod.Calculate().Due, limitValueCrypto))
                        {
                            logs.Write($"{logPrefix} {errorMessage}");
                            return(null);
                        }
                    }
                }
                ///////////////


#pragma warning disable CS0618
                if (paymentMethod.GetId().IsBTCOnChain)
                {
                    entity.TxFee          = paymentMethod.NextNetworkFee;
                    entity.Rate           = paymentMethod.Rate;
                    entity.DepositAddress = paymentMethod.DepositAddress;
                }
#pragma warning restore CS0618
                return(paymentMethod);
            }
            catch (PaymentMethodUnavailableException ex)
            {
                logs.Write($"{supportedPaymentMethod.PaymentId.CryptoCode}: Payment method unavailable ({ex.Message})");
            }
            catch (Exception ex)
            {
                logs.Write($"{supportedPaymentMethod.PaymentId.CryptoCode}: Unexpected exception ({ex.ToString()})");
            }
            return(null);
        }
Exemple #28
0
        public async Task <IActionResult> CheckoutExperience(CheckoutExperienceViewModel model)
        {
            CurrencyValue lightningMaxValue = null;

            if (!string.IsNullOrWhiteSpace(model.LightningMaxValue))
            {
                if (!CurrencyValue.TryParse(model.LightningMaxValue, out lightningMaxValue))
                {
                    ModelState.AddModelError(nameof(model.LightningMaxValue), "Invalid lightning max value");
                }
            }

            CurrencyValue onchainMinValue = null;

            if (!string.IsNullOrWhiteSpace(model.OnChainMinValue))
            {
                if (!CurrencyValue.TryParse(model.OnChainMinValue, out onchainMinValue))
                {
                    ModelState.AddModelError(nameof(model.OnChainMinValue), "Invalid on chain min value");
                }
            }
            bool needUpdate             = false;
            var  blob                   = CurrentStore.GetStoreBlob();
            var  defaultPaymentMethodId = model.DefaultPaymentMethod == null ? null : PaymentMethodId.Parse(model.DefaultPaymentMethod);

            if (CurrentStore.GetDefaultPaymentId(_NetworkProvider) != defaultPaymentMethodId)
            {
                needUpdate = true;
                CurrentStore.SetDefaultPaymentId(defaultPaymentMethodId);
            }
            SetCryptoCurrencies(model, CurrentStore);
            model.SetLanguages(_LangService, model.DefaultLang);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            blob.CustomLogo                = model.CustomLogo;
            blob.CustomCSS                 = model.CustomCSS;
            blob.HtmlTitle                 = string.IsNullOrWhiteSpace(model.HtmlTitle) ? null : model.HtmlTitle;
            blob.DefaultLang               = model.DefaultLang;
            blob.RequiresRefundEmail       = model.RequiresRefundEmail;
            blob.ShowRecommendedFee        = model.ShowRecommendedFee;
            blob.RecommendedFeeBlockTarget = model.RecommendedFeeBlockTarget;
            blob.OnChainMinValue           = onchainMinValue;
            blob.LightningMaxValue         = lightningMaxValue;
            blob.LightningAmountInSatoshi  = model.LightningAmountInSatoshi;
            blob.RedirectAutomatically     = model.RedirectAutomatically;
            if (CurrentStore.SetStoreBlob(blob))
            {
                needUpdate = true;
            }
            if (needUpdate)
            {
                await _Repo.UpdateStore(CurrentStore);

                TempData[WellKnownTempData.SuccessMessage] = "Store successfully updated";
            }

            return(RedirectToAction(nameof(CheckoutExperience), new
            {
                storeId = CurrentStore.Id
            }));
        }
Exemple #29
0
 public CurrencyValue Convert(CurrencyValue from, CurrencySymbol to) =>
 new CurrencyValue
 {
     Symbol = to,
     Amount = from.Amount * _conversionTable[(int)from.Symbol, (int)to]
 };
        public async Task <IActionResult> CheckoutAppearance(CheckoutAppearanceViewModel model)
        {
            bool needUpdate             = false;
            var  blob                   = CurrentStore.GetStoreBlob();
            var  defaultPaymentMethodId = model.DefaultPaymentMethod == null ? null : PaymentMethodId.Parse(model.DefaultPaymentMethod);

            if (CurrentStore.GetDefaultPaymentId() != defaultPaymentMethodId)
            {
                needUpdate = true;
                CurrentStore.SetDefaultPaymentId(defaultPaymentMethodId);
            }
            SetCryptoCurrencies(model, CurrentStore);
            model.SetLanguages(_LangService, model.DefaultLang);
            model.PaymentMethodCriteria ??= new List <PaymentMethodCriteriaViewModel>();
            for (var index = 0; index < model.PaymentMethodCriteria.Count; index++)
            {
                var methodCriterion = model.PaymentMethodCriteria[index];
                if (!string.IsNullOrWhiteSpace(methodCriterion.Value))
                {
                    if (!CurrencyValue.TryParse(methodCriterion.Value, out var value))
                    {
                        model.AddModelError(viewModel => viewModel.PaymentMethodCriteria[index].Value,
                                            $"{methodCriterion.PaymentMethod}: Invalid format. Make sure to enter a valid amount and currency code. Examples: '5 USD', '0.001 BTC'", this);
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Payment criteria for Off-Chain should also affect LNUrl
            foreach (var newCriteria in model.PaymentMethodCriteria.ToList())
            {
                var paymentMethodId = PaymentMethodId.Parse(newCriteria.PaymentMethod);
                if (paymentMethodId.PaymentType == PaymentTypes.LightningLike)
                {
                    model.PaymentMethodCriteria.Add(new PaymentMethodCriteriaViewModel()
                    {
                        PaymentMethod = new PaymentMethodId(paymentMethodId.CryptoCode, PaymentTypes.LNURLPay).ToString(),
                        Type          = newCriteria.Type,
                        Value         = newCriteria.Value
                    });
                }
                // Should not be able to set LNUrlPay criteria directly in UI
                if (paymentMethodId.PaymentType == PaymentTypes.LNURLPay)
                {
                    model.PaymentMethodCriteria.Remove(newCriteria);
                }
            }
            blob.PaymentMethodCriteria ??= new List <PaymentMethodCriteria>();
            foreach (var newCriteria in model.PaymentMethodCriteria)
            {
                var paymentMethodId  = PaymentMethodId.Parse(newCriteria.PaymentMethod);
                var existingCriteria = blob.PaymentMethodCriteria.FirstOrDefault(c => c.PaymentMethod == paymentMethodId);
                if (existingCriteria != null)
                {
                    blob.PaymentMethodCriteria.Remove(existingCriteria);
                }
                CurrencyValue.TryParse(newCriteria.Value, out var cv);
                blob.PaymentMethodCriteria.Add(new PaymentMethodCriteria()
                {
                    Above         = newCriteria.Type == PaymentMethodCriteriaViewModel.CriteriaType.GreaterThan,
                    Value         = cv,
                    PaymentMethod = paymentMethodId
                });
            }
            blob.RequiresRefundEmail   = model.RequiresRefundEmail;
            blob.LazyPaymentMethods    = model.LazyPaymentMethods;
            blob.RedirectAutomatically = model.RedirectAutomatically;
            blob.CustomLogo            = model.CustomLogo;
            blob.CustomCSS             = model.CustomCSS;
            blob.HtmlTitle             = string.IsNullOrWhiteSpace(model.HtmlTitle) ? null : model.HtmlTitle;
            blob.AutoDetectLanguage    = model.AutoDetectLanguage;
            blob.DefaultLang           = model.DefaultLang;

            if (CurrentStore.SetStoreBlob(blob))
            {
                needUpdate = true;
            }
            if (needUpdate)
            {
                await _Repo.UpdateStore(CurrentStore);

                TempData[WellKnownTempData.SuccessMessage] = "Store successfully updated";
            }

            return(RedirectToAction(nameof(CheckoutAppearance), new
            {
                storeId = CurrentStore.Id
            }));
        }