Ejemplo n.º 1
0
		private static string BuildMessage(string message, IMoney missing)
		{
			StringBuilder builder = new StringBuilder();
			builder.Append(message);
			if(missing != null)
				builder.Append(" with missing amount " + missing);
			return builder.ToString();
		}
Ejemplo n.º 2
0
        public IMoney Add(IMoney Add)
        {
            if (m_oCurrencyCode != Add.CurrencyCode)
            {
                throw new Exception("Can't add two money objects with different currency");
            }

            if (Add.Amount.Equals(0))
            {
                return(this);
            }

            return(GetMoney(m_oAmount + Add.Amount, m_oCurrencyCode));
        }
Ejemplo n.º 3
0
        bool IMoney.IsCompatible(IMoney money)
        {
            if (money == null)
            {
                throw new ArgumentNullException("money");
            }
            AssetMoney assetMoney = money as AssetMoney;

            if (assetMoney == null)
            {
                return(false);
            }
            return(assetMoney.Id == Id);
        }
        /// <summary>
        /// 文字型をお金クラスに変換
        /// </summary>
        /// <param name="str"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public bool TryToMoney(string str, out IMoney money)
        {
            money = null;

            //数値型に変換可能か
            int moneyNum;

            if (int.TryParse(str, out moneyNum) == false)
            {
                return(false);
            }

            //お金クラスに変換可能か
            return(TryToMoney(moneyNum, out money));
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            MoneyBag bag    = new MoneyBag();
            Money    moneyA = new Money(10, "EUR");
            Money    moneyB = new Money(20, "USD");
            Money    moneyC = new Money(15, "EUR");
            Money    moneyD = new Money(25, "JPY");
            IMoney   money  = bag.AddMoney(moneyA);

            money = money.AddMoney(moneyB);
            money = money.AddMoney(moneyC);
            money = money.AddMoney(moneyD);
            Console.WriteLine("My Portfolio : " + money.ToString());
            Console.ReadLine();
        }
Ejemplo n.º 6
0
        private IMoney GetRevenueFromHoldingSell(int Quantity, string Ticker)
        {
            IMoney GAA = GetGAAFromHolding(Quantity, Ticker);

            if (GAA == null)
            {
                throw new Exception("Not possible, not enough number of stocks");
            }


            //calculate revenue from the current ticker
            Quote HoldingQuote = ImperaturGlobal.Quotes.Where(q => q.Symbol.Equals(Ticker)).First();

            return(HoldingQuote.LastTradePrice.Multiply(Quantity).Subtract(GAA.Multiply(Quantity)));
        }
Ejemplo n.º 7
0
 public Transaction(IMoney _DebitAmount, IMoney _CreditAmount, Guid _DebitAccount, Guid _CreditAccount, TransactionType _TransactionType, ITradeInterface _SecurtiesTrade, DateTime _TransactionDate, string _ProcessCode = "Manual")
 {
     this._DebitAmount     = _DebitAmount;
     this._CreditAmount    = _CreditAmount;
     this._DebitAccount    = _DebitAccount;
     this._CreditAccount   = _CreditAccount;
     this._TransactionType = _TransactionType;
     this._SecuritiesTrade = _SecurtiesTrade;
     this._TransactionDate = _TransactionDate;
     this._ProcessCode     = _ProcessCode;
     if (!_DebitAmount.Amount.Equals(_CreditAmount.Amount))
     {
         throw new Exception("Amount is not equal");
     }
 }
        /// <summary>
        /// int型をお金クラスに変換
        /// </summary>
        /// <param name="num"></param>
        /// <param name="moneyType"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        private bool ConvertMoney(int num, Type moneyType, out IMoney money)
        {
            money = null;

            //お金タイプをインスタンス化して値を比較
            var sampleMoney = (IMoney)Activator.CreateInstance(moneyType);

            if (sampleMoney.GetPrice() == num)
            {
                money = sampleMoney;
                return(true);
            }

            return(false);
        }
        /// <summary>
        /// int型をお金クラスに変換
        /// </summary>
        /// <param name="num"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public bool TryToMoney(int num, out IMoney money)
        {
            money = null;

            //対応しているお金の一覧を取得
            var supportMoneyList = GetSupportedMoneyList();

            //数値をお金に変換できたら成功
            foreach (var moneyType in supportMoneyList)
            {
                bool isSuccess = ConvertMoney(num, moneyType, out IMoney temp);
                money = isSuccess ? temp : money;
            }

            return(money != null);
        }
Ejemplo n.º 10
0
 public static string PrintFormattedMoney(IMoney money)
 {
     if (money is Coin)
     {
         var coin = money as Coin;
         return($"Coin: ${coin.Value} (Size: {coin.Size.ToString()})");
     }
     else if (money is Note)
     {
         return($"Note: ${money.Value}");
     }
     else
     {
         return(string.Empty);
     }
 }
Ejemplo n.º 11
0
        private IMoney SelectAmount(IMoney zero, BalanceSummaryDetails balanceSummaryDetails)
        {
            var cc = zero as AssetMoney;

            if (cc == null)
            {
                return(balanceSummaryDetails.Amount);
            }
            var assetDetails = balanceSummaryDetails.Assets.FirstOrDefault(a => a.Asset.AssetId == cc.Id);

            if (assetDetails == null)
            {
                return(zero);
            }
            return(new AssetMoney(assetDetails.Asset, assetDetails.Quantity));
        }
Ejemplo n.º 12
0
 public bool Equals(IMoney other)
 {
     if (object.ReferenceEquals(other, null))
     {
         return(false);
     }
     if (AllowImplicitConversion)
     {
         return(Amount == other.Convert(currencyCode).Amount &&
                other.Amount == Convert(other.CurrencyCodes).Amount);
     }
     else
     {
         return((CurrencySymbol == other.CurrencySymbol) && (Amount == other.Amount));
     }
 }
Ejemplo n.º 13
0
        public bool TryConvert(MoneyModel o, out IMoney result)
        {
            result = null;

            if (o == null)
            {
                return(false);
            }

            result = new Money
            {
                Amount     = o.Amount,
                CurrencyId = o.CurrencyId
            };

            return(true);
        }
Ejemplo n.º 14
0
        public void AssertTotal(IDestination dest, IMoney total)
        {
            var zero    = total.Sub(total);
            var address = dest.ScriptPubKey.GetDestinationAddress(Network).ToColoredAddress();
            var summary = SendGet <BalanceSummary>("balances/" + address + "/summary");

            Assert.Equal(total, SelectAmount(zero, summary.UnConfirmed).Add(SelectAmount(zero, summary.Confirmed)).Add(SelectAmount(zero, summary.Immature)));

            var balances = SendGet <BalanceModel>("balances/" + address);
            var actual   = balances.Operations.SelectMany(o => o.ReceivedCoins).Select(c => SelectAmount(zero, c))
                           .Sum(zero)
                           .Sub(
                balances.Operations.SelectMany(o => o.SpentCoins).Select(c => SelectAmount(zero, c))
                .Sum(zero));

            Assert.Equal(total, actual);
        }
Ejemplo n.º 15
0
        public void TestMoneyCalculatorMaxReturnsValueWhenOneMoneySubmitted()
        {
            //Arrange
            IMoney expectedMoney = new Money {
                Amount = 20, Currency = "GBP"
            };

            IMoney[] monies =
            {
                expectedMoney
            };

            //Act
            IMoney returnedMoney = _moneyCalculator.Max(monies);

            //Assert
            Assert.AreEqual(expectedMoney, returnedMoney);
        }
Ejemplo n.º 16
0
        public static IMoney Sum(this IEnumerable <IMoney> moneys, IMoney zero)
        {
            if (moneys == null)
            {
                throw new ArgumentNullException(nameof(moneys));
            }
            if (zero == null)
            {
                throw new ArgumentNullException(nameof(zero));
            }
            IMoney result = zero;

            foreach (var money in moneys)
            {
                result = result.Add(money);
            }
            return(result);
        }
Ejemplo n.º 17
0
        private void AppendMoney(Money aMoney)
        {
            IMoney old = FindMoney(aMoney.Currency);

            if (old == null)
            {
                fMonies.Add(aMoney);
                return;
            }
            fMonies.Remove(old);
            IMoney sum = old.Add(aMoney);

            if (sum.IsZero)
            {
                return;
            }
            fMonies.Add(sum);
        }
Ejemplo n.º 18
0
        public static IDiscount Create(IMarketingCampaign campaign, IMoney money)
        {
            if (campaign.IsCrazySalesDay())
            {
                return(new DiscountCrazySalesDay());
            }

            if (money.IsMoreThanOneThousand())
            {
                return(new DiscountOneThousand());
            }

            if (money.IsMoreThanOneHundred() && campaign.IsActive())
            {
                return(new DiscountOneHundred());
            }

            return(new DiscountNoDiscount());
        }
Ejemplo n.º 19
0
        private void button_search_Click(object sender, EventArgs e)
        {
            if (this.textBox_Search.Text.Trim() == "")
            {
                return;
            }

            if (listView_searchresult.Items.Count > 0)
            {
                listView_searchresult.Items.Clear();
            }

            //populate the account list

            foreach (IAccountInterface oA in m_oAh.SearchAccount(this.textBox_Search.Text.Trim(), AccountType.Customer))
            {
                List <ICurrency> FilterCurrency = new List <ICurrency>();
                FilterCurrency.Add(ImperaturGlobal.GetSystemCurrency());

                IMoney AvailableSystemAmount = oA.GetAvailableFunds(FilterCurrency).First();
                IMoney TotalFunds            = oA.GetTotalFunds(FilterCurrency).First();
                IMoney TotalDeposit          = oA.GetDepositedAmount(FilterCurrency).First();

                //row["Change"] = oM.Subtract(TotalDeposit.Where(od => od.CurrencyCode.Equals(oM.CurrencyCode)).First()).ToString();
                //row["ChangePercent"] = string.Format("{0}%", TotalDeposit.Where(od => od.CurrencyCode.Equals(oM.CurrencyCode)).First().Amount > 0 ? oM.Subtract(TotalDeposit.Where(od => od.CurrencyCode.Equals(oM.CurrencyCode)).First().Amount).Divide(TotalDeposit.Where(od => od.CurrencyCode.Equals(oM.CurrencyCode)).First().Amount).Multiply(100).ToString(true, false) : "0");


                ListViewItem oSearchResultRow = new ListViewItem(
                    new string[]
                {
                    oA.GetCustomer().FullName,
                    AvailableSystemAmount.ToString(false, false),
                    TotalFunds.ToString(false, false),
                    TotalFunds.Subtract(TotalDeposit).ToString(false, false),
                    string.Format("{0}%", TotalDeposit.Amount > 0 ? TotalFunds.Subtract(TotalDeposit.Amount).Divide(TotalDeposit.Amount).Multiply(100).ToString(true, false) : "0"),
                }
                    );
                oSearchResultRow.Tag = oA.Identifier.ToString();
                listView_searchresult.Items.Add(oSearchResultRow);
            }
            listView_searchresult.Refresh();
        }
Ejemplo n.º 20
0
        public ITradeInterface GetTrade(string Symbol, decimal Quantity, DateTime TradeDateTime, IMoney Revenue)
        {
            Quote    oHoldingTicker = GetQuote(Symbol);
            IMoney   TradeAmount    = oHoldingTicker.LastTradePrice.Multiply(Quantity);
            Security NewSecurity    = new Security()
            {
                Price  = oHoldingTicker.LastTradePrice,
                Symbol = Symbol
            };

            ITradeInterface oNewTrade = ImperaturGlobal.Kernel.Get <ITradeInterface>(
                new Ninject.Parameters.ConstructorArgument("m_oQuantity", Quantity),
                new Ninject.Parameters.ConstructorArgument("m_oSecurity", NewSecurity),
                new Ninject.Parameters.ConstructorArgument("m_oTradeAmount", TradeAmount),
                new Ninject.Parameters.ConstructorArgument("m_oTradeDateTime", TradeDateTime),
                new Ninject.Parameters.ConstructorArgument("m_oRevenue", Revenue)
                );

            return(oNewTrade);
        }
Ejemplo n.º 21
0
        static (IMoney final, Amount added) Add(IMoney money, Amount amount, DateTime at)
        {
            switch (money)
            {
            case Cash cash when amount.Currency == cash.Currency:
                return(new Cash(cash.Value + amount.Value, cash.Currency), amount);

            case Cash _:
                return(money, new Amount(0, amount.Currency));

            case Gift gift when at < gift.ValidBefore && gift.Currency == amount.Currency:
                return(new Gift(gift.Value + amount.Value, gift.Currency, gift.ValidBefore), amount);

            case Gift _:
                return(money, new Amount(0, amount.Currency));

            default:
                throw new ArgumentException();
            }
        }
Ejemplo n.º 22
0
        static void Main(string[] args)

        {
            const int ONE_MILLION = 10000; // <--- Suppose this is one million :)

            int[] currencyDenominations = new[] { 1, 5, 10, 20, 50, 100 };

            MoneyFactory moneyFactory = new MoneyFactory();

            int sum = 0;

            while (sum <= ONE_MILLION)

            {
                IMoney graphicalMoneyObj = null;

                Random rand = new Random();

                int currencyDisplayValue = currencyDenominations[rand.Next(0, currencyDenominations

                                                                           .Length)];

                if (currencyDisplayValue == 1 || currencyDisplayValue == 5)
                {
                    graphicalMoneyObj = moneyFactory.GetMoneyToDisplay(EnMoneyType.Metallic);
                }

                else
                {
                    graphicalMoneyObj = moneyFactory.GetMoneyToDisplay(EnMoneyType.Paper);
                }

                graphicalMoneyObj.GetDisplayOfMoneyFalling(currencyDisplayValue);

                sum = sum + currencyDisplayValue;
            }

            Console.WriteLine("Total Objects created=" + MoneyFactory.ObjectsCount.ToString());

            Console.ReadLine();
        }
Ejemplo n.º 23
0
        public static (Amount subtracted, IMoney remaining) Subtract(
            this IMoney from, Amount amount)
        {
            switch (from)
            {
            case Cash cash:
                return(new Amount(cash.Value, cash.Currency)
                       .Subtract(amount)
                       .Map(pair => (pair.subtracted, new Cash(pair.final.Value, pair.final.Currency))));

            case Gift gift:
                return(gift.Value
                       .Subtract(amount)
                       .Map(pair => (pair.subtracted, new Gift(pair.final, gift.ValidBefore))));

            case BankCard card:
                return(amount, card);

            default: throw new ArgumentException("Unsupported money type.");
            }
        }
Ejemplo n.º 24
0
        public static decimal GetValue(this IMoney m, BTCPayNetwork network = null)
        {
            switch (m)
            {
            case Money money:
                return(money.ToDecimal(MoneyUnit.BTC));

//                case MoneyBag mb:
//                    return mb.Select(money => money.GetValue(network)).Sum();
//                case AssetMoney assetMoney:
//                    if (network is ElementsBTCPayNetwork elementsBTCPayNetwork)
//                    {
//                        return elementsBTCPayNetwork.AssetId == assetMoney.AssetId
//                            ? new Money(assetMoney.Quantity)
//                            : Money.Zero;
//                    }
//                    throw new NotSupportedException("IMoney type not supported");
            default:
                throw new NotSupportedException("IMoney type not supported");
            }
        }
Ejemplo n.º 25
0
        public static decimal GetValue(this IMoney m, uint256 assetId = null)
        {
            switch (m)
            {
            case Money money:
                return(money.ToDecimal(MoneyUnit.BTC));

            case MoneyBag mb:
                return(mb.Select(money => money.GetValue(assetId)).Sum());

            case AssetMoney assetMoney:
                return(assetId == assetMoney.AssetId
                        ? Convert(assetMoney.Quantity)
                        : 0);

                throw new NotSupportedException("IMoney type not supported");

            default:
                throw new NotSupportedException("IMoney type not supported");
            }
        }
Ejemplo n.º 26
0
        public IEnumerable <ICoin> Select(IEnumerable <ICoin> coins, IMoney target)
        {
            var targetMoney = target as Money;

            var available = UnspentCoins.Sum(x => x.Amount);

            if (available < targetMoney)
            {
                throw new InsufficientBalanceException(targetMoney, available);
            }

            // Group coins by scriptPubKey in order to treat them all as one.
            var coinsByScriptPubKey = UnspentCoins
                                      .GroupBy(c => c.ScriptPubKey)
                                      .Select(group => new
            {
                Coins        = group,
                Unconfirmed  = group.Any(x => !x.Confirmed),                           // If group has an unconfirmed, then the whole group is unconfirmed.
                AnonymitySet = group.Min(x => x.AnonymitySet),                         // The group is as anonymous as its weakest member.
                Amount       = group.Sum(x => x.Amount)
            });

            var coinsToSpend = new List <SmartCoin>();

            foreach (IGrouping <Script, SmartCoin> coinsGroup in coinsByScriptPubKey
                     .OrderBy(group => group.Unconfirmed)
                     .ThenByDescending(group => group.AnonymitySet)                // Always try to spend/merge the largest anonset coins first.
                     .ThenByDescending(group => group.Amount)                      // Then always try to spend by amount.
                     .Select(group => group.Coins))
            {
                coinsToSpend.AddRange(coinsGroup);

                if (coinsToSpend.Sum(x => x.Amount) >= targetMoney)
                {
                    break;
                }
            }

            return(coinsToSpend.Select(c => c.GetCoin()));
        }
Ejemplo n.º 27
0
        public void MobileObject_Die()
        {
            EquipedEquipment(mob).Add(armor.Object);
            mob.Money = 10;
            mob.Enchantments.Add(enchantment.Object);

            ICorpse corpse = mob.Die(attacker.Object);

            Assert.IsFalse(mob.IsAlive);
            Assert.AreEqual("A corpse lies here.", corpse.ShortDescription);
            Assert.AreEqual("This corpse once was living but no life exists here now.", corpse.LookDescription);
            Assert.AreEqual("This corpse once was living but no life exists here now.", corpse.ExamineDescription);
            Assert.IsTrue(corpse.KeyWords.Contains("Corpse"));
            Assert.AreEqual("corpse", corpse.SentenceDescription);
            Assert.AreEqual(3, corpse.Items.Count);
            Assert.IsTrue(corpse.Items.Contains(item.Object));
            Assert.IsTrue(corpse.Items.Contains(armor.Object));
            Assert.AreSame(attacker.Object, corpse.Killer);

            IMoney corpseMoney = null;

            foreach (IItem localItem in corpse.Items)
            {
                IMoney money = (localItem as IMoney);
                if (money != null)
                {
                    corpseMoney = money;
                    break;
                }
            }

            Assert.AreEqual(10ul, corpseMoney.Value);
            Assert.AreEqual(0, mob.Items.Count);
            Assert.AreEqual(0, mob.EquipedEquipment.Count());
            Assert.AreEqual(0ul, mob.Money);
            Assert.IsTrue(corpse.Items.Contains(item.Object));
            evnt.Verify(e => e.OnDeath(mob), Times.Once);
            enchantment.VerifySet(e => e.EnchantmentEndingDateTime = new DateTime());
        }
Ejemplo n.º 28
0
        public static decimal GetValue(this IMoney m, BTCPayNetwork network = null)
        {
            switch (m)
            {
            case Money money:
                return(money.ToDecimal(MoneyUnit.BTC));

            case MoneyBag mb:
                return(mb.Select(money => money.GetValue(network)).Sum());

            case AssetMoney assetMoney:
                if (network is ElementsBTCPayNetwork elementsBTCPayNetwork)
                {
                    return(elementsBTCPayNetwork.AssetId == assetMoney.AssetId
                            ? Convert(assetMoney.Quantity, elementsBTCPayNetwork.Divisibility)
                            : 0);
                }
                throw new NotSupportedException("IMoney type not supported");

            default:
                throw new NotSupportedException("IMoney type not supported");
            }
        }
Ejemplo n.º 29
0
        public IMoney ConvertToLocal(IMoney originalMoney)
        {
            if (originalMoney == null)
            {
                return(null);
            }
            if (originalMoney.Currency == this.internalCurrency)
            {
                return(originalMoney);
            }

            var exchangeRate = this.stocks.GetExchangeRate(originalMoney.Currency.AlphabeticCode, this.internalCurrency.AlphabeticCode);

            if (exchangeRate == null)
            {
                throw new InvalidOperationException(
                          "Missing exchange rate for '" + originalMoney.Currency.AlphabeticCode + "' to '" + this.internalCurrency.AlphabeticCode + "'");
            }

            var newValue = originalMoney.Amount * exchangeRate.ConversionRate;

            return(this.InternalMoney(newValue));
        }
Ejemplo n.º 30
0
        public bool AddTransaction(ITransactionInterface oTrans)
        {
            /*make sure the transaction is allowed
             * if withdrawal/transfer from customers account, the amount of availble funds must cover the amount of the transaction
             * if puchase of securites, the amount of availble funds must cover the amount of the transaction
             */
            try
            {
                List <IMoney> AvailableFunds         = GetAvailableFunds().Where(t => t.CurrencyCode.Equals(oTrans.DebitAmount.CurrencyCode)).ToList();
                IMoney        AvailableFundsCurrency = ImperaturGlobal.GetMoney(0m, oTrans.CreditAmount.CurrencyCode);

                if (AvailableFunds.Where(a => a.CurrencyCode.Equals(oTrans.CreditAmount.CurrencyCode)).Count() > 0)
                {
                    AvailableFundsCurrency = AvailableFunds.Where(a => a.CurrencyCode.Equals(oTrans.CreditAmount.CurrencyCode)).First();
                }

                if ((oTrans.TransactionType == TransactionType.Withdrawal || oTrans.TransactionType == TransactionType.Transfer || oTrans.TransactionType == TransactionType.Buy)
                    &&
                    oTrans.DebitAccount == this.Identifier
                    &&
                    oTrans.DebitAmount.Amount > AvailableFundsCurrency.Amount
                    )
                {
                    //abort transaction
                    LastErrorMessage = "Not enough available funds to cover this transaction!";
                    throw new Exception("Not enough available funds to cover this transaction!");
                }

                m_oTransactions.Add(oTrans);
            }
            catch (Exception ex)
            {
                ImperaturGlobal.GetLog().Error(string.Format("[Account.AddTransaction] Couldn't create transaction on account {0}", this.Identifier), ex);
                LastErrorMessage = ex.Message;
            }
            return(true);
        }
Ejemplo n.º 31
0
        public bool DepositAmount(Guid Identifier, IMoney Deposit)
        {
            IAccountInterface oA = m_oAccounts.Single(a => a.Identifier.Equals(Identifier));

            try
            {
                oA.AddTransaction(
                    ImperaturGlobal.Kernel.Get <ITransactionInterface>(
                        new Ninject.Parameters.ConstructorArgument("_DebitAmount", Deposit),
                        new Ninject.Parameters.ConstructorArgument("_CreditAmount", Deposit),
                        new Ninject.Parameters.ConstructorArgument("_DebitAccount", oA.GetBankAccountsFromCache().First()),
                        new Ninject.Parameters.ConstructorArgument("_CreditAccount", oA.Identifier),
                        new Ninject.Parameters.ConstructorArgument("_TransactionType", TransactionType.Transfer),
                        new Ninject.Parameters.ConstructorArgument("_SecurtiesTrade", (object)null)
                        )
                    );
            }
            catch (Exception ex)
            {
                LastErrorMessage = ex.Message;
                return(false);
            }
            return(true);
        }
 public RandomChangeStrategy(IMoney money, ICurrencyRandomizer randomizer)
 {
     _money = money;
     _randomizer = randomizer;
 }
Ejemplo n.º 33
0
		private IEnumerable<ICoin> BuildTransaction(
			TransactionBuildingContext ctx,
			BuilderGroup group,
			IEnumerable<Builder> builders,
			IEnumerable<ICoin> coins,
			IMoney zero)
		{
			var originalCtx = ctx.CreateMemento();
			var target = builders.Concat(ctx.AdditionalBuilders).Select(b => b(ctx)).Sum(zero);
			if(ctx.CoverOnly != null)
			{
				target = ctx.CoverOnly.Add(ctx.ChangeAmount);
			}

			var unconsumed = coins.Where(c => ctx.ConsumedCoins.All(cc => cc.Outpoint != c.Outpoint));
			var selection = CoinSelector.Select(unconsumed, target);
			if(selection == null)
				throw new NotEnoughFundsException("Not enough fund to cover the target",
					group.Name,
					target.Sub(unconsumed.Select(u => u.Amount).Sum(zero))
					);
			var total = selection.Select(s => s.Amount).Sum(zero);
			var change = total.Sub(target);
			if(change.CompareTo(zero) == -1)
				throw new NotEnoughFundsException("Not enough fund to cover the target",
					group.Name,
					change.Negate()
				);
			if(change.CompareTo(ctx.Dust) == 1)
			{
				var changeScript = group.ChangeScript[(int)ctx.ChangeType];
				if(changeScript == null)
					throw new InvalidOperationException("A change address should be specified (" + ctx.ChangeType + ")");
				if(!(ctx.Dust is Money) || change.CompareTo(GetDust(changeScript)) == 1)
				{
					ctx.RestoreMemento(originalCtx);
					ctx.ChangeAmount = change;
					try
					{
						return BuildTransaction(ctx, group, builders, coins, zero);
					}
					finally
					{
						ctx.ChangeAmount = zero;
					}
				}
			}
			foreach(var coin in selection)
			{
				ctx.ConsumedCoins.Add(coin);
				var input = ctx.Transaction.Inputs.FirstOrDefault(i => i.PrevOut == coin.Outpoint);
				if(input == null)
					input = ctx.Transaction.AddInput(new TxIn(coin.Outpoint));
				if(_LockTime != null && !ctx.NonFinalSequenceSet)
				{
					input.Sequence = 0;
					ctx.NonFinalSequenceSet = true;
				}
			}
			return selection;
		}
Ejemplo n.º 34
0
 public LeatherWallet(IMoney money)
 {
     _money = money;
 }
Ejemplo n.º 35
0
 /// <summary>Adds a money to this money. Forwards the request to
 /// the AddMoney helper.</summary>
 public IMoney Add(IMoney m)
 {
     return m.AddMoney(this);
 }
Ejemplo n.º 36
0
 public IMoney Subtract(IMoney m)
 {
     return Add(m.Negate());
 }
Ejemplo n.º 37
0
		/// <summary>
		/// Send a money amount to the destination
		/// </summary>
		/// <param name="destination">The destination</param>
		/// <param name="amount">The amount (supported : Money, AssetMoney, MoneyBag)</param>
		/// <returns></returns>
		/// <exception cref="System.NotSupportedException">The coin type is not supported</exception>
		public TransactionBuilder Send(Script scriptPubKey, IMoney amount)
		{
			MoneyBag bag = amount as MoneyBag;
			if(bag != null)
			{
				foreach(var money in bag)
					Send(scriptPubKey, amount);
				return this;
			}
			Money coinAmount = amount as Money;
			if(coinAmount != null)
				return Send(scriptPubKey, coinAmount);
			AssetMoney assetAmount = amount as AssetMoney;
			if(assetAmount != null)
				return SendAsset(scriptPubKey, assetAmount);
			throw new NotSupportedException("Type of Money not supported");
		}
Ejemplo n.º 38
0
		/// <summary>
		/// Send a money amount to the destination
		/// </summary>
		/// <param name="destination">The destination</param>
		/// <param name="amount">The amount (supported : Money, AssetMoney, MoneyBag)</param>
		/// <returns></returns>
		/// <exception cref="System.NotSupportedException">The coin type is not supported</exception>
		public TransactionBuilder Send(IDestination destination, IMoney amount)
		{
			return Send(destination.ScriptPubKey, amount);
		}
Ejemplo n.º 39
0
		public NotEnoughFundsPolicyError(string message, IMoney missing)
			: base(BuildMessage(message, missing))
		{
			Missing = missing;
		}
 public MinimalChangeStrategy(IMoney money)
 {
     _money = money;
 }
Ejemplo n.º 41
0
 public BlueWallet(IMoney money)
 {
     _money = money;
 }
Ejemplo n.º 42
0
		public IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target)
		{
			var zero = target.Sub(target);
			var targetCoin = coins
							.FirstOrDefault(c => c.Amount.CompareTo(target) == 0);
			//If any of your UTXO² matches the Target¹ it will be used.
			if(targetCoin != null)
				return new[] { targetCoin };

			List<ICoin> result = new List<ICoin>();
			IMoney total = zero;

			if(target.CompareTo(zero) == 0)
				return result;

			var orderedCoins = coins.OrderBy(s => s.Amount).ToArray();

			foreach(var coin in orderedCoins)
			{
				if(coin.Amount.CompareTo(target) == -1 && total.CompareTo(target) == -1)
				{
					total = total.Add(coin.Amount);
					result.Add(coin);
					//If the "sum of all your UTXO smaller than the Target" happens to match the Target, they will be used. (This is the case if you sweep a complete wallet.)
					if(total.CompareTo(target) == 0)
						return result;

				}
				else
				{
					if(total.CompareTo(target) == -1 && coin.Amount.CompareTo(target) == 1)
					{
						//If the "sum of all your UTXO smaller than the Target" doesn't surpass the target, the smallest UTXO greater than your Target will be used.
						return new[] { coin };
					}
					else
					{
						//						Else Bitcoin Core does 1000 rounds of randomly combining unspent transaction outputs until their sum is greater than or equal to the Target. If it happens to find an exact match, it stops early and uses that.
						//Otherwise it finally settles for the minimum of
						//the smallest UTXO greater than the Target
						//the smallest combination of UTXO it discovered in Step 4.
						var allCoins = orderedCoins.ToArray();
						IMoney minTotal = null;
						for(int _ = 0; _ < 1000; _++)
						{
							var selection = new List<ICoin>();
							Utils.Shuffle(allCoins, _Rand);
							total = zero;
							for(int i = 0; i < allCoins.Length; i++)
							{
								selection.Add(allCoins[i]);
								total = total.Add(allCoins[i].Amount);
								if(total.CompareTo(target) == 0)
									return selection;
								if(total.CompareTo(target) == 1)
									break;
							}
							if(total.CompareTo(target) == -1)
							{
								return null;
							}
							if(minTotal == null || total.CompareTo(minTotal) == -1)
							{
								minTotal = total;
							}
						}
					}
				}
			}
			if(total.CompareTo(target) == -1)
				return null;
			return result;
		}
Ejemplo n.º 43
0
		public NotEnoughFundsException(string message, string group, IMoney missing)
			: base(BuildMessage(message, group, missing))
		{
			Missing = missing;
			Group = group;
		}