public void RecoverWalletSuccessfullyReturnsWalletModel()
        {
            Bitcoin.Wallet.Wallet wallet = new Bitcoin.Wallet.Wallet
            {
                Name    = "myWallet",
                Network = WalletHelpers.GetNetwork("mainnet")
            };
            var mockWalletWrapper = new Mock <IWalletManager>();

            mockWalletWrapper.Setup(w => w.LoadWallet(It.IsAny <string>(), It.IsAny <string>())).Returns(wallet);
            string dir        = AssureEmptyDir("TestData/ControllersTests/RecoverWalletSuccessfullyReturnsWalletModel");
            var    dataFolder = new DataFolder(new NodeSettings {
                DataDir = dir
            });

            var controller = new WalletController(mockWalletWrapper.Object, new Mock <IWalletSyncManager>().Object, It.IsAny <ConnectionManager>(), Network.Main, new Mock <ConcurrentChain>().Object, dataFolder);

            // Act
            var result = controller.Load(new WalletLoadRequest
            {
                Name       = "myWallet",
                FolderPath = "",
                Password   = ""
            });

            // Assert
            mockWalletWrapper.VerifyAll();
            var viewResult = Assert.IsType <OkResult>(result);

            Assert.Equal(200, viewResult.StatusCode);
        }
        public Unity3dController(ILoggerFactory loggerFactory, IAddressIndexer addressIndexer,
                                 IBlockStore blockStore, IChainState chainState, Network network, ICoinView coinView, WalletController walletController, ChainIndexer chainIndexer, INFTTransferIndexer NFTTransferIndexer,
                                 IStakeChain stakeChain = null,
                                 IContractPrimitiveSerializer primitiveSerializer = null, IStateRepositoryRoot stateRoot = null, IContractAssemblyCache contractAssemblyCache                   = null,
                                 IReceiptRepository receiptRepository             = null, ISmartContractTransactionService smartContractTransactionService = null, ILocalExecutor localExecutor = null)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
            this.addressIndexer     = Guard.NotNull(addressIndexer, nameof(addressIndexer));
            this.blockStore         = Guard.NotNull(blockStore, nameof(blockStore));
            this.chainState         = Guard.NotNull(chainState, nameof(chainState));
            this.network            = Guard.NotNull(network, nameof(network));
            this.coinView           = Guard.NotNull(coinView, nameof(coinView));
            this.walletController   = Guard.NotNull(walletController, nameof(walletController));
            this.chainIndexer       = Guard.NotNull(chainIndexer, nameof(chainIndexer));
            this.stakeChain         = stakeChain;
            this.NFTTransferIndexer = NFTTransferIndexer;

            this.primitiveSerializer             = primitiveSerializer;
            this.stateRoot                       = stateRoot;
            this.contractAssemblyCache           = contractAssemblyCache;
            this.receiptRepository               = receiptRepository;
            this.smartContractTransactionService = smartContractTransactionService;
            this.localExecutor                   = localExecutor;
        }
        private void GenerateKeys(string seed)
        {
            // generate the RSA keypair for the address
            AsymmetricCipherKeyPair rsaKeyPair = WalletController.GetRSAKeyPairFromSeed(seed);

            RsaKeyParameters rsaPublicKey = rsaKeyPair.Public as RsaKeyParameters;
            RsaPublicKey     pbk          = new RsaPublicKey()
            {
                Exponent = rsaPublicKey.Exponent.ToByteArrayUnsigned(),
                Modulus  = rsaPublicKey.Modulus.ToByteArrayUnsigned()
            };

            RsaPrivateCrtKeyParameters rsaPrivateKey = rsaKeyPair.Private as RsaPrivateCrtKeyParameters;
            RsaPrivateKey prk = new RsaPrivateKey()
            {
                DP             = rsaPrivateKey.DP.ToByteArrayUnsigned(),
                DQ             = rsaPrivateKey.DQ.ToByteArrayUnsigned(),
                Exponent       = rsaPrivateKey.Exponent.ToByteArrayUnsigned(),
                Modulus        = rsaPrivateKey.Modulus.ToByteArrayUnsigned(),
                P              = rsaPrivateKey.P.ToByteArrayUnsigned(),
                PublicExponent = rsaPrivateKey.PublicExponent.ToByteArrayUnsigned(),
                Q              = rsaPrivateKey.Q.ToByteArrayUnsigned(),
                QInv           = rsaPrivateKey.QInv.ToByteArrayUnsigned()
            };

            this._testOutputHelper.WriteLine($"Public key: {pbk.ToHex()}");
            this._testOutputHelper.WriteLine($"Private key: {prk.ToHex()}");
        }
Ejemplo n.º 4
0
        public void RecoverWalletSuccessfullyReturnsWalletModel()
        {
            WalletModel walletModel = new WalletModel
            {
                FileName  = "myWallet",
                Network   = "MainNet",
                Addresses = new List <string> {
                    "address1", "address2", "address3", "address4", "address5"
                }
            };
            var mockWalletWrapper = new Mock <IWalletWrapper>();

            mockWalletWrapper.Setup(wallet => wallet.Load(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(walletModel);

            var controller = new WalletController(mockWalletWrapper.Object);

            // Act
            var result = controller.Load(new WalletLoadRequest
            {
                Name       = "myName",
                FolderPath = "",
                Password   = ""
            });

            // Assert
            mockWalletWrapper.VerifyAll();
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.NotNull(viewResult.Value);
            Assert.IsType <WalletModel>(viewResult.Value);

            var model = viewResult.Value as WalletModel;

            Assert.Equal("myWallet", model.FileName);
        }
Ejemplo n.º 5
0
        public void RecoverWalletSuccessfullyReturnsWalletModel()
        {
            Wallet.Wallet wallet = new Wallet.Wallet
            {
                Name    = "myWallet",
                Network = WalletHelpers.GetNetwork("mainnet")
            };
            var mockWalletWrapper = new Mock <IWalletManager>();

            mockWalletWrapper.Setup(w => w.LoadWallet(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(wallet);

            var controller = new WalletController(mockWalletWrapper.Object, new Mock <ITracker>().Object);

            // Act
            var result = controller.Load(new WalletLoadRequest
            {
                Name       = "myWallet",
                FolderPath = "",
                Password   = ""
            });

            // Assert
            mockWalletWrapper.VerifyAll();
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.NotNull(viewResult.Value);
            Assert.IsType <WalletModel>(viewResult.Value);

            var model = viewResult.Value as WalletModel;

            Assert.Equal("Main", model.Network);
        }
Ejemplo n.º 6
0
 void Start()
 {
     if (itemType != ItemsType.coin && itemType != ItemsType.yellowCard)
     {
         value = WalletController.getValue(itemType);
     }
 }
Ejemplo n.º 7
0
    void android_purchaseSucceededEvent(GooglePurchase purchase)
    {
        if (purchase.purchaseState == GooglePurchase.GooglePurchaseState.Purchased)
        {
            if (purchase.productId == BillingItemsIds.coin_01)
            {
                WalletController.addCoins(100f);
            }
            else if (purchase.productId == BillingItemsIds.coin_02)
            {
                WalletController.addCoins(1000f);
            }
            else if (purchase.productId == BillingItemsIds.coin_03)
            {
                WalletController.addCoins(10000f);
            }
            else if (purchase.productId == BillingItemsIds.coin_04)
            {
                WalletController.addCoins(100000f);
            }

            BillingManager.consumeItem(purchase.productId);

            StoreInterface.updateCoin();
        }
    }
Ejemplo n.º 8
0
    private void addOnWallet()
    {
        switch (itemType)
        {
        case ItemsType.coin: {
            WalletController.addCoin();

            break;
        }

        case ItemsType.whistle: {
            WalletController.addCoins(value);

            break;
        }

        case ItemsType.yellowCard: {
            WalletController.addYellowCard();

            break;
        }

        default: {
            WalletController.addItems(itemType, value);

            break;
        }
        }

        Destroy(this.gameObject);
    }
Ejemplo n.º 9
0
        public async Task IShouldCanSeeTheWalletExtract()
        {
            var viewModel = new ExtractViewModel();

            var mockForWalletService = new Mock <IWalletApplicationService>();

            mockForWalletService.Setup(d => d.GetExtract(It.IsAny <string>()))
            .ReturnsAsync(viewModel)
            .Verifiable();

            var mockForHttpContextAccessor = new Mock <IHttpContextAccessor>();

            mockForHttpContextAccessor.Setup(d => d.HttpContext.User.Identity.Name)
            .Returns(It.IsAny <string>())
            .Verifiable();

            var controller = new WalletController(
                mockForWalletService.Object,
                mockForHttpContextAccessor.Object);

            var result = await controller.Extract();

            var resultOk   = result as OkObjectResult;
            var resultData = resultOk.Value as BalanceViewModel;

            Assert.IsInstanceOfType(result, typeof(ActionResult));
            Assert.AreEqual(resultOk.StatusCode, 200);
            mockForWalletService.VerifyAll();
        }
Ejemplo n.º 10
0
        public void LoadWalletSuccessfullyReturnsWalletModel()
        {
            Bitcoin.Wallet.Wallet wallet = new Bitcoin.Wallet.Wallet
            {
                Name    = "myWallet",
                Network = WalletHelpers.GetNetwork("mainnet")
            };

            var mockWalletWrapper = new Mock <IWalletManager>();

            mockWalletWrapper.Setup(w => w.RecoverWallet(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>(), null)).Returns(wallet);

            var controller = new WalletController(mockWalletWrapper.Object, new Mock <IWalletSyncManager>().Object, It.IsAny <ConnectionManager>(), Network.Main, new Mock <ConcurrentChain>().Object);

            // Act
            var result = controller.Recover(new WalletRecoveryRequest
            {
                Name       = "myWallet",
                FolderPath = "",
                Password   = "",
                Network    = "MainNet",
                Mnemonic   = "mnemonic"
            });

            // Assert
            mockWalletWrapper.VerifyAll();
            var viewResult = Assert.IsType <OkResult>(result);

            Assert.Equal(200, viewResult.StatusCode);
        }
        public void FileNotFoundExceptionandReturns404()
        {
            var mockWalletWrapper = new Mock <IWalletManager>();

            mockWalletWrapper.Setup(wallet => wallet.LoadWallet(It.IsAny <string>(), It.IsAny <string>())).Throws <FileNotFoundException>();
            string dir        = AssureEmptyDir("TestData/ControllersTests/FileNotFoundExceptionandReturns404");
            var    dataFolder = new DataFolder(new NodeSettings {
                DataDir = dir
            });

            var controller = new WalletController(mockWalletWrapper.Object, new Mock <IWalletSyncManager>().Object, It.IsAny <ConnectionManager>(), Network.Main, new Mock <ConcurrentChain>().Object, dataFolder);

            // Act
            var result = controller.Load(new WalletLoadRequest
            {
                Name       = "myName",
                FolderPath = "",
                Password   = ""
            });

            // Assert
            mockWalletWrapper.VerifyAll();
            var viewResult = Assert.IsType <ErrorResult>(result);

            Assert.NotNull(viewResult);
            Assert.Equal(404, viewResult.StatusCode);
        }
        public void CreateWalletSuccessfullyReturnsMnemonic()
        {
            Mnemonic mnemonic         = new Mnemonic(Wordlist.English, WordCount.Twelve);
            var      mockWalletCreate = new Mock <IWalletManager>();

            mockWalletCreate.Setup(wallet => wallet.CreateWallet(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(mnemonic);

            string dir        = AssureEmptyDir("TestData/ControllersTests/CreateWalletSuccessfullyReturnsMnemonic");
            var    dataFolder = new DataFolder(new NodeSettings {
                DataDir = dir
            });

            var controller = new WalletController(mockWalletCreate.Object, new Mock <IWalletSyncManager>().Object, It.IsAny <ConnectionManager>(), Network.Main, new Mock <ConcurrentChain>().Object, dataFolder);

            // Act
            var result = controller.Create(new WalletCreationRequest
            {
                Name       = "myName",
                FolderPath = "",
                Password   = "",
                Network    = ""
            });

            // Assert
            mockWalletCreate.VerifyAll();
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Equal(mnemonic.ToString(), viewResult.Value);
            Assert.NotNull(result);
        }
Ejemplo n.º 13
0
        public void SetupBeforeEachTest()
        {
            this.accountRepository = A.Fake <IRepository <Account> >();
            this.controller        = new WalletController(this.accountRepository);
            var context = A.Fake <HttpControllerContext>();

            var configuration = A.Fake <HttpConfiguration>();
            var route         = configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary {
                { "controller", "values" }
            });

            context.Configuration = configuration;
            context.RouteData     = routeData;
            context.Controller    = controller;

            this.controller.ControllerContext = context;
            this.controller.Request           = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51018/api/values/");
            this.controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, context.Configuration);
            this.controller.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, context.RouteData);
            this.urlHelper      = A.Fake <UrlHelper>();
            this.controller.Url = this.urlHelper;
            A.CallTo(() => this.urlHelper.Link("DefaultApi", A <object> ._)).Returns("http://api/1");
        }
Ejemplo n.º 14
0
        public void CreateWalletSuccessfullyReturnsMnemonic()
        {
            Mnemonic mnemonic         = new Mnemonic(Wordlist.English, WordCount.Twelve);
            var      mockWalletCreate = new Mock <IWalletManager>();

            mockWalletCreate.Setup(wallet => wallet.CreateWallet(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), null)).Returns(mnemonic);

            var controller = new WalletController(mockWalletCreate.Object, new Mock <ITracker>().Object);

            // Act
            var result = controller.Create(new WalletCreationRequest
            {
                Name       = "myName",
                FolderPath = "",
                Password   = "",
                Network    = ""
            });

            // Assert
            mockWalletCreate.VerifyAll();
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Equal(mnemonic.ToString(), viewResult.Value);
            Assert.NotNull(result);
        }
        public async Task Initialize()
        {
            // create test user
            var user = new AppIdentityUser
            {
                Id               = "TestUser",
                UserName         = "******",
                Email            = "*****@*****.**",
                TwoFactorEnabled = true
            };

            var userManager = this._serviceProvider.GetRequiredService <UserManager <AppIdentityUser> >();
            await userManager.CreateAsync(user, "Pass@word1");

            // sign in test user
            var httpContext = this._serviceProvider.GetRequiredService <IHttpContextAccessor>().HttpContext;

            httpContext.User = new ClaimsPrincipal(
                new ClaimsIdentity(new GenericIdentity(user.Email), new[] { new Claim("ID", user.Id) }));
            httpContext.RequestServices = this._serviceProvider;

            this.walletController = new WalletController(
                this._serviceProvider.GetRequiredService <IWalletService>(),
                userManager);

            this.walletController.ControllerContext.HttpContext = httpContext;
        }
Ejemplo n.º 16
0
        //Setup
        public unit_test_walletcontroller()
        {
            //Setting up In memory dbs.
            userdb   = new SqliteConnection("DataSource=:memory:");
            passdb   = new SqliteConnection("DataSource=:memory:");
            walletdb = new SqliteConnection("DataSource=:memory:");
            userdb.Open();
            passdb.Open();
            walletdb.Open();

            //Setting up contexts.
            var userbuild = new DbContextOptionsBuilder <UserModelContext>()
                            .UseSqlite(userdb).Options;
            var passbuild = new DbContextOptionsBuilder <PassModelContext>()
                            .UseSqlite(passdb).Options;
            var walletbuild = new DbContextOptionsBuilder <WalletContext>()
                              .UseSqlite(walletdb).Options;
            var userContext   = new UserModelContext(userbuild);
            var passContext   = new PassModelContext(passbuild);
            var walletContext = new WalletContext(walletbuild);

            //Drop and create
            userContext.Database.EnsureDeleted();
            userContext.Database.EnsureCreated();
            passContext.Database.EnsureDeleted();
            passContext.Database.EnsureCreated();
            walletContext.Database.EnsureDeleted();
            walletContext.Database.EnsureCreated();
            //Seeding data to test on
            SeedUsers.seedUsers(userContext, passContext, walletContext);

            //Setting uut
            _uut = new WalletController(walletContext);
        }
Ejemplo n.º 17
0
    public static void buyItemUtilits(Items _item, float _moneyItem)
    {
        if (_moneyItem <= WalletController.getValue(ItemsType.coin))
        {
            WalletController.removeItems(ItemsType.coin, _moneyItem);

            foreach (Items _args  in DictionaryItems.listItems)
            {
                if (_args.Item == ItemsType.redCard)
                {
                    if (_item.Item == ItemsType.redCard)
                    {
                        _args.Level++;
                    }
                }
                else if (_args.Item == ItemsType.life)
                {
                    if (_item.Item == ItemsType.life)
                    {
                        _args.Level++;
                    }
                }
            }
        }
        else
        {
            WarningManager.noMoney();
        }
    }
Ejemplo n.º 18
0
 public Main()
 {
     controller = new MainController();
     wallet     = new WalletController();
     action     = new ActionController();
     InitializeComponent();
 }
Ejemplo n.º 19
0
 // Use this for initialization
 void Start()
 {
     walletController      = oyagiObject.GetComponent <WalletController>();
     atmController         = atmObject.GetComponent <ATMController>();
     timerController       = timerObject.GetComponent <GameTimerController>();
     resultLayerController = resultLayerObject.GetComponent <ResultLayerController>();
     startCash             = atmController.cash;
 }
Ejemplo n.º 20
0
 void OnTriggerEnter2D(Collider2D c)
 {
     if (c.tag == tagPullDeposit)
     {
         WalletController wallet = c.GetComponent <WalletController>();
         PullDeposit(wallet);
     }
 }
Ejemplo n.º 21
0
    public void useRedCard()
    {
        WalletController.removeRedCard();

        PlayerBehavior.Get.immunize(true);

        executionTimeManager.startManagerTime(runningTime);
    }
Ejemplo n.º 22
0
        public async Task Deposit_Deposit10_ReturnsOkAndPostDepositBalance()
        {
            //// Arrange

            decimal postDepositBalance = 15;
            Balance expectedBalance    = new Balance()
            {
                Amount = postDepositBalance
            };
            BalanceResponse expectedBalanceResponse = new BalanceResponse()
            {
                Amount = postDepositBalance
            };

            decimal        depositAmount  = 10;
            DepositRequest depositRequest = new DepositRequest {
                Amount = depositAmount
            };

            // Setup Mocks

            Mock <IWalletService> walletServiceMock = new Mock <IWalletService>();

            Deposit deposit = new Deposit {
                Amount = depositAmount
            };

            walletServiceMock
            .Setup(walletService => walletService.DepositFundsAsync(deposit))
            .Returns(Task.FromResult(expectedBalance));

            IWalletService walletService = walletServiceMock.Object;

            ILogger <WalletController> logger = Mock.Of <ILogger <WalletController> >();

            IMapper mapper = Mock.Of <IMapper>(mapper => mapper.Map <Deposit>(depositRequest) == deposit &&
                                               mapper.Map <BalanceResponse>(expectedBalance) == expectedBalanceResponse);

            // Initialize SUT

            WalletController walletController = new WalletController(logger, mapper, walletService);

            //// Act

            ActionResult <BalanceResponse> actionResult = await walletController.Deposit(depositRequest);

            ActionResult actualActionResult = actionResult.Result;

            //// Assert

            OkObjectResult  okObjectResult        = Assert.IsType <OkObjectResult>(actionResult.Result);
            BalanceResponse actualBalanceResponse = Assert.IsType <BalanceResponse>(okObjectResult.Value);

            Assert.Equal(expectedBalanceResponse, actualBalanceResponse);

            walletServiceMock.Verify(walletService => walletService.DepositFundsAsync(deposit), Times.Once);
            walletServiceMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 23
0
        public async Task Withdrawal_Withdraw20_ReturnsOkAndBalance5()
        {
            //// Arrange

            decimal postWithdrawalBalanceAmount = 5;
            Balance postWithdrawalBalance       = new Balance()
            {
                Amount = postWithdrawalBalanceAmount
            };
            BalanceResponse expectedBalanceResponse = new BalanceResponse()
            {
                Amount = postWithdrawalBalanceAmount
            };

            decimal           withdrawalAmount  = 20;
            WithdrawalRequest withdrawalRequest = new WithdrawalRequest {
                Amount = withdrawalAmount
            };

            // Setup Mocks

            Mock <IWalletService> walletServiceMock = new Mock <IWalletService>();

            Withdrawal withdrawal = new Withdrawal {
                Amount = withdrawalAmount
            };

            walletServiceMock
            .Setup(walletService => walletService.WithdrawFundsAsync(withdrawal))
            .Returns(Task.FromResult(postWithdrawalBalance));

            IWalletService walletService = walletServiceMock.Object;

            ILogger <WalletController> logger = Mock.Of <ILogger <WalletController> >();

            IMapper mapper = Mock.Of <IMapper>(mapper => mapper.Map <Withdrawal>(withdrawalRequest) == withdrawal &&
                                               mapper.Map <BalanceResponse>(postWithdrawalBalance) == expectedBalanceResponse);

            // Initialize SUT

            WalletController walletController = new WalletController(logger, mapper, walletService);

            //// Act

            ActionResult <BalanceResponse> actionResult = await walletController.Withdraw(withdrawalRequest);

            ActionResult actualActionResult = actionResult.Result;

            //// Assert

            OkObjectResult  okObjectResult        = Assert.IsType <OkObjectResult>(actionResult.Result);
            BalanceResponse actualBalanceResponse = Assert.IsType <BalanceResponse>(okObjectResult.Value);

            Assert.Equal(expectedBalanceResponse, actualBalanceResponse);

            walletServiceMock.Verify(walletService => walletService.WithdrawFundsAsync(withdrawal), Times.Once);
            walletServiceMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 24
0
        public WalletControllerTest(ContextFixture contextFixture)
        {
            var walletRepository        = new WalletRepository(contextFixture.ApiContext);
            var cryptoRepository        = new CryptoRepository(contextFixture.ApiContext);
            var emailEmailService       = new EmailService();
            var coinMarketCapApiService = new WalletOperationsService(emailEmailService);

            _walletController = new WalletController(walletRepository, cryptoRepository, coinMarketCapApiService);
        }
Ejemplo n.º 25
0
        public void AssertGeneratedWalletCredentialsVerifyWithoutPassphrase()
        {
            string   passphrase = "";           // cannot be null
            Mnemonic mnemonic   = WalletController.GenerateMnemonic(passphrase, Network.Main);

            var isVerified = WalletController.VerifyWalletCredentials(mnemonic.ToString(), passphrase, Network.Main);

            Assert.True(isVerified);
        }
Ejemplo n.º 26
0
 public PassphraseViewModel(IScreen hostScreen) : base(hostScreen)
 {
     SubmitCommand = ReactiveCommand.CreateFromObservable(() =>
     {
         var mnemonic = WalletController.GenerateMnemonic(Passphrase, Global.Network).ToString();
         HostScreen.Router.Navigate.Execute(new MnemonicViewModel(hostScreen, mnemonic)).Subscribe();
         return(Observable.Return(Unit.Default));
     });
 }
Ejemplo n.º 27
0
        public async Task Balance_GetBalanceIs4_ReturnsOkAndBalance4()
        {
            //// Arrange

            decimal currentBalanceAmount = 4;
            Balance currentBalance       = new Balance()
            {
                Amount = currentBalanceAmount
            };
            BalanceResponse expectedBalanceResponse = new BalanceResponse()
            {
                Amount = currentBalanceAmount
            };

            // Setup Mocks

            Mock <ILogger <WalletController> > loggerMock = new Mock <ILogger <WalletController> >();
            ILogger <WalletController>         logger     = loggerMock.Object;

            Mock <IMapper> mapperMock = new Mock <IMapper>();

            mapperMock
            .Setup(mapper => mapper.Map <BalanceResponse>(currentBalance))
            .Returns(expectedBalanceResponse);

            IMapper mapper = mapperMock.Object;

            Mock <IWalletService> walletServiceMock = new Mock <IWalletService>();

            walletServiceMock
            .Setup(walletService => walletService.GetBalanceAsync())
            .Returns(Task.FromResult(currentBalance));

            IWalletService walletService = walletServiceMock.Object;

            // Initialize SUT

            WalletController walletController = new WalletController(logger, mapper, walletService);

            //// Act

            ActionResult <BalanceResponse> actionResult = await walletController.Balance();

            ActionResult actualActionResult = actionResult.Result;

            /// Assert

            OkObjectResult  okObjectResult        = Assert.IsType <OkObjectResult>(actionResult.Result);
            BalanceResponse actualBalanceResponse = Assert.IsType <BalanceResponse>(okObjectResult.Value);

            Assert.Equal(expectedBalanceResponse, actualBalanceResponse);

            walletServiceMock.Verify(walletService => walletService.GetBalanceAsync(), Times.Once);
            walletServiceMock.VerifyNoOtherCalls();
        }
        public void Create_WithFunds_Via_Controller()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractNode();
                CoreNode scReceiver = builder.CreateSmartContractNode();

                builder.StartAll();

                scSender.NotInIBD();
                scReceiver.NotInIBD();

                scSender.FullNode.WalletManager().CreateWallet(Password, WalletName);
                scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName);
                HdAddress addr = scSender.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, AccountName));
                Features.Wallet.Wallet wallet = scSender.FullNode.WalletManager().GetWalletByName(WalletName);
                Key key = wallet.GetExtendedPrivateKeyForAddress(Password, addr).PrivateKey;

                scSender.SetDummyMinerSecret(new BitcoinSecret(key, scSender.FullNode.Network));
                scReceiver.SetDummyMinerSecret(new BitcoinSecret(key, scReceiver.FullNode.Network));
                var maturity = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                scSender.GenerateStratisWithMiner(maturity + 5);
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * (maturity + 5) * 50, total);

                SmartContractsController       senderSmartContractsController = scSender.FullNode.NodeService <SmartContractsController>();
                WalletController               senderWalletController         = scSender.FullNode.NodeService <WalletController>();
                SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/StorageDemo.cs");
                Assert.True(compilationResult.Success);

                var buildRequest = new BuildCreateContractTransactionRequest
                {
                    AccountName  = AccountName,
                    Amount       = "30",
                    GasLimit     = "10000",
                    GasPrice     = "1",
                    ContractCode = compilationResult.Compilation.ToHexString(),
                    FeeAmount    = "0.001",
                    Password     = Password,
                    WalletName   = WalletName,
                    Sender       = addr.Address
                };

                JsonResult result   = (JsonResult)senderSmartContractsController.BuildCreateSmartContractTransaction(buildRequest);
                var        response = (BuildCreateContractTransactionResponse)result.Value;
                scSender.CreateRPCClient().AddNode(scReceiver.Endpoint, true);

                SmartContractSharedSteps.SendTransactionAndMine(scSender, scReceiver, senderWalletController, response.Hex);

                ContractStateRepositoryRoot senderState = scSender.FullNode.NodeService <ContractStateRepositoryRoot>();
                Assert.Equal((ulong)30 * 100_000_000, senderState.GetCurrentBalance(new Address(response.NewContractAddress).ToUint160(new SmartContractsRegTest())));
            }
        }
Ejemplo n.º 29
0
 bool PullDeposit(WalletController wallet)
 {
     if (depositPullPrice <= cash)
     {
         audio.Play();
         wallet.cash = wallet.cash + depositPullPrice;
         cash        = cash - depositPullPrice;
         return(true);
     }
     return(false);
 }
Ejemplo n.º 30
0
        public void TestGetWalletInfo(long IdCode, bool expected)
        {
            var dbContext  = DbContextMocker.GetDatabaseBTCContext(string.Format("WalletInfoDatabaseBTC{0}", IdCode.ToString()));
            var controller = new WalletController(dbContext);

            var response = controller.Get(IdCode) as SaleService.Model.WalletInfo;

            dbContext.Dispose();

            Assert.Equal(expected, response != null);
        }
Ejemplo n.º 31
0
	void Awake () 
	{		
		// Singleton pattern
		if (instance == null) 
		{
			// Gameinstance related stuff here
			/************************************/
			// For static reference
			instance = this;

			// PaycastMask for ignoring the buildings
			Layer = 0;
			raycastIgnoreMask = 1 << Layer;
			raycastIgnoreMask = ~raycastIgnoreMask;

			// Instantiate all controllers
			gridFieldController = new GridFieldController();
			treeGroupController = new TreeGroupController();
			buildingController = new BuildingController();
			npcController = new NPCController();

			// Nothing opened, nothing selected!
			selectedBuilding = 123456;
			selectedNPC = 123456;
			isSelected = false;
			isBuilding = false;


			// Wallet related stuff here
			/************************************/
			// Number of wallets are determined by the number of Player Names
			// How much starting cash is given to the constructor
			walletController = new WalletController(2000);
		}
		else if(instance != this)
		{
			// Singleton pattern - destroy the new one if you want to make another GameController
			Destroy(gameObject);
		}
	}