コード例 #1
0
        public Money Offer(
            ECXOnlyPubKey oraclePubKey,
            SchnorrNonce eventNonce,
            DiscretePayoffs offererPayoffs,
            Timeouts timeouts, Money?collateral = null)
        {
            using var tx = StartTransaction();
            if (!s.IsInitiator)
            {
                throw new InvalidOperationException("The acceptor can't initiate an offer");
            }
            s.OracleInfo     = new OracleInfo(oraclePubKey, eventNonce);
            s.Timeouts       = timeouts;
            s.OffererPayoffs = offererPayoffs;
            s.Offerer        = new Party();
            var minimumCollateral = offererPayoffs.CalculateMinimumCollateral();

            if (collateral is Money m && m < minimumCollateral)
            {
                throw new ArgumentException($"The collateral is too small, it should be at least {minimumCollateral.ToString(false, false)}");
            }
            s.Offerer.Collateral = collateral ?? minimumCollateral;
            tx.Commit();
            return(s.Offerer.Collateral);
        }
コード例 #2
0
 public ExpectedFundingViewModel(List <Models.ProjectGrantAllocationRequest> projectGrantAllocationRequests, Money?projectEstimatedTotalCost, string projectFundingSourceNotes, List <ProjectFundingSource> projectFundingSources)
 {
     ProjectGrantAllocationRequestSimples = projectGrantAllocationRequests.Select(x => new ProjectGrantAllocationRequestSimple(x)).ToList();
     ProjectEstimatedTotalCost            = projectEstimatedTotalCost;
     ProjectFundingSourceNotes            = projectFundingSourceNotes;
     FundingSourceIDs = projectFundingSources.Select(x => x.FundingSourceID).ToList();
 }
コード例 #3
0
 public WithNullableParam(decimal?x, Money?y, int?z, double?dbl)
 {
     X   = x;
     Y   = y;
     Z   = z;
     Dbl = dbl;
 }
コード例 #4
0
        public BroadcastTransactionViewModel(
            BitcoinStore store,
            Network network,
            TransactionBroadcaster broadcaster,
            SmartTransaction transaction)
        {
            Title = "Broadcast Transaction";

            var nullMoney  = new Money(-1L);
            var nullOutput = new TxOut(nullMoney, Script.Empty);

            var psbt = PSBT.FromTransaction(transaction.Transaction, network);

            TxOut GetOutput(OutPoint outpoint) =>
            store.TransactionStore.TryGetTransaction(outpoint.Hash, out var prevTxn)
                                        ? prevTxn.Transaction.Outputs[outpoint.N]
                                        : nullOutput;

            var inputAddressAmount = psbt.Inputs
                                     .Select(x => x.PrevOut)
                                     .Select(GetOutput)
                                     .ToArray();

            var outputAddressAmount = psbt.Outputs
                                      .Select(x => x.GetCoin().TxOut)
                                      .ToArray();

            var psbtTxn = psbt.GetOriginalTransaction();

            _transactionId     = psbtTxn.GetHash().ToString();
            _inputCount        = inputAddressAmount.Length;
            _inputCountString  = $" input{TextHelpers.AddSIfPlural(_inputCount)} and ";
            _outputCount       = outputAddressAmount.Length;
            _outputCountString = $" output{TextHelpers.AddSIfPlural(_outputCount)}.";
            _totalInputValue   = inputAddressAmount.Any(x => x.Value == nullMoney)
                                ? null
                                : inputAddressAmount.Select(x => x.Value).Sum();
            _totalOutputValue = outputAddressAmount.Any(x => x.Value == nullMoney)
                                ? null
                                : outputAddressAmount.Select(x => x.Value).Sum();
            _networkFee = TotalInputValue is null || TotalOutputValue is null
                                ? null
                                : TotalInputValue - TotalOutputValue;

            EnableCancel = true;

            EnableBack = false;

            this.WhenAnyValue(x => x.IsBusy)
            .Subscribe(x => EnableCancel = !x);

            var nextCommandCanExecute = this.WhenAnyValue(x => x.IsBusy)
                                        .Select(x => !x);

            NextCommand = ReactiveCommand.CreateFromTask(
                async() => await OnNext(broadcaster, transaction),
                nextCommandCanExecute);

            EnableAutoBusyOn(NextCommand);
        }
コード例 #5
0
        /// <summary>
        /// Updates the <see cref="T:EPiServer.Commerce.Order.ILineItem"/> item placed price or raises <see cref="T:EPiServer.Commerce.Order.ValidationIssue"/> if their is no valid price.
        ///
        /// </summary>
        /// <param name="lineItem">The line item.</param><param name="customerContact"/><param name="market">The market.</param><param name="currency">The currency.</param><param name="onValidationError">A callback that is invoked if a validation issue is detected.</param>
        /// <returns>
        /// False if is there is no valid price
        /// </returns>
        public override bool UpdatePlacedPrice(ILineItem lineItem, CustomerContact customerContact, IMarket market, Currency currency, Action <ILineItem, ValidationIssue> onValidationError)
        {
            EntryContentBase entryContent = lineItem.GetEntryContent(_referenceConverter, _contentLoader);

            if (entryContent == null)
            {
                onValidationError(lineItem, ValidationIssue.RemovedDueToUnavailableItem);
                return(false);
            }
            if (lineItem.Properties[Constants.Quote.PreQuotePrice] != null && !string.IsNullOrEmpty(lineItem.Properties[Constants.Quote.PreQuotePrice].ToString()))
            {
                return(true);
            }

            Money?placedPrice = GetPlacedPrice(entryContent, lineItem.Quantity, customerContact, market, currency);

            if (placedPrice.HasValue)
            {
                if (new Money(currency.Round(lineItem.PlacedPrice), currency) == placedPrice.Value)
                {
                    return(true);
                }
                onValidationError(lineItem, ValidationIssue.PlacedPricedChanged);
                lineItem.PlacedPrice = placedPrice.Value.Amount;
                return(true);
            }
            onValidationError(lineItem, ValidationIssue.RemovedDueToInvalidPrice);
            return(false);
        }
コード例 #6
0
        public void TryConvert_To_NullCurrency_DefaultConversion()
        {
            Money?thirteenEuro = 13m.Usd().TryConvert().To(null);

            Assert.That(thirteenEuro.HasValue, Is.False, "the default safe converter ignores null currency instances");
            Assert.That(thirteenEuro.GetValueOrDefault(), Is.EqualTo(default(Money)));
        }
コード例 #7
0
        public IDishFactory WithPrice(double ammount, string currency = null !)
        {
            Price      = new Money(ammount);
            IsPriceSet = true;

            return(this);
        }
コード例 #8
0
 public IntradayPrices(Money?open, Money?close, Money?high, Money?low)
 {
     this.Open  = open;
     this.Close = close;
     this.High  = high;
     this.Low   = low;
 }
コード例 #9
0
 public CoreNodeParams(
     Network network,
     MempoolService mempoolService,
     string dataDir,
     bool tryRestart,
     bool tryDeleteDataDir,
     EndPointStrategy p2pEndPointStrategy,
     EndPointStrategy rpcEndPointStrategy,
     int?txIndex,
     int?prune,
     string mempoolReplacement,
     string userAgent,
     Money?fallbackFee,
     IMemoryCache cache)
 {
     Network             = Guard.NotNull(nameof(network), network);
     MempoolService      = Guard.NotNull(nameof(mempoolService), mempoolService);
     DataDir             = Guard.NotNullOrEmptyOrWhitespace(nameof(dataDir), dataDir);
     TryRestart          = tryRestart;
     TryDeleteDataDir    = tryDeleteDataDir;
     P2pEndPointStrategy = Guard.NotNull(nameof(p2pEndPointStrategy), p2pEndPointStrategy);
     RpcEndPointStrategy = Guard.NotNull(nameof(rpcEndPointStrategy), rpcEndPointStrategy);
     TxIndex             = txIndex;
     Prune = prune;
     MempoolReplacement = mempoolReplacement;
     UserAgent          = Guard.NotNullOrEmptyOrWhitespace(nameof(userAgent), userAgent, trim: true);
     FallbackFee        = fallbackFee;
     Cache = Guard.NotNull(nameof(cache), cache);
 }
コード例 #10
0
        public void MoneyExplicitConversion_NullAmount_Null()
        {
            MonetaryQuantity noAmount = new MonetaryQuantity(null, "XXX");
            Money?           money    = (Money?)noAmount;

            Assert.That(money, Is.Null);
        }
コード例 #11
0
        private void PopulateVariationInfo(CatalogEntryDto.CatalogEntryRow entryRow, LineItem lineItem)
        {
            CatalogEntryDto.VariationRow variationRow = entryRow.GetVariationRows().FirstOrDefault();

            if (variationRow != null)
            {
                lineItem.MaxQuantity = variationRow.MaxQuantity;
                lineItem.MinQuantity = variationRow.MinQuantity;
                CustomerContact customerContact = CustomerContext.Current.GetContactById(lineItem.Parent.Parent.CustomerId);

                Money?newListPrice = GetItemPrice(entryRow, lineItem, customerContact);
                if (newListPrice.HasValue)
                {
                    Money oldListPrice = new Money(Math.Round(lineItem.ListPrice, 2), lineItem.Parent.Parent.BillingCurrency);

                    if (oldListPrice != newListPrice.Value)
                    {
                        AddWarningSafe(Warnings,
                                       "LineItemPriceChange-" + lineItem.Parent.LineItems.IndexOf(lineItem).ToString(),
                                       string.Format("Price for \"{0}\" has been changed from {1} to {2}.", lineItem.DisplayName, oldListPrice.ToString(), newListPrice.ToString()));

                        // Set new price on line item.
                        lineItem.ListPrice = newListPrice.Value.Amount;
                        if (lineItem.Parent.Parent.ProviderId.ToLower().Equals("frontend"))
                        {
                            lineItem.PlacedPrice = newListPrice.Value.Amount;
                        }
                    }
                }
            }
        }
コード例 #12
0
        public virtual async Task <Money> GetShoppingCartPaymentFeeAsync(IList <OrganizedShoppingCartItem> cart, decimal fixedFeeOrPercentage, bool usePercentage)
        {
            Guard.NotNull(cart, nameof(cart));

            var paymentFee = decimal.Zero;

            if (fixedFeeOrPercentage != decimal.Zero)
            {
                if (usePercentage)
                {
                    // Percentage.
                    Money?orderTotalWithoutPaymentFee = await GetShoppingCartTotalAsync(cart, includePaymentAdditionalFee : false);

                    if (orderTotalWithoutPaymentFee.HasValue)
                    {
                        paymentFee = orderTotalWithoutPaymentFee.Value.Amount * fixedFeeOrPercentage / 100m;
                    }
                }
                else
                {
                    // Fixed fee value.
                    paymentFee = fixedFeeOrPercentage;
                }
            }

            return(_primaryCurrency.AsMoney(paymentFee, false));
        }
コード例 #13
0
        public void MoneyExplicitConversion_Null_Null()
        {
            MonetaryQuantity @null = null;
            Money?           money = (Money?)@null;

            Assert.That(money, Is.Null);
        }
コード例 #14
0
        public void CustomDefaultConverter_NullDefaultContractResolver_Null()
        {
            Money? @null = default(Money?);

            string actual = JsonConvert.SerializeObject(@null, new DefaultNullableMoneyConverter());

            Assert.That(actual, Is.EqualTo("null"));
        }
コード例 #15
0
        public void TryConvert_To_Currency_DefaultConversion()
        {
            Money?thirteenEuro = 13m.Usd().TryConvert().To(Currency.Euro);

            Assert.That(thirteenEuro.HasValue, Is.True);
            Assert.That(thirteenEuro.GetValueOrDefault().Amount, Is.EqualTo(13m), "the default exchange provider merely changes the currency");
            Assert.That(thirteenEuro.GetValueOrDefault().CurrencyCode, Is.EqualTo(CurrencyIsoCode.EUR));
        }
コード例 #16
0
        public void TryConvert_To_Currency_DoubledConversion()
        {
            Money?oewMeThirteenEuro = 13m.Usd().TryConvert().To(Currency.Euro);

            Assert.That(oewMeThirteenEuro.HasValue, Is.True);
            Assert.That(oewMeThirteenEuro.GetValueOrDefault().Amount, Is.EqualTo(26m), "the rate of two exchange provider multiplies the amount by two and changes the currency");
            Assert.That(oewMeThirteenEuro.GetValueOrDefault().CurrencyCode, Is.EqualTo(CurrencyIsoCode.EUR));
        }
コード例 #17
0
 public RevenueMoney(bool hadMissingMarketData,
                     Money?money,
                     HighProfitComponents components)
 {
     this.HadMissingMarketData = hadMissingMarketData;
     this.Money      = money;
     this.Components = components;
 }
コード例 #18
0
        public void MoneyExplicitConversion_NullCurrency_MissingCurrency()
        {
            MonetaryQuantity noCurrency = new MonetaryQuantity(12, null);
            Money?           money      = (Money?)noCurrency;

            Assert.That(money.HasValue, Is.True);
            Assert.That(money.Value.CurrencyCode, Is.EqualTo(CurrencyIsoCode.XXX));
        }
コード例 #19
0
ファイル: Json_NET.cs プロジェクト: shadowca/nmoneys
        internal static object AdaptNullables(Type objectType, Money?money)
        {
            // if nullable, whatever is in money will do
            // it not nullable, we better not return null
            object read = objectType == typeof(Money?) ? money : money.GetValueOrDefault();

            return(read);
        }
コード例 #20
0
        public void CustomCanonicalConverter_NullDefaultContractResolver_UsesPascalCasedPropertyNamesAndAlphabeticCode()
        {
            Money? @null = default(Money?);

            string actual = JsonConvert.SerializeObject(@null, new CanonicalNullableMoneyConverter());

            Assert.That(actual, Is.EqualTo("null"));
        }
コード例 #21
0
        public void ToMoney_NullCurrency_MissingCurrency()
        {
            MonetaryQuantity noCurrency = new MonetaryQuantity(12, null);
            Money?           money      = MonetaryQuantity.ToMoney(noCurrency);

            Assert.That(money.HasValue, Is.True);
            Assert.That(money.Value.CurrencyCode, Is.EqualTo(CurrencyIsoCode.XXX));
        }
コード例 #22
0
        /// <summary>
        /// Pre processes item record adding additional LineItems if needed.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="record">The record.</param>
        private void PreProcessItemRecord(OrderGroup order, PromotionItemRecord record)
        {
            // We do special logic for the gift promotion reward
            if (record.PromotionReward is GiftPromotionReward)
            {
                // Check if item already in the cart, if not add
                if (((GiftPromotionReward)record.PromotionReward).AddStrategy == GiftPromotionReward.Strategy.AddWhenNeeded)
                {
                    // We assume that all affected entries are the gifts that need to be added to the cart
                    foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
                    {
                        LineItem giftLineItem = FindGiftLineItemInOrder(order, entry.CatalogEntryCode, record);

                        if (!IsOrderHaveSpecifiedGiftPromotion(order, record))
                        {
                            // Didn't find, add it
                            if (giftLineItem == null)
                            {
                                // we should some kind of delegate or common implementation here so we can use the same function in both discount and front end
                                CatalogEntryResponseGroup responseGroup = new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Variations);
                                Entry catEntry = CatalogContext.Current.GetCatalogEntry(entry.CatalogEntryCode, responseGroup);
                                giftLineItem = AddNewGiftLineItemToOrder(order, catEntry, entry.Quantity);
                                AddGiftItemToAShipment(giftLineItem, giftLineItem.Parent.LineItems.Count - 1);
                                CatalogEntryDto entryDto = CatalogContext.Current.GetCatalogEntryDto(giftLineItem.Code, responseGroup);
                                CatalogEntryDto.CatalogEntryRow entryRow = entryDto.CatalogEntry[0];
                                Money?price = GetItemPrice(entryRow, giftLineItem, CustomerContext.Current.CurrentContact);
                                giftLineItem.ListPrice   = price.HasValue ? price.Value.Amount : 0m;
                                giftLineItem.PlacedPrice = giftLineItem.ListPrice;
                                // populate inventory information for giftLineItem
                                var aggregateInventory = ServiceLocator.Current.GetInstance <IInventoryService>().QueryByEntry(new [] { entryRow.Code });
                                foreach (var inventoryRecord in aggregateInventory)
                                {
                                    PopulateInventoryInfo(inventoryRecord, giftLineItem);
                                }
                            }
                            else
                            {
                                giftLineItem.Quantity = Math.Max(entry.Quantity, giftLineItem.Quantity);

                                var index = giftLineItem.Parent.LineItems.IndexOf(giftLineItem);

                                if (!giftLineItem.Parent.Shipments.SelectMany(x => x.LineItemIndexes).Contains(index.ToString()))
                                {
                                    AddGiftItemToAShipment(giftLineItem, index);
                                }
                            }
                        }
                        else
                        {
                            entry.Quantity = giftLineItem != null?Math.Min(entry.Quantity, giftLineItem.Quantity) : entry.Quantity;
                        }
                        entry.Owner        = giftLineItem;
                        entry.CostPerEntry = giftLineItem != null ? giftLineItem.ListPrice : 0m;
                    }
                }
            }
        }
コード例 #23
0
 public FakeProperty(int locationIndex = 0, IPlayer owner = null, Money?cost = null, Money?rent = null, bool isMortgaged = false)
 {
     LocationIndex = locationIndex;
     Owner         = owner;
     Cost          = cost ?? new Money(0);
     Rent          = rent ?? new Money(0);
     LandedPlayers = new List <string>();
     IsMortgaged   = isMortgaged;
 }
コード例 #24
0
ファイル: MoneyRequest.cs プロジェクト: yahiheb/WalletWasabi
 private MoneyRequest(Money?amount, MoneyRequestType type, bool subtractFee)
 {
     if (type is MoneyRequestType.AllRemaining or MoneyRequestType.Change)
     {
         if (amount is not null)
         {
             throw new ArgumentException("Must be null.", nameof(amount));
         }
     }
コード例 #25
0
 public void BuySnack()
 {
     if (MoneyInside == null || MoneyInTransaction == null)
     {
         return;
     }
     MoneyInside       += MoneyInTransaction;
     MoneyInTransaction = Money.None;
 }
コード例 #26
0
        public void Serialization_DefaultNull_Null()
        {
            Money? @null = default(Money?);

            _proxy.Serializer = new DefaultMoneySerializer();

            string actual = @null.ToJson();

            Assert.That(actual, Is.EqualTo("null"));
        }
コード例 #27
0
        public void Serialization_CanonicalNullInstance_Null()
        {
            Money? @null = default(Money?);

            _proxy.Serializer = new CanonicalMoneySerializer();

            string actual = @null.ToJson();

            Assert.That(actual, Is.EqualTo("null"));
        }
コード例 #28
0
        public void ExplicitConversion_NotNull_InstanceWithMoneyValues()
        {
            Money?           notNull  = 42.74m.Eur();
            MonetaryQuantity quantity = (MonetaryQuantity)notNull;

            Assert.That(quantity, Is.Not.Null);

            Assert.That(quantity, Must.Have.Property <MonetaryQuantity>(q => q.Amount, Is.EqualTo(42.74m)) &
                        Must.Have.Property <MonetaryQuantity>(q => q.Currency, Is.EqualTo(CurrencyIsoCode.EUR.AlphabeticCode())));
        }
コード例 #29
0
        public void CustomDefaultConverter_NullNumericStyle_UsesNumericCode()
        {
            Money? @null = default(Money?);

            using (new NullableConfigScope(DefaultNullableMoneySerializer.Numeric.Serialize))
            {
                string actual = JsonSerializer.SerializeToString(@null);
                Assert.That(actual, Is.Null);
            }
        }
コード例 #30
0
        public void CustomDefaultConverter_NullCamelCasing_UsesCamelCasedPropertyNamesAndAlphabeticCode()
        {
            Money? @null = default(Money?);

            using (new NullableConfigScope(DefaultNullableMoneySerializer.Serialize, JsConfig.With(emitCamelCaseNames: true)))
            {
                string actual = JsonSerializer.SerializeToString(@null);
                Assert.That(actual, Is.Null);
            }
        }