Ejemplo n.º 1
0
        public void DepositTest_NewAddressMustBeGenerated_VerifiesThroughDatabaseQueryAndReturnValue()
        {
            DepositController         depositController        = (DepositController)ContextRegistry.GetContext()["DepositController"];
            IDepositAddressRepository depositAddressRepository = (IDepositAddressRepository)ContextRegistry.GetContext()["DepositAddressRepository"];

            Assert.IsNotNull(depositController);

            string apiKey = "apiKey";

            depositController.Request = new HttpRequestMessage(HttpMethod.Post, "");
            depositController.Request.Headers.Add("Auth", apiKey);
            IHttpActionResult httpActionResult = depositController.CreateDepositAddress(new GenerateAddressParams(1, "LTC"));
            OkNegotiatedContentResult <DepositAddressRepresentation> response =
                (OkNegotiatedContentResult <DepositAddressRepresentation>)httpActionResult;

            Assert.IsNotNull(response);
            Assert.IsTrue(!string.IsNullOrEmpty(response.Content.Address));
            Assert.AreEqual(AddressStatus.New.ToString(), response.Content.Status);

            DepositAddress depositAddress = depositAddressRepository.GetDepositAddressByAddress(new BitcoinAddress(response.Content.Address));

            Assert.IsNotNull(depositAddress);
            Assert.AreEqual(AddressStatus.New, depositAddress.Status);

            httpActionResult = depositController.GetDepositAddresses(new GetDepositAddressesParams("LTC"));
            OkNegotiatedContentResult <IList <DepositAddressRepresentation> > depositAddresses =
                (OkNegotiatedContentResult <IList <DepositAddressRepresentation> >)httpActionResult;

            Assert.IsNotNull(depositAddresses.Content);
            Assert.Greater(depositAddresses.Content.Count, 0);
            Assert.AreEqual(response.Content.Address, depositAddresses.Content[0].Address);
            Assert.AreEqual(response.Content.Status, depositAddresses.Content[0].Status);
        }
Ejemplo n.º 2
0
 internal static void Display(DepositAddress address)
 {
     lock (ConsoleSync)
     {
         Console.WriteLine($"  {address.Asset} => {address.Address} - {(!string.IsNullOrWhiteSpace(address.AddressTag) ? address.AddressTag : "[No Address Tag]")}");
     }
 }
Ejemplo n.º 3
0
        public void SaveDepositAddressesAndRetreiveByAccountIdTest_SavesObjectsToDatabase_ChecksIfTheyAreAsExpected()
        {
            DepositAddress deposit = new DepositAddress(new Currency("XBT", true), new BitcoinAddress("iambitcoin123"), AddressStatus.New, DateTime.Now,
                                                        new AccountId(1));

            _persistanceRepository.SaveOrUpdate(deposit);

            DepositAddress deposit2 = new DepositAddress(new Currency("XBT", true), new BitcoinAddress("iambitcoin123"), AddressStatus.New, DateTime.Now,
                                                         new AccountId(1));

            Thread.Sleep(500);

            _persistanceRepository.SaveOrUpdate(deposit2);

            List <DepositAddress> retrievedDepositAddressList = _depositAddressRepository.GetDepositAddressByAccountId(new AccountId(1));

            Assert.IsNotNull(retrievedDepositAddressList);
            Assert.AreEqual(2, retrievedDepositAddressList.Count);

            Assert.AreEqual(deposit.BitcoinAddress.Value, retrievedDepositAddressList[0].BitcoinAddress.Value);
            Assert.AreEqual(deposit.Status, retrievedDepositAddressList[0].Status);
            Assert.AreEqual(deposit.AccountId.Value, retrievedDepositAddressList[0].AccountId.Value);

            Assert.AreEqual(deposit.BitcoinAddress.Value, retrievedDepositAddressList[1].BitcoinAddress.Value);
            Assert.AreEqual(deposit2.Status, retrievedDepositAddressList[1].Status);
            Assert.AreEqual(deposit2.AccountId.Value, retrievedDepositAddressList[1].AccountId.Value);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Add new Address
        /// </summary>
        /// <param name="addAddressCommand"></param>
        /// <returns></returns>
        public WithdrawAddressResponse AddAddress(AddAddressCommand addAddressCommand)
        {
            if (addAddressCommand.BitcoinAddress.Length < 26 || addAddressCommand.BitcoinAddress.Length > 34)
            {
                return(new WithdrawAddressResponse(false, "Invalid address"));
            }
            List <WithdrawAddress> withdrawAddresses = _withdrawAddressRepository.GetWithdrawAddressByAccountIdAndCurrency(
                new AccountId(addAddressCommand.AccountId), new Currency(addAddressCommand.Currency));

            foreach (var address in withdrawAddresses)
            {
                if (address.BitcoinAddress.Value == addAddressCommand.BitcoinAddress ||
                    address.Description == addAddressCommand.Description)
                {
                    return(new WithdrawAddressResponse(false, "Duplicate Entry"));
                }
            }
            // Create a new address and save in the database
            WithdrawAddress withdrawAddress = new WithdrawAddress(new Currency(addAddressCommand.Currency),
                                                                  new BitcoinAddress(addAddressCommand.BitcoinAddress), addAddressCommand.Description,
                                                                  new AccountId(addAddressCommand.AccountId), DateTime.Now);

            _fundsPersistenceRepository.SaveOrUpdate(withdrawAddress);

            DepositAddress depositAddress = _depositAddressRepository.GetDepositAddressByAddress(new BitcoinAddress(addAddressCommand.BitcoinAddress));

            if (depositAddress != null)
            {
                depositAddress.StatusUsed();
                _fundsPersistenceRepository.SaveOrUpdate(depositAddress);
            }
            return(new WithdrawAddressResponse(true, "Address Saved"));
        }
Ejemplo n.º 5
0
        public void DepositArrivedAndConfirmedTest_ChecksThatANewDepositInstanceIsCreatedAndConfirmedAsExpected_VerifiesThroughDatabaseQuery()
        {
            IDepositApplicationService  depositApplicationService  = (IDepositApplicationService)ContextRegistry.GetContext()["DepositApplicationService"];
            IFundsPersistenceRepository fundsPersistenceRepository = (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
            IBalanceRepository          balanceRepository          = (IBalanceRepository)ContextRegistry.GetContext()["BalanceRepository"];
            IDepositRepository          depositRepository          = (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];
            IDepositLimitRepository     depositLimitRepository     = (IDepositLimitRepository)ContextRegistry.GetContext()["DepositLimitRepository"];

            AccountId      accountId      = new AccountId(123);
            Currency       currency       = new Currency("BTC", true);
            BitcoinAddress bitcoinAddress = new BitcoinAddress("bitcoinaddress1");
            TransactionId  transactionId  = new TransactionId("transactionid1");
            string         category       = BitcoinConstants.ReceiveCategory;

            DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress, AddressStatus.New, DateTime.Now, accountId);

            fundsPersistenceRepository.SaveOrUpdate(depositAddress);
            DepositLimit depositLimit = depositLimitRepository.GetLimitByTierLevelAndCurrency("Tier 1", "Default");

            Assert.IsNotNull(depositLimit, "DepositLimit used initially to compare later");

            List <Tuple <string, string, decimal, string> > transactionsList = new List <Tuple <string, string, decimal, string> >();

            // Provide the amount which is greater than the daily limit
            transactionsList.Add(new Tuple <string, string, decimal, string>(bitcoinAddress.Value, transactionId.Value,
                                                                             depositLimit.DailyLimit - 0.01M, category));
            depositApplicationService.OnDepositArrival(currency.Name, transactionsList);

            // Deposit Transaction first arrival
            Deposit deposit = depositRepository.GetDepositByTransactionId(transactionId);

            Assert.IsNotNull(deposit);
            Assert.AreEqual(depositLimit.DailyLimit - 0.01M, deposit.Amount);
            Assert.AreEqual(transactionId.Value, deposit.TransactionId.Value);
            Assert.AreEqual(accountId.Value, deposit.AccountId.Value);
            Assert.AreEqual(bitcoinAddress.Value, deposit.BitcoinAddress.Value);
            Assert.AreEqual(TransactionStatus.Pending, deposit.Status);
            Balance balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);

            Assert.IsNull(balance);

            // Deposit Confirmation
            depositApplicationService.OnDepositConfirmed(transactionId.Value, 7);
            deposit = depositRepository.GetDepositByTransactionId(transactionId);
            Assert.IsNotNull(deposit);
            Assert.AreEqual(depositLimit.DailyLimit - 0.01M, deposit.Amount);
            Assert.AreEqual(transactionId.Value, deposit.TransactionId.Value);
            Assert.AreEqual(accountId.Value, deposit.AccountId.Value);
            Assert.AreEqual(bitcoinAddress.Value, deposit.BitcoinAddress.Value);
            Assert.AreEqual(TransactionStatus.Confirmed, deposit.Status);

            // Balance instance now will have been created
            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNotNull(balance);
            Assert.AreEqual(depositLimit.DailyLimit - 0.01M, balance.AvailableBalance);
            Assert.AreEqual(depositLimit.DailyLimit - 0.01M, balance.CurrentBalance);
            Assert.AreEqual(0, balance.PendingBalance);
            Assert.IsFalse(balance.IsFrozen);
        }
Ejemplo n.º 6
0
 public static BlockchainDepositAddressEntity Create(DepositAddress address)
 {
     return(new BlockchainDepositAddressEntity
     {
         PartitionKey = GeneratePartitionKey(address.AssetSymbol, address.Blockchain, address.Address),
         RowKey = GenerateRowKey(),
         Address = address
     });
 }
        /// <summary>
        /// Get a new address from the Bitcoin Client
        /// </summary>
        /// <param name="generateNewAddressCommand"></param>
        /// <returns></returns>
        public DepositAddressRepresentation GenarateNewAddress(GenerateNewAddressCommand generateNewAddressCommand)
        {
            Balance balance = _balanceRepository.GetBalanceByCurrencyAndAccountId(new Currency(generateNewAddressCommand.Currency),
                                                                                  new AccountId(generateNewAddressCommand.AccountId));

            if (balance != null)
            {
                if (balance.IsFrozen)
                {
                    throw new InvalidOperationException(string.Format("Account balance Frozen for Account ID = {0}, Currency = {1}",
                                                                      generateNewAddressCommand.AccountId, generateNewAddressCommand.Currency));
                }
            }
            //Check if the required Tier Level for this operation is verified i.e., Tier 1
            if (_fundsValidationService.IsTierVerified(generateNewAddressCommand.AccountId, true).Item1)
            {
                List <DepositAddress> depositAddresses = _depositAddressRepository.
                                                         GetDepositAddressByAccountIdAndCurrency(
                    new AccountId(generateNewAddressCommand.AccountId), generateNewAddressCommand.Currency);

                if (depositAddresses != null && depositAddresses.Any())
                {
                    // Cannot allow more than 5 New Unused addresses at a time, so will raise exception if count exceeds or reaches 5
                    int counter = 0;
                    foreach (DepositAddress depositAddress1 in depositAddresses)
                    {
                        if (depositAddress1.Status == AddressStatus.New)
                        {
                            counter++;
                        }
                    }
                    if (counter >= 5)
                    {
                        Log.Debug(string.Format("Cannot create more than 5 new addresses at a time: Currency = {0}, AccountID = {1}",
                                                generateNewAddressCommand.Currency, generateNewAddressCommand.AccountId));
                        throw new InvalidOperationException("Too many New addresses");
                    }
                }
                // Generate new address using the client
                string address = _clientInteractionService.GenerateNewAddress(generateNewAddressCommand.Currency);
                if (!string.IsNullOrEmpty(address))
                {
                    // Save the address in database
                    DepositAddress depositAddress = new DepositAddress(new Currency(generateNewAddressCommand.Currency),
                                                                       new BitcoinAddress(address), AddressStatus.New,
                                                                       DateTime.Now,
                                                                       new AccountId(generateNewAddressCommand.AccountId));
                    _fundsPersistenceRepository.SaveOrUpdate(depositAddress);
                    Log.Debug(string.Format("New address generated and saved: Currency = {0} | AccountID = {1}",
                                            generateNewAddressCommand.Currency, generateNewAddressCommand.AccountId));
                    return(new DepositAddressRepresentation(address, AddressStatus.New.ToString()));
                }
                throw new NullReferenceException(string.Format("Null address returned from client for currency: {0}", generateNewAddressCommand.Currency));
            }
            throw new InvalidOperationException(string.Format("Tier 1 is not verified: Account ID = {0}",
                                                              generateNewAddressCommand.AccountId));
        }
Ejemplo n.º 8
0
        public void DepositArrivedStandaloneFailedTest_TestsIfTheOperationIsAbortedWhenAmountIshigherThanThresholdLimit_VerifiesThroughQueryingDatabaseIsntances()
        {
            // Tests the event handler DepositArrived by directly sending data
            IDepositApplicationService    depositApplicationService  = (IDepositApplicationService)ContextRegistry.GetContext()["DepositApplicationService"];
            IFundsPersistenceRepository   fundsPersistenceRepository = (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
            IBalanceRepository            balanceRepository          = (IBalanceRepository)ContextRegistry.GetContext()["BalanceRepository"];
            ILedgerRepository             ledgerRepository           = (ILedgerRepository)ContextRegistry.GetContext()["LedgerRepository"];
            IDepositRepository            depositRepository          = (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];
            IDepositLimitRepository       depositLimitRepository     = (IDepositLimitRepository)ContextRegistry.GetContext()["DepositLimitRepository"];
            StubTierLevelRetrievalService tierLevelRetrievalService  = (ITierLevelRetrievalService)ContextRegistry.GetContext()["TierLevelRetrievalService"] as StubTierLevelRetrievalService;

            Assert.IsNotNull(tierLevelRetrievalService);
            tierLevelRetrievalService.SetTierLevel(TierConstants.TierLevel1);
            AccountId      accountId      = new AccountId(123);
            Currency       currency       = new Currency("BTC", true);
            BitcoinAddress bitcoinAddress = new BitcoinAddress("bitcoinaddress1");
            TransactionId  transactionId  = new TransactionId("transactionid1");

            DepositLimit depositLimit = depositLimitRepository.GetLimitByTierLevelAndCurrency(TierConstants.TierLevel1,
                                                                                              LimitsCurrency.Default.ToString());
            decimal amount   = depositLimit.DailyLimit + 0.001M;
            string  category = BitcoinConstants.ReceiveCategory;

            DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress, AddressStatus.New, DateTime.Now,
                                                               accountId);

            fundsPersistenceRepository.SaveOrUpdate(depositAddress);

            Balance balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);

            Assert.IsNull(balance);

            IList <Ledger> ledgers = ledgerRepository.GetLedgerByAccountIdAndCurrency(currency.Name, accountId);

            Assert.AreEqual(ledgers.Count, 0);

            List <Tuple <string, string, decimal, string> > transactionsList = new List <Tuple <string, string, decimal, string> >();

            transactionsList.Add(new Tuple <string, string, decimal, string>(bitcoinAddress.Value, transactionId.Value, amount, category));
            depositApplicationService.OnDepositArrival(currency.Name, transactionsList);

            Deposit deposit = depositRepository.GetDepositByTransactionId(transactionId);

            Assert.IsNotNull(deposit);
            Assert.AreEqual(amount, deposit.Amount);
            Assert.AreEqual(currency.Name, deposit.Currency.Name);
            Assert.AreEqual(accountId.Value, deposit.AccountId.Value);
            Assert.AreEqual(bitcoinAddress.Value, deposit.BitcoinAddress.Value);
            Assert.AreEqual(transactionId.Value, deposit.TransactionId.Value);
            Assert.AreEqual(TransactionStatus.Frozen, deposit.Status);

            // Confirm that the balance for the user has been frozen for this account
            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNotNull(balance);
            Assert.IsTrue(balance.IsFrozen);
        }
        public void Properties()
        {
            var          asset      = Asset.BTC;
            const string address    = "1234567890";
            const string addressTag = "12341234";

            var depositAddress = new DepositAddress(asset, address, addressTag);

            Assert.Equal(asset, depositAddress.Asset);
            Assert.Equal(address, depositAddress.Address);
            Assert.Equal(addressTag, depositAddress.AddressTag);
        }
Ejemplo n.º 10
0
        public InvoiceResponse EntityToDTO()
        {
            ServerUrl = ServerUrl ?? "";
            InvoiceResponse dto = new InvoiceResponse
            {
                Id             = Id,
                OrderId        = OrderId,
                PosData        = PosData,
                CurrentTime    = DateTimeOffset.UtcNow,
                InvoiceTime    = InvoiceTime,
                ExpirationTime = ExpirationTime,
                BTCPrice       = Money.Coins((decimal)(1.0 / Rate)).ToString(),
                Status         = Status,
                Url            = ServerUrl.WithTrailingSlash() + "invoice?id=" + Id,
                Currency       = ProductInformation.Currency,
                Flags          = new Flags()
                {
                    Refundable = Refundable
                }
            };

            Populate(ProductInformation, dto);
            Populate(BuyerInformation, dto);
            dto.ExRates = new Dictionary <string, double>
            {
                { ProductInformation.Currency, Rate }
            };
            dto.PaymentUrls = new InvoicePaymentUrls()
            {
                BIP72  = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}&r={ServerUrl.WithTrailingSlash() + ($"i/{Id}")}",
                BIP72b = $"bitcoin:?r={ServerUrl.WithTrailingSlash() + ($"i/{Id}")}",
                BIP73  = ServerUrl.WithTrailingSlash() + ($"i/{Id}"),
                BIP21  = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}",
            };
            dto.BitcoinAddress = DepositAddress.ToString();
            dto.Token          = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16));    //No idea what it is useful for
            dto.Guid           = Guid.NewGuid().ToString();

            var paid = Payments.Select(p => p.Output.Value).Sum();

            dto.BTCPaid = paid.ToString();
            dto.BTCDue  = GetCryptoDue().ToString();

            dto.ExceptionStatus = ExceptionStatus == null ? new JValue(false) : new JValue(ExceptionStatus);
            return(dto);
        }
Ejemplo n.º 11
0
        public void DepositArrivedFailTest_VerifiesThatNewDepositWithAMountGreaterThanLimitsIsSuspendedAndAccountBalanceFrozen_VerifiesThroughDatabaseQuery()
        {
            IDepositApplicationService  depositApplicationService  = (IDepositApplicationService)ContextRegistry.GetContext()["DepositApplicationService"];
            IFundsPersistenceRepository fundsPersistenceRepository = (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
            IBalanceRepository          balanceRepository          = (IBalanceRepository)ContextRegistry.GetContext()["BalanceRepository"];
            IDepositRepository          depositRepository          = (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];
            IDepositLimitRepository     depositLimitRepository     = (IDepositLimitRepository)ContextRegistry.GetContext()["DepositLimitRepository"];

            AccountId      accountId      = new AccountId(123);
            Currency       currency       = new Currency("BTC", true);
            BitcoinAddress bitcoinAddress = new BitcoinAddress("bitcoinaddress1");
            TransactionId  transactionId  = new TransactionId("transactionid1");
            string         category       = BitcoinConstants.ReceiveCategory;

            DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress, AddressStatus.New, DateTime.Now, accountId);

            fundsPersistenceRepository.SaveOrUpdate(depositAddress);
            DepositLimit depositLimit = depositLimitRepository.GetLimitByTierLevelAndCurrency("Tier 1", "Default");

            Assert.IsNotNull(depositLimit, "DepositLimit used initially to compare later");

            List <Tuple <string, string, decimal, string> > transactionsList = new List <Tuple <string, string, decimal, string> >();

            // Provide the amount which is greater than the daily limit
            transactionsList.Add(new Tuple <string, string, decimal, string>(bitcoinAddress.Value, transactionId.Value,
                                                                             depositLimit.DailyLimit + 0.001M, category));
            depositApplicationService.OnDepositArrival(currency.Name, transactionsList);

            Deposit deposit = depositRepository.GetDepositByTransactionId(transactionId);

            Assert.IsNotNull(deposit);
            Assert.AreEqual(TransactionStatus.Frozen, deposit.Status);
            Balance balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);

            Assert.IsNotNull(balance);
            Assert.IsTrue(balance.IsFrozen);
        }
 public DepositAddressSqlEntity(DepositAddress address) : base(address)
 {
 }
Ejemplo n.º 13
0
 public string GetPaymentDestination()
 {
     return(DepositAddress?.ToString());
 }
Ejemplo n.º 14
0
        public void DepositCheckNewTransactionsTest_TestIfDepositHandlingIsDoneAsExpected_VerifiesThroughReturnedValue()
        {
            // Submits withdraw to own address, after the first NewTransactionInterval has been elapsed.
            // Checks if new deposit has been created by the DepositAPplicationService and DepositAddress marked used
            if (_shouldRunTests)
            {
                ICoinClientService coinClientService =
                    (ICoinClientService)ContextRegistry.GetContext()["BitcoinClientService"];
                IFundsPersistenceRepository fundsPersistenceRepository =
                    (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
                IDepositAddressRepository depositAddressRepository =
                    (IDepositAddressRepository)ContextRegistry.GetContext()["DepositAddressRepository"];
                IDepositRepository depositRepository =
                    (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];

                Currency       currency       = new Currency("BTC", true);
                AccountId      accountId      = new AccountId(1);
                string         newAddress     = coinClientService.CreateNewAddress();
                BitcoinAddress bitcoinAddress = new BitcoinAddress(newAddress);
                DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress,
                                                                   AddressStatus.New, DateTime.Now, accountId);
                fundsPersistenceRepository.SaveOrUpdate(depositAddress);

                // Check that there is no deposit with htis address present
                List <Deposit> deposits = depositRepository.GetDepositsByBitcoinAddress(bitcoinAddress);
                Assert.AreEqual(0, deposits.Count);

                ManualResetEvent manualResetEvent = new ManualResetEvent(false);

                // Wait for the first interval to elapse, and then withdraw, because only then we will be able to figure if a
                // new transaction has been received
                manualResetEvent.WaitOne(Convert.ToInt32(coinClientService.PollingInterval + 3000));

                manualResetEvent.Reset();
                bool eventFired = false;
                coinClientService.DepositArrived += delegate(string curr, List <Tuple <string, string, decimal, string> > pendingList)
                {
                    eventFired = true;
                    manualResetEvent.Set();
                };

                Withdraw withdraw = new Withdraw(currency, Guid.NewGuid().ToString(), DateTime.Now, WithdrawType.Bitcoin,
                                                 Amount, 0.001m, TransactionStatus.Pending, accountId,
                                                 new BitcoinAddress(newAddress));
                string withdrawTransactionId = coinClientService.CommitWithdraw(withdraw.BitcoinAddress.Value, withdraw.Amount);
                Assert.IsNotNull(withdrawTransactionId);
                Assert.IsFalse(string.IsNullOrEmpty(withdrawTransactionId));
                manualResetEvent.WaitOne();

                Assert.IsTrue(eventFired);
                depositAddress = depositAddressRepository.GetDepositAddressByAddress(bitcoinAddress);
                Assert.IsNotNull(depositAddress);
                Assert.AreEqual(AddressStatus.Used, depositAddress.Status);

                // See If DepositApplicationService created the deposit instance
                deposits = depositRepository.GetDepositsByBitcoinAddress(bitcoinAddress);
                Deposit deposit = deposits.Single();
                Assert.IsNotNull(deposit);
                Assert.AreEqual(Amount, deposit.Amount);
                Assert.AreEqual(currency.Name, deposit.Currency.Name);
                Assert.IsFalse(string.IsNullOrEmpty(deposit.TransactionId.Value));
                Assert.AreEqual(bitcoinAddress.Value, deposit.BitcoinAddress.Value);
                Assert.AreEqual(DepositType.Default, deposit.Type);
                Assert.AreEqual(0, deposit.Confirmations);
                Assert.AreEqual(accountId.Value, deposit.AccountId.Value);
                Assert.AreEqual(TransactionStatus.Pending, deposit.Status);

                Assert.AreEqual(withdrawTransactionId, deposit.TransactionId.Value);
            }
        }
Ejemplo n.º 15
0
        public void DepositArrivedAndConfirmedEventTest_TestsThatDepositArrivedEventIsHandledAsExpected_VerifiesThroughRaisedEvent()
        {
            // Withdraw is submitted and events are actually raised from the CoinClientService
            // Over the limit deposit so account and deposit are frozen
            IFundsPersistenceRepository fundsPersistenceRepository = (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
            IBalanceRepository          balanceRepository          = (IBalanceRepository)ContextRegistry.GetContext()["BalanceRepository"];
            IDepositRepository          depositRepository          = (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];
            IWithdrawRepository         withdrawRepository         = (IWithdrawRepository)ContextRegistry.GetContext()["WithdrawRepository"];
            IDepositLimitRepository     depositLimitRepository     = (IDepositLimitRepository)ContextRegistry.GetContext()["DepositLimitRepository"];
            IWithdrawApplicationService withdrawApplicationService = (IWithdrawApplicationService)ContextRegistry.GetContext()["WithdrawApplicationService"];

            AccountId      accountId      = new AccountId(123);
            Currency       currency       = new Currency("BTC", true);
            BitcoinAddress bitcoinAddress = new BitcoinAddress("bitcoinaddress1");
            TransactionId  transactionId  = new TransactionId("transactionid1");

            DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress, AddressStatus.New, DateTime.Now,
                                                               accountId);

            fundsPersistenceRepository.SaveOrUpdate(depositAddress);
            DepositLimit depositLimit = depositLimitRepository.GetLimitByTierLevelAndCurrency("Tier 1", "Default");

            Assert.IsNotNull(depositLimit, "DepositLimit used initially to compare later");
            decimal amount = depositLimit.DailyLimit - 0.001M;

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            Balance balance = new Balance(currency, accountId, 10, 10);

            fundsPersistenceRepository.SaveOrUpdate(balance);
            CommitWithdrawResponse commitWithdrawResponse = withdrawApplicationService.CommitWithdrawal(new CommitWithdrawCommand(
                                                                                                            accountId.Value, currency.Name, currency.IsCryptoCurrency, bitcoinAddress.Value, amount));

            Assert.IsNotNull(commitWithdrawResponse);
            Assert.IsTrue(commitWithdrawResponse.CommitSuccessful);
            // Get the interval after which the withdraw will be submitted. Once submitted to the StubClientService, the events
            // of DepositArrived will be raised and handled in Deposit APplicationService, which will create a new Deposit
            // instance and save in database
            int withdrawInterval = Convert.ToInt16(ConfigurationManager.AppSettings.Get("WithdrawSubmitInterval"));

            manualResetEvent.WaitOne(withdrawInterval + 2000);

            Withdraw withdraw = withdrawRepository.GetWithdrawByWithdrawId(commitWithdrawResponse.WithdrawId);

            Assert.IsNotNull(withdraw);
            Deposit deposit = depositRepository.GetDepositByTransactionId(transactionId);

            Assert.IsNotNull(deposit);
            Assert.AreEqual(amount - withdraw.Fee, deposit.Amount);
            Assert.AreEqual(withdraw.TransactionId.Value, deposit.TransactionId.Value);
            Assert.AreEqual(accountId.Value, deposit.AccountId.Value);
            Assert.AreEqual(bitcoinAddress.Value, deposit.BitcoinAddress.Value);
            Assert.AreEqual(TransactionStatus.Confirmed, deposit.Status);
            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNotNull(balance);

            // Balance instance now will have been created
            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNotNull(balance);
            Assert.AreEqual(0, balance.PendingBalance);
            Assert.IsFalse(balance.IsFrozen);
        }
Ejemplo n.º 16
0
        public void DepositConfirmedTest_TestsIfTheOperationProceedsAsExpectedWhenADepositIsConfirmed_VerifiesThroughQueryingDatabaseIsntances()
        {
            IDepositApplicationService    depositApplicationService  = (IDepositApplicationService)ContextRegistry.GetContext()["DepositApplicationService"];
            IFundsPersistenceRepository   fundsPersistenceRepository = (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
            IBalanceRepository            balanceRepository          = (IBalanceRepository)ContextRegistry.GetContext()["BalanceRepository"];
            ILedgerRepository             ledgerRepository           = (ILedgerRepository)ContextRegistry.GetContext()["LedgerRepository"];
            IDepositRepository            depositRepository          = (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];
            IDepositAddressRepository     depositAddressRepository   = (IDepositAddressRepository)ContextRegistry.GetContext()["DepositAddressRepository"];
            StubTierLevelRetrievalService tierLevelRetrievalService  = (ITierLevelRetrievalService)ContextRegistry.GetContext()["TierLevelRetrievalService"] as StubTierLevelRetrievalService;

            if (tierLevelRetrievalService != null)
            {
                tierLevelRetrievalService.SetTierLevel(TierConstants.TierLevel1);
            }
            AccountId      accountId      = new AccountId(123);
            Currency       currency       = new Currency("BTC", true);
            BitcoinAddress bitcoinAddress = new BitcoinAddress("bitcoinaddress1");
            TransactionId  transactionId  = new TransactionId("transactionid1");
            decimal        amount         = 1.02m;
            string         category       = BitcoinConstants.ReceiveCategory;

            DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress, AddressStatus.New, DateTime.Now,
                                                               accountId);

            fundsPersistenceRepository.SaveOrUpdate(depositAddress);

            Balance balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);

            Assert.IsNull(balance);

            IList <Ledger> ledgers = ledgerRepository.GetLedgerByAccountIdAndCurrency(currency.Name, accountId);

            Assert.AreEqual(ledgers.Count, 0);

            List <Tuple <string, string, decimal, string> > transactionsList = new List <Tuple <string, string, decimal, string> >();

            transactionsList.Add(new Tuple <string, string, decimal, string>(bitcoinAddress.Value, transactionId.Value, amount, category));
            depositApplicationService.OnDepositArrival(currency.Name, transactionsList);

            Deposit deposit = depositRepository.GetDepositByTransactionId(transactionId);

            Assert.IsNotNull(deposit);
            Assert.AreEqual(deposit.Amount, amount);
            Assert.AreEqual(deposit.Currency.Name, currency.Name);
            Assert.IsTrue(deposit.Currency.IsCryptoCurrency);
            Assert.AreEqual(deposit.TransactionId.Value, transactionId.Value);
            Assert.AreEqual(deposit.BitcoinAddress.Value, bitcoinAddress.Value);
            Assert.AreEqual(TransactionStatus.Pending, deposit.Status);

            depositAddress = depositAddressRepository.GetDepositAddressByAddress(bitcoinAddress);
            Assert.IsNotNull(depositAddress);
            Assert.AreEqual(AddressStatus.Used, depositAddress.Status);

            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNull(balance);

            ledgers = ledgerRepository.GetLedgerByAccountIdAndCurrency(currency.Name, accountId);
            Assert.AreEqual(0, ledgers.Count);

            depositApplicationService.OnDepositConfirmed(transactionId.Value, 7);

            deposit = depositRepository.GetDepositByTransactionId(transactionId);
            Assert.IsNotNull(deposit);
            Assert.AreEqual(deposit.Status, TransactionStatus.Confirmed);

            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNotNull(balance);
            Assert.AreEqual(amount, balance.AvailableBalance);
            Assert.AreEqual(amount, balance.CurrentBalance);
            Assert.AreEqual(0, balance.PendingBalance);

            ledgers = ledgerRepository.GetLedgerByAccountIdAndCurrency(currency.Name, accountId);
            Assert.AreEqual(1, ledgers.Count);
            var ledger = ledgers.SingleOrDefault();

            Assert.IsNotNull(ledger);
            Assert.AreEqual(LedgerType.Deposit, ledger.LedgerType);
            Assert.AreEqual(accountId.Value, ledger.AccountId.Value);
            Assert.AreEqual(amount, ledger.Amount);
            Assert.AreEqual(deposit.DepositId, ledger.DepositId);
            Assert.AreEqual(0, ledger.Fee);
        }
Ejemplo n.º 17
0
        public void DepositArrivedStandaloneTest_TestsIfTheOperationProceedsAsExpectedWHenANewDepositArrives_VerifiesThroughQueryingDatabaseIsntances()
        {
            // Tests the event handler DepositArrived by directly sending data
            IDepositApplicationService    depositApplicationService  = (IDepositApplicationService)ContextRegistry.GetContext()["DepositApplicationService"];
            IFundsPersistenceRepository   fundsPersistenceRepository = (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
            IBalanceRepository            balanceRepository          = (IBalanceRepository)ContextRegistry.GetContext()["BalanceRepository"];
            ILedgerRepository             ledgerRepository           = (ILedgerRepository)ContextRegistry.GetContext()["LedgerRepository"];
            IDepositRepository            depositRepository          = (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];
            IDepositAddressRepository     depositAddressRepository   = (IDepositAddressRepository)ContextRegistry.GetContext()["DepositAddressRepository"];
            IDepositLimitRepository       depositLimitRepository     = (IDepositLimitRepository)ContextRegistry.GetContext()["DepositLimitRepository"];
            StubTierLevelRetrievalService tierLevelRetrieval         = (StubTierLevelRetrievalService)ContextRegistry.GetContext()["TierLevelRetrievalService"];

            tierLevelRetrieval.SetTierLevel(TierConstants.TierLevel1);
            AccountId      accountId      = new AccountId(123);
            Currency       currency       = new Currency("BTC", true);
            BitcoinAddress bitcoinAddress = new BitcoinAddress("bitcoinaddress1");
            TransactionId  transactionId  = new TransactionId("transactionid1");
            DepositLimit   depositLimit   = depositLimitRepository.GetLimitByTierLevelAndCurrency(TierConstants.TierLevel1,
                                                                                                  LimitsCurrency.Default.ToString());
            decimal amount   = depositLimit.DailyLimit - 0.001M;
            string  category = BitcoinConstants.ReceiveCategory;

            DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress, AddressStatus.New, DateTime.Now,
                                                               accountId);

            fundsPersistenceRepository.SaveOrUpdate(depositAddress);

            Balance balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);

            Assert.IsNull(balance);

            IList <Ledger> ledgers = ledgerRepository.GetLedgerByAccountIdAndCurrency(currency.Name, accountId);

            Assert.AreEqual(ledgers.Count, 0);

            List <Tuple <string, string, decimal, string> > transactionsList = new List <Tuple <string, string, decimal, string> >();

            transactionsList.Add(new Tuple <string, string, decimal, string>(bitcoinAddress.Value, transactionId.Value, amount, category));
            depositApplicationService.OnDepositArrival(currency.Name, transactionsList);

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            manualResetEvent.WaitOne(2000);
            Deposit deposit = depositRepository.GetDepositByTransactionId(transactionId);

            Assert.IsNotNull(deposit);
            Assert.AreEqual(deposit.Amount, amount);
            Assert.AreEqual(deposit.Currency.Name, currency.Name);
            Assert.IsTrue(deposit.Currency.IsCryptoCurrency);
            Assert.AreEqual(deposit.TransactionId.Value, transactionId.Value);
            Assert.AreEqual(deposit.BitcoinAddress.Value, bitcoinAddress.Value);
            Assert.AreEqual(deposit.Status, TransactionStatus.Pending);

            depositAddress = depositAddressRepository.GetDepositAddressByAddress(bitcoinAddress);
            Assert.IsNotNull(depositAddress);
            Assert.AreEqual(depositAddress.Status, AddressStatus.Used);

            balance = balanceRepository.GetBalanceByCurrencyAndAccountId(currency, accountId);
            Assert.IsNull(balance);

            ledgers = ledgerRepository.GetLedgerByAccountIdAndCurrency(currency.Name, accountId);
            Assert.AreEqual(ledgers.Count, 0);
        }