Example #1
0
        public ContractDemo CreateAccount()
        {
            //To full the new account
            var    password           = "******";
            var    senderAddress      = "0x12890d2cce102216644c59daE5baed380d84830c";
            var    web3               = new Nethereum.Web3.Web3(new ManagedAccount(senderAddress, password));
            var    transactionPolling = new TransactionReceiptPollingService(web3);
            string path               = @"C:\Programathon\Nethereum-master\testchain\devChain\keystore\";

            //Generate a private key pair using SecureRandom
            var ecKey = Nethereum.Signer.EthECKey.GenerateKey();
            //Get the public address (derivied from the public key)
            var newAddress = ecKey.GetPublicAddress();
            var privateKey = ecKey.GetPrivateKey();

            //Create a store service, to encrypt and save the file using the web3 standard
            var service      = new KeyStoreService();
            var encryptedKey = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), newAddress);
            var fileName     = service.GenerateUTCFileName(newAddress);

            //save the File

            using (var newfile = System.IO.File.CreateText(Path.Combine(path, fileName)))
            {
                newfile.Write(encryptedKey);
                newfile.Flush();
            }


            var web3Geth     = new Web3Geth();
            var miningResult = web3Geth.Miner.Start.SendRequestAsync(6).Result;

            var currentBalance = web3.Eth.GetBalance.SendRequestAsync(newAddress).Result;
            //when sending a transaction using an Account, a raw transaction is signed and send using the private key

            var transactionReceipt = transactionPolling.SendRequestAsync(() =>
                                                                         web3.TransactionManager.SendTransactionAsync(senderAddress, newAddress, new HexBigInteger(4000000000000000000))
                                                                         ).Result;


            var newBalance = web3.Eth.GetBalance.SendRequestAsync(newAddress).Result;

            miningResult = web3Geth.Miner.Stop.SendRequestAsync().Result;


            ContractDemo d = new ContractDemo();

            d.Address = newAddress;
            return(d);
        }
        public WonkaEthERC721OpSource(string psSourceId, string psSenderAddr, string psPwd, string psContractAddr, string psCustomOpMethodName, string psWeb3Url = "") :
            base(psSourceId, psSenderAddr, psPwd, psContractAddr, null, null, psCustomOpMethodName)
        {
            var account = new Nethereum.Web3.Accounts.Account(psPwd);

            if (!String.IsNullOrEmpty(psWeb3Url))
            {
                SenderWeb3 = new Nethereum.Web3.Web3(account, psWeb3Url);
            }
            else
            {
                SenderWeb3 = new Nethereum.Web3.Web3(account);
            }
        }
Example #3
0
        /// <summary>
        /// Start a miner and get back the result. Not needed in a live environment, but we're in testrpc now
        /// </summary>
        /// <param name="web3"></param>
        /// <param name="transactionHash"></param>
        /// <returns></returns>
        private static Nethereum.RPC.Eth.DTOs.TransactionReceipt MineAndGetReceipt(Nethereum.Web3.Web3 web3, string transactionHash)
        {
            var web3Geth     = new Nethereum.Geth.Web3Geth();
            var miningResult = web3Geth.Miner.Start.SendRequestAsync(6).Result;
            var receipt      = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash).Result;

            while (receipt == null)
            {
                Thread.Sleep(1000);
                receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash).Result;
            }

            miningResult = web3Geth.Miner.Stop.SendRequestAsync().Result;
            return(receipt);
        }
Example #4
0
        private void storeTheKey()
        {
            //SQLite Db
            var databasePath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "device_key.db");
            var db = new SQLiteConnection(databasePath);
            //key
            var web3 = new Nethereum.Web3.Web3("http://ec2-52-91-125-113.compute-1.amazonaws.com:3000/");
            var ecKey = Nethereum.Signer.EthECKey.GenerateKey();
            var privateKey = ecKey.GetPrivateKeyAsBytes().ToHex();

            db.CreateTable<MobileKey>();
            var Id = db.Insert(new MobileKey()
            {
                keyId = privateKey
            });
        }
Example #5
0
        static async Task <bool> DeployContract()
        {
            //trying this with the genesis block account instead
            //var senderAddress = "0xF0FC30D327447bDa40F7081Dd3855b6901B37447";
            //var password = "******";
            var senderAddress = "0xfab5d94a10d4342026ab2abbfb928377b3acf4f9";
            var password      = "******";
            var abi           = @"[{""constant"":false,""inputs"":[{""name"":""val"",""type"":""int256""}],""name"":""multiply"",""outputs"":[{""name"":""d"",""type"":""int256""}],""payable"":false,""stateMutability"":""nonpayable"",""type"":""function""},{""inputs"":[{""name"":""multiplier"",""type"":""int256""}],""payable"":false,""stateMutability"":""nonpayable"",""type"":""constructor""}]";
            var byteCode      = "6060604052341561000f57600080fd5b6040516020806100d0833981016040528080516000555050609b806100356000396000f300606060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416631df4f14481146043575b600080fd5b3415604d57600080fd5b60566004356068565b60405190815260200160405180910390f35b60005402905600a165627a7a723058204b555172cdfdd4542892daabc7d7da51eb044d47f5bffaac484db165be55bfa80029";

            var multiplier = 7;

            var web3 = new Nethereum.Web3.Web3("http://eth002au3nds.eastus2.cloudapp.azure.com:8545");
            var unlockAccountResult = await web3.Personal.UnlockAccount.SendRequestAsync(senderAddress, password, 120);

            if (!unlockAccountResult)
            {
                throw new Exception("Unable to unlock account.");
            }

            var transactionHash = await web3.Eth.DeployContract.SendRequestAsync(abi, byteCode, senderAddress, new Nethereum.Hex.HexTypes.HexBigInteger("0xF4240"), multiplier);

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            while (receipt == null)
            {
                Thread.Sleep(5000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            var contractAddress = receipt.ContractAddress;

            var contract = web3.Eth.GetContract(abi, contractAddress);

            var multiplyFunction = contract.GetFunction("multiply");

            var result = await multiplyFunction.CallAsync <int>(7);

            if (result != 49)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Example #6
0
            //[Fact]
            public async void ShouldCheckFeeHistory()
            {
                //besu
                // var web3 = new Nethereum.Web3.Web3("http://18.116.30.130:8545/");
                //calavera
                var web3 = new Nethereum.Web3.Web3("http://18.224.51.102:8545/");
                //var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Goerli);
                var version = await new Web3ClientVersion(web3.Client).SendRequestAsync().ConfigureAwait(false);

                var x    = new TimePreferenceFeeSuggestionStrategy(web3.Client);
                var fees = await x.SuggestFeesAsync();

                //var block =
                //    await web3.Eth.FeeHistory.SendRequestAsync(7, new BlockParameter(10), new []{10,20, 30}
                //         );
                var count = fees.Length;
            }
Example #7
0
        public string ProposalsOptionsCount(int proprosalId)
        {
            var senderAddress      = "0x12890d2cce102216644c59daE5baed380d84830c";
            var password           = "******";
            var web3               = new Nethereum.Web3.Web3(new ManagedAccount(senderAddress, password));
            var transactionPolling = new TransactionReceiptPollingService(web3);



            var contract = web3.Eth.GetContract(ABI, CONTRACTADDRESS);


            var Func   = contract.GetFunction("proposalsoptionsCount");
            var result = Func.CallAsync <int>(proprosalId).Result;

            return(result.ToString());
        }
        public Nethereum.Web3.Web3 GetWeb3(string psUrl = CONST_ONLINE_TEST_CHAIN_URL)
        {
            var account = new Account(msPassword);

            Nethereum.Web3.Web3 web3 = null;

            if (!String.IsNullOrEmpty(psUrl))
            {
                web3 = new Nethereum.Web3.Web3(account, psUrl);
            }
            else
            {
                web3 = new Nethereum.Web3.Web3(account);
            }

            return(web3);
        }
Example #9
0
        public async Task ShouldBeAbleToDeployAContract()
        {
            var password = "******";
            var abi      = @"[{""constant"":false,""inputs"":[{""name"":""direcDestinatario"",""type"":""address""}],""name"":""donate"",""outputs"":[{""name"":""retorno"",""type"":""bool""}],""payable"":true,""type"":""function""}]";
            var byteCode =
                "0x6060604052341561000c57fe5b5b6101508061001c6000396000f300606060405263ffffffff60e060020a600035041662362a95811461002b5780633ccfd60b14610053575bfe5b61003f600160a060020a0360043516610065565b604080519115158252519081900360200190f35b341561005b57fe5b6100636100d0565b005b600160a060020a038116600090815260016020818152604080842080543401908190558483529084205492909152106100c65750600160a060020a0381166000908152600160208181526040808420546002909252909220919091556100ca565b5060005b5b919050565b600160a060020a033316600081815260026020818152604080842080546001845282862086905593909252908390555190929183156108fc02918491818181858888f19350505050151561012057fe5b5b505600a165627a7a723058200ca2894f66f4b6d9d95c0b0e470eebbba48b39b963c0f1911eed74050d80ab160029";

            var emisor   = "0xb6747110b8d1d0038fe250f9b9c2a0cb348fff57";
            var receptor = "0x74805a06192899214083bb0abe7efffc403a0c61";

            var web3 = new Nethereum.Web3.Web3();
            //var unlockAccountResult =
            //await web3.Personal.UnlockAccount.SendRequestAsync(receptor, password, 120);
            //Assert.True(unlockAccountResult);

            var transactionHash =
                await web3.Eth.DeployContract.SendRequestAsync(byteCode, emisor, new HexBigInteger(500000), new HexBigInteger(1));

            var mineResult = await web3.Miner.Start.SendRequestAsync(6);

            Assert.True(mineResult);

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            while (receipt == null)
            {
                Thread.Sleep(5000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            mineResult = await web3.Miner.Stop.SendRequestAsync();

            Assert.True(mineResult);

            var contractAddress = receipt.ContractAddress;

            var contract = web3.Eth.GetContract(abi, contractAddress);

            var funcionDonar = contract.GetFunction("donate");

            var hashTransaccion = await funcionDonar.SendTransactionAsync(emisor, new HexBigInteger(20), new HexBigInteger(1), new HexBigInteger(30));


            //var receibo = await MineAndGetReceiptAsync(web3, hashDonacion);
        }
Example #10
0
        private static string GetCurrentBlockNum(WonkaBizRulesEngine poEngine, string psUnusedVal)
        {
            string sCurrBlockNum = string.Empty;

            if (EngineWeb3Accounts.ContainsKey(poEngine))
            {
                Nethereum.Web3.Web3 EngineWeb3 = EngineWeb3Accounts[poEngine];

                sCurrBlockNum = EngineWeb3.Eth.Blocks.GetBlockNumber.SendRequestAsync().Result.HexValue.ToString();
            }

            if (sCurrBlockNum.HasHexPrefix())
            {
                sCurrBlockNum = sCurrBlockNum.RemoveHexPrefix();
            }

            return(sCurrBlockNum);
        }
        protected Nethereum.Contracts.Contract GetContract()
        {
            var account = new Account(BlockchainEngine.Password);

            Nethereum.Web3.Web3 web3 = null;
            if (!String.IsNullOrEmpty(msWeb3HttpUrl))
            {
                web3 = new Nethereum.Web3.Web3(account, msWeb3HttpUrl);
            }
            else
            {
                web3 = new Nethereum.Web3.Web3(account);
            }

            var contract = web3.Eth.GetContract(BlockchainEngine.ContractABI, BlockchainEngine.ContractAddress);

            return(contract);
        }
Example #12
0
        // Send balance request using Web3, note that Web3 uses Task and await
        private async Task GetBalanceByWeb3(string address, UnityAction <decimal> callback)
        {
            Debug.Log("StaticWalletBalance:GetBalanceByWeb3()");
            // Create a Web3 object using Nethereum lib
            var web3 = new Nethereum.Web3.Web3(WalletSettings.current.networkUrl);
            // Use GetBalance request
            var balance = await web3.Eth.GetBalance.SendRequestAsync(address);

            Debug.Log("StaticWalletBalance:GetBalanceByWeb3 - balance returned");


            var web3geth = new Nethereum.Geth.Web3Geth(WalletSettings.current.networkUrl);
            var result   = await web3geth.Miner.Start.SendRequestAsync();

            Debug.Log(result);

            callback(Nethereum.Util.UnitConversion.Convert.FromWei(balance, 18));
        }
Example #13
0
        public async Task <TransactionReceipt> MineAndGetReceiptAsync(Nethereum.Web3.Web3 web3, string transactionHash)
        {
            var result = await web3.Miner.SetGasPrice.SendRequestAsync(new Nethereum.Hex.HexTypes.HexBigInteger("0x3d0900"));

            var miningResult = await web3.Miner.Start.SendRequestAsync();

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            while (receipt == null)
            {
                Thread.Sleep(1000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            miningResult = await web3.Miner.Stop.SendRequestAsync();

            return(receipt);
        }
Example #14
0
        public Nethereum.Contracts.Contract GetContract(WonkaBizSource TargetSource)
        {
            var account = new Account(TargetSource.Password);

            Nethereum.Web3.Web3 web3 = null;
            if ((moOrchInitData != null) && !String.IsNullOrEmpty(moOrchInitData.Web3HttpUrl))
            {
                web3 = new Nethereum.Web3.Web3(account, moOrchInitData.Web3HttpUrl);
            }
            else
            {
                web3 = new Nethereum.Web3.Web3(account);
            }

            var contract = web3.Eth.GetContract(TargetSource.ContractABI, TargetSource.ContractAddress);

            return(contract);
        }
Example #15
0
        public async Task <TransactionReceipt> MineAndGetReceiptAsync(Nethereum.Web3.Web3 web3, string transactionHash)
        {
            var web3Geth = new Web3Geth();

            var miningResult = await web3Geth.Miner.Start.SendRequestAsync(6);

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            while (receipt == null)
            {
                Thread.Sleep(1000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            miningResult = await web3Geth.Miner.Stop.SendRequestAsync();

            return(receipt);
        }
        public async Task <IActionResult> Index()
        {
            HomeViewModel viewModel = new HomeViewModel();

            Nethereum.Web3.Web3 web3 = new Nethereum.Web3.Web3("http://192.168.0.103:8545");
            var accounts             = await web3.Personal.ListAccounts.SendRequestAsync();

            foreach (var account in accounts)
            {
                Models.AccountViewModel accountViewModel = new Models.AccountViewModel()
                {
                    Account = account
                };
                viewModel.Accounts.Add(accountViewModel);
            }

            return(View(viewModel));
        }
Example #17
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Welcome to the CoffeeChain Wallet Application.");
            Console.WriteLine("==============================================");

            Console.WriteLine("Bootstrapping Nethereum...");

            //var password =  Console.ReadLine();
            var password = PassPhrase;

            var account = Account.LoadFromKeyStore(KeyFile, password);

            var web3 = new Nethereum.Web3.Web3(account, "http://192.168.1.166:30304");
            var coffeeEconomyService = new CoffeeEconomyService(account, web3, ContractAddress);
            var console = new ConsoleService(web3, coffeeEconomyService);

            await console.Handle();
        }
        public async Task ShouldBeAbleToDeployAContract()
        {
            var senderAddress = "";
            var password      = "******";
            var abi           = @"[{""constant"":false,""inputs"":[{""name"":""val"",""type"":""int256""}],""name"":""multiply"",""outputs"":[{""name"":""d"",""type"":""int256""}],""type"":""function""},{""inputs"":[{""name"":""multiplier"",""type"":""int256""}],""type"":""constructor""}]";
            var byteCode      =
                "0x60606040526040516020806052833950608060405251600081905550602b8060276000396000f3606060405260e060020a60003504631df4f1448114601a575b005b600054600435026060908152602090f3";

            var multiplier = 7;

            var web3 = new Nethereum.Web3.Web3();
            //var unlockAccountResult =
            //await web3.Personal.UnlockAccount.SendRequestAsync(senderAddress, password, 120);
            //Assert.True(unlockAccountResult);

            var transactionHash =
                await web3.Eth.DeployContract.SendRequestAsync(abi, byteCode, senderAddress, multiplier);

            var mineResult = await web3.Miner.Start.SendRequestAsync(6);

            Assert.True(mineResult);

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            while (receipt == null)
            {
                Thread.Sleep(5000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            mineResult = await web3.Miner.Stop.SendRequestAsync();

            Assert.True(mineResult);

            var contractAddress = receipt.ContractAddress;

            var contract = web3.Eth.GetContract(abi, contractAddress);

            var multiplyFunction = contract.GetFunction("multiply");

            var result = await multiplyFunction.CallAsync <int>(7);

            Assert.Equal(49, result);
        }
Example #19
0
        public async System.Threading.Tasks.Task <ActionResult> Index()
        {
            //AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();

            try
            {
                //var keyVaultClient = new KeyVaultClient(
                //    new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

                //var secret = await keyVaultClient.GetSecretAsync("https://kv6.vault.azure.net/secrets/secret")
                //    .ConfigureAwait(false);

                //var secrets = await keyVaultClient.GetSecretsAsync("https://kv1mert.vault.azure.net/");



                //await keyVaultClient.SetSecretAsync("https://kv1mert.vault.azure.net/", "test2", "oley");
                //var secret2 = await keyVaultClient.GetSecretAsync("https://kv6.vault.azure.net/secrets/test2");
                // var secret = await keyVaultClient.GetSecretAsync("https://kv61.vault.azure.net/secrets/test/234584487ce449c482e75b46a5837a80");
                //ViewBag.Secret = $"Secret: {secrets.First().Id} + {secrets.ElementAt(1).Id}";
                //ViewBag.Secret2 = $"Secret: {secret2.Value}";
                //var ecKey = Nethereum.Signer.EthECKey.GenerateKey();
                //var privateKey = ecKey.GetPrivateKeyAsBytes().ToHex();
                //Nethereum.Web3.Accounts.Account account = new Nethereum.Web3.Accounts.Account("0x7b6612e69adf30b586aec352010cc521b241e85ba72369fb922c2cf654b18762");
                var senderAddress = "0x611F4b562CdBDB23cD1d474A7b8047d3eaF9E929";
                var password      = "******";

                var account = new ManagedAccount(senderAddress, password);
                //var web3 = new Web3.Web3(account);
                var web3 = new Nethereum.Web3.Web3("http://ethdacaxlaox.eastus.cloudapp.azure.com:8545/");
                //web3.Eth.DeployContract.SendRequestAsync()
                var t = await web3.TransactionManager.SendTransactionAsync(account.Address, "0x087fa189f4749a879e1282863e7dbda280f7f0cb", new HexBigInteger(20));

                ViewBag.Secret = t;
            }
            catch (Exception exp)
            {
                ViewBag.Error = $"Something went wrong: {exp}";
            }

            //ViewBag.Principal = azureServiceTokenProvider.PrincipalUsed != null ? $"Principal Used: {azureServiceTokenProvider.PrincipalUsed}" : string.Empty;
            return(View());
        }
        public async void Test1()
        {
            string consentDirectSmartContractAddress = "0x8a3239306c13ca56c1d73f883e77fcdd9682cb0f";
            string consentDirectAccount = "0x42c3b5107df5cb714f883ecaf4896f69d2b06a67";

            var web3 = new Nethereum.Web3.Web3(); // localhost 8545
            var cds  = new ConsentDirectService(web3, consentDirectSmartContractAddress);

            string subjectAddress = "0x47d6bb71fbdc161794ac6d4db623da7c8de24e31";
            bool   success        = await cds.RegisterSubject(
                senderAddress : consentDirectAccount,
                subjectAddress : subjectAddress,
                emailhash : "0x7c492afa7e42bf537557c3cdf470fc843ddc532d72f6fae27a755f74115fb557"
                );

            Assert.True(success);

            success = await cds.SubjectHasRegistered(subjectAddress : "0x6d65dea4846bdbc12ee458c607bc078161689607");
        }
Example #21
0
        public string AddVoteToProposalv2(int proposalId, int optionId, string userSenderAddress)
        {
            //userSenderAddress = "0x12890d2cce102216644c59daE5baed380d84830c";
            var password           = "******";
            var web3               = new Nethereum.Web3.Web3(new ManagedAccount(userSenderAddress, password));
            var transactionPolling = new TransactionReceiptPollingService(web3);



            var contract = web3.Eth.GetContract(ABI, CONTRACTADDRESS);

            var Func      = contract.GetFunction("addVoteToProposalv2");
            var Event     = contract.GetEvent("Voted");
            var filterAll = Event.CreateFilterAsync().Result;

            var unlockResult = web3.Personal.UnlockAccount.SendRequestAsync(userSenderAddress, password, 60).Result;

            web3.TransactionManager.DefaultGas      = BigInteger.Parse("4000000");
            web3.TransactionManager.DefaultGasPrice = BigInteger.Parse("4000000");

            var resultPro  = Func.SendTransactionAsync(userSenderAddress, proposalId, optionId).Result;
            var resultTran = MineAndGetReceiptAsync(web3, resultPro).Result;


            var log = Event.GetFilterChanges <VotedEvent>(filterAll).Result;



            if (log.Count > 0)
            {
                string message = string.Empty;
                for (int i = 0; i < log.Count; i++)
                {
                    message += log[i].Event.Result.ToString();
                    message += " / ";
                }
                return(message);
            }
            else
            {
                return("No hay respuesta");
            }
        }
        private async Task DrainPoolItem(AccountPoolItem poolItem)
        {
            if (poolItem == null)
            {
                return;
            }

            if (poolItem.IsProcessed)
            {
                return;
            }

            if (string.IsNullOrEmpty(drainAddress))
            {
                return;
            }

            if (!string.Equals(poolItem.CurrencyName, CurrencyCode, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (poolItem.Balance > drainValue && poolItem.Balance > drainLimit)
            {
                try
                {
                    var web3 = new Nethereum.Web3.Web3(gethNodeAddress);

                    var sendBalance = Converter.DecimalToAtomicUnit(poolItem.Balance - drainLimit);

                    await web3.Personal.UnlockAccount.SendRequestAsync(poolItem.Address, defaultAccountPassword, AccountUnlockDurationInSeconds).ConfigureAwait(false);

                    await web3.TransactionManager.SendTransactionAsync(poolItem.Address, drainAddress, sendBalance).ConfigureAwait(false);

                    await addressPool.ClearBalance(poolItem.Address).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Failed to DrainPoolItem");
                }
            }
        }
Example #23
0
        public async Task <IActionResult> Post([FromBody] InitAccountRequest initRequest)
        {
            if (string.IsNullOrEmpty(initRequest?.Address))
            {
                return(BadRequest());
            }

            var userId = new Guid(User.Claims.Single(cl => cl.Type == ClaimTypes.NameIdentifier).Value);
            var player = _context.Players.Single(x => x.Id == userId);

            player.Address = initRequest.Address;
            await _context.SaveChangesAsync();

            var web3 = new Nethereum.Web3.Web3(_account.Value.Address);

            var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(_account.Value.MasterAccountAddress);

            var encoded = web3.OfflineTransactionSigner.SignTransaction(_account.Value.MasterAccountPrivateKey, initRequest.Address, 10, txCount.Value);

            return(Ok(await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded)));
        }
Example #24
0
        public async Task <IActionResult> Confirm(string token)
        {
            try
            {
                // Confirm that the token exists and retrieve the emailhash and account
                var _firebaseDBRegistrationToken = _firebaseDBRegistrations.Node(token);
                FirebaseResponse resp            = _firebaseDBRegistrationToken.Get();

                if (!resp.Success)
                {
                    var sr = new StandardResponse();
                    sr.Success      = false;
                    sr.ErrorMessage = $"Could not retrieve token {token}";
                    return(StatusCode(500, value: sr));
                }

                var subjectDetails = JsonConvert.DeserializeObject <DataSubject>(resp.JSONContent);

                // register the subject into the Consent Direct smart contract
                var web3 = new Nethereum.Web3.Web3(_configuration["Ethereum:Provider"]);
                var cds  = new ConsentDirectService(web3, _configuration["Ethereum:SmartContracts:Consent.Direct:address"]);

                bool success = await cds.RegisterSubject(_configuration["Ethereum:Accounts:Consent.Direct"], subjectDetails.Account, subjectDetails.EmailHash);

                if (success)
                {
                    // Remove the registration token information from temp storage
                    resp = _firebaseDBRegistrationToken.Delete();
                }
                else
                {
                    throw new Exception("Could not confirm registration because the DataSubject registration failed");
                }
                return(Ok(resp));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, value: ex));
            }
        }
Example #25
0
        public async Task <(string, DateTime)> CriarTransacoesAsync(string hashDoArquivo, string assJwt)
        {
            var senderAddress = "0x3c30BdDA887BeE28e6D09F801E3f6B0E7AE876F6";
            var client        = new Nethereum.JsonRpc.Client.RpcClient(new Uri("https://ropsten.infura.io/v3/69d76e2ed4cf459091d6113d9f18b0c0"));
            var account       = new Nethereum.Web3.Accounts.Account("5C634792510B7D93283FA4A03D6B396CEECE19E860BF0E0632C54BE513B10259");
            var web3          = new Nethereum.Web3.Web3(account, client);

            var contractAddress = "0xF6676908F5E3580C7bFF689dF739D843607DBc6c";
            var abi             = @"[{'constant':false,'inputs':[{'name':'hashArquivo','type':'string'},{'name':'assinatura','type':'string'}],'name':'adicionarAssinatura','outputs':[],'payable':false,'stateMutability':'nonpayable','type':'function'},{'constant':false,'inputs':[{'name':'hashArquivo','type':'string'}],'name':'removerAssinatura','outputs':[],'payable':false,'stateMutability':'nonpayable','type':'function'},{'constant':false,'inputs':[],'name':'removeSdaContract','outputs':[],'payable':false,'stateMutability':'nonpayable','type':'function'},{'constant':true,'inputs':[],'name':'empresa','outputs':[{'name':'','type':'string'}],'payable':false,'stateMutability':'view','type':'function'},{'constant':true,'inputs':[{'name':'hashArquivo','type':'string'}],'name':'buscarAssinatura','outputs':[{'name':'','type':'string'}],'payable':false,'stateMutability':'view','type':'function'},{'inputs':[{'name':'_empresa','type':'string'}],'payable':false,'stateMutability':'nonpayable','type':'constructor'},{'anonymous':false,'inputs':[{'indexed':true,'name':'hashArquivo','type':'string'},{'indexed':true,'name':'assinatura','type':'string'},{'indexed':false,'name':'datahora','type':'uint256'}],'name':'AssinaturaAdicionada','type':'event'}]";

            var contract = web3.Eth.GetContract(abi, contractAddress);
            var adicionarAssinaturaFunc = contract.GetFunction("adicionarAssinatura");

            try
            {
                var trx = await adicionarAssinaturaFunc.SendTransactionAsync(
                    senderAddress,
                    new HexBigInteger(900000),
                    new HexBigInteger(1000),
                    new HexBigInteger(0),
                    hashDoArquivo,
                    assJwt);

                // Verificar se já foi processada

                Nethereum.RPC.Eth.DTOs.TransactionReceipt receiptAdd = null;
                while (receiptAdd == null)
                {
                    receiptAdd = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(trx);

                    System.Threading.Thread.Sleep(1000);
                }

                return(trx, DateTime.Now);
            }
            catch (Exception ex)
            {
                return(string.Empty, DateTime.Now);
            }
        }
Example #26
0
        async Task PayToServiceProvider(Exchange exchange)
        {
            if (exchange.OutTxId != null)
            {
                throw new ApiException(ErrorCode.PaymentAlreadyMade);
            }
            exchange.OutTxId = string.Empty;

            try
            {
                var web3 = new Nethereum.Web3.Web3(new Account(_settings.EthereumPrivatekey), _settings.EthereumUrl);

                var transactionMessage = new TransferFunction()
                {
                    FromAddress = _settings.EthereumAddress,
                    To          = exchange.BuyerWallet,// receiverAddress,
                    TokenAmount = (BigInteger)exchange.BuyAmount,
                    GasPrice    = Nethereum.Web3.Web3.Convert.ToWei(25, UnitConversion.EthUnit.Gwei)
                };

                var transferHandler = web3.Eth.GetContractTransactionHandler <TransferFunction>();

                var estimate = await transferHandler.EstimateGasAsync(_settings.StableCoinContractAddress, transactionMessage);

                transactionMessage.Gas = estimate.Value;

                var transactionHash = await transferHandler.SendRequestAsync(_settings.StableCoinContractAddress, transactionMessage);

                //exchange.Status = PaymentStatus.Received;
                exchange.OutTxStatus = PaymentStatus.Confirmed;
                exchange.OutTxId     = transactionHash;
            }
            catch (Exception ex)
            {
                exchange.OutTxId                = null;
                exchange.OutTxStatus            = PaymentStatus.Fail;
                exchange.OutTxStatusDescription = ex.Message;
            }
        }
Example #27
0
        public string DeployWonkaContract()
        {
            string sSenderAddress   = msSenderAddress;
            string sContractAddress = "blah";

            var account = new Account(msPassword);

            Nethereum.Web3.Web3 web3 = null;
            if ((moOrchInitData != null) && !String.IsNullOrEmpty(moOrchInitData.Web3HttpUrl))
            {
                web3 = new Nethereum.Web3.Web3(account, moOrchInitData.Web3HttpUrl);
            }
            else
            {
                web3 = new Nethereum.Web3.Web3(account);
            }

            System.Numerics.BigInteger totalSupply = System.Numerics.BigInteger.Parse("10000000");

            /**
            ** NOTE: Deployment issues have not yet been resolved - more work needs to be done
            **
            ** // System.Exception: Too many arguments: 1 > 0
            ** // at Nethereum.ABI.FunctionEncoding.ParametersEncoder.EncodeParameters (Nethereum.ABI.Model.Parameter[] parameters, System.Object[] values) [0x00078] in <b4e1e3b6a7e947da9576619c2d31bafc>:0
            ** // var receipt =
            ** // web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(msAbiWonka, msByteCodeWonka, sSenderAddress, new Nethereum.Hex.HexTypes.HexBigInteger(900000), null, totalSupply).Result;
            ** // sContractAddress = receipt.ContractAddress;
            **
            ** // var unlockReceipt = web3.Personal.UnlockAccount.SendRequestAsync(sSenderAddress, msPassword, 120).Result;
            **
            ** // base fee exceeds gas limit?
            ** // https://gitter.im/Nethereum/Nethereum?at=5a15318e540c78242d34505f
            ** // sContractAddress = web3.Eth.DeployContract.SendRequestAsync(msAbiWonka, msByteCodeWonka, sSenderAddress, new Nethereum.Hex.HexTypes.HexBigInteger(totalSupply)).Result;
            **
            **/

            return(sContractAddress);
        }
        private async Task <string> CreateNewAccount()
        {
            string result = null;

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    var web3 = new Nethereum.Web3.Web3(gethNodeAddress);
                    result = await web3.Personal.NewAccount.SendRequestAsync(defaultAccountPassword);

                    break;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Failed to CreateNewAccount");
                }

                await Task.Delay(5000);
            }

            return(result);
        }
Example #29
0
        /// <summary>
        ///
        /// This method will register the default set of standard operations (especially Nethereum-related ones) that can be
        /// invoked from within the Wonka rules engine
        ///
        /// <param name="poEngine">The target instance of an engine</param>
        /// <returns>None</returns>
        /// </summary>
        public static void SetDefaultStdOps(this WonkaBizRulesEngine poEngine, string psPassword, string psWeb3HttpUrl = null)
        {
            var account = new Account(psPassword);

            Nethereum.Web3.Web3 web3 = null;
            if (!String.IsNullOrEmpty(psWeb3HttpUrl))
            {
                web3 = new Nethereum.Web3.Web3(account, psWeb3HttpUrl);
            }
            else
            {
                web3 = new Nethereum.Web3.Web3(account);
            }

            EngineWeb3Accounts[poEngine] = web3;

            Dictionary <STD_OP_TYPE, WonkaBizRulesEngine.RetrieveStdOpValDelegate> DefaultStdOpMap =
                new Dictionary <STD_OP_TYPE, WonkaBizRulesEngine.RetrieveStdOpValDelegate>();

            DefaultStdOpMap[STD_OP_TYPE.STD_OP_BLOCK_NUM] = GetCurrentBlockNum;

            poEngine.StdOpMap = DefaultStdOpMap;
        }
Example #30
0
        /// <summary>
        ///
        /// NOTE: UNDER CONSTRUCTION
        ///
        /// This method will log the Wonka Report to an instance of the ChronoLog contract.
        ///
        /// <param name=""></param>
        /// <returns></returns>
        /// </summary>
        public static async Task <string> WriteToChronoLog(this Wonka.Eth.Extensions.RuleTreeReport poReport,
                                                           Wonka.Eth.Init.WonkaEthEngineInitialization poEngineInitData,
                                                           string psChronoLogContractAddr,
                                                           AddChronoLogEventFunction poAddChronoLogEventFunction)
        {
            var account = new Nethereum.Web3.Accounts.Account(poEngineInitData.EthPassword);

            Nethereum.Web3.Web3 SenderWeb3;

            if (!String.IsNullOrEmpty(poEngineInitData.Web3HttpUrl))
            {
                SenderWeb3 = new Nethereum.Web3.Web3(account, poEngineInitData.Web3HttpUrl);
            }
            else
            {
                SenderWeb3 = new Nethereum.Web3.Web3(account);
            }

            var addLogHandler = SenderWeb3.Eth.GetContractTransactionHandler <AddChronoLogEventFunction>();

            var receipt = await addLogHandler.SendRequestAndWaitForReceiptAsync(psChronoLogContractAddr, poAddChronoLogEventFunction);

            return(receipt.TransactionHash);
        }
Example #31
0
        public async void Test()
        {
           
                var contractByteCode =
                    "0x60606040526040516020806106f5833981016040528080519060200190919050505b80600160005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005081905550806000600050819055505b506106868061006f6000396000f360606040523615610074576000357c010000000000000000000000000000000000000000000000000000000090048063095ea7b31461008157806318160ddd146100b657806323b872dd146100d957806370a0823114610117578063a9059cbb14610143578063dd62ed3e1461017857610074565b61007f5b610002565b565b005b6100a060048080359060200190919080359060200190919050506101ad565b6040518082815260200191505060405180910390f35b6100c36004805050610674565b6040518082815260200191505060405180910390f35b6101016004808035906020019091908035906020019091908035906020019091905050610281565b6040518082815260200191505060405180910390f35b61012d600480803590602001909190505061048d565b6040518082815260200191505060405180910390f35b61016260048080359060200190919080359060200190919050506104cb565b6040518082815260200191505060405180910390f35b610197600480803590602001909190803590602001909190505061060b565b6040518082815260200191505060405180910390f35b600081600260005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060008573ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905061027b565b92915050565b600081600160005060008673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050541015801561031b575081600260005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060003373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000505410155b80156103275750600082115b1561047c5781600160005060008573ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505401925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a381600160005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282825054039250508190555081600260005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060003373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505403925050819055506001905061048656610485565b60009050610486565b5b9392505050565b6000600160005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000505490506104c6565b919050565b600081600160005060003373ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050541015801561050c5750600082115b156105fb5781600160005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282825054039250508190555081600160005060008573ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905061060556610604565b60009050610605565b5b92915050565b6000600260005060008473ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060008373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005054905061066e565b92915050565b60006000600050549050610683565b9056";
                var abi =
                    @"[{""constant"":false,""inputs"":[{""name"":""_spender"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""approve"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[],""name"":""totalSupply"",""outputs"":[{""name"":""supply"",""type"":""uint256""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_from"",""type"":""address""},{""name"":""_to"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""transferFrom"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""name"":""balance"",""type"":""uint256""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_to"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""transfer"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""},{""name"":""_spender"",""type"":""address""}],""name"":""allowance"",""outputs"":[{""name"":""remaining"",""type"":""uint256""}],""type"":""function""},{""inputs"":[{""name"":""_initialAmount"",""type"":""uint256""}],""type"":""constructor""},{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_from"",""type"":""address""},{""indexed"":true,""name"":""_to"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Transfer"",""type"":""event""},{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_owner"",""type"":""address""},{""indexed"":true,""name"":""_spender"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Approval"",""type"":""event""}]";
                var addressOwner = "0x12890d2cce102216644c59dae5baed380d84830c";

                var web3 = new Nethereum.Web3.Web3(ClientFactory.GetClient());
            try
            {
                var eth = web3.Eth;
                var transactions = eth.Transactions;
                ulong totalSupply = 1000000;

                var pass = "******";
                var result =
                    await web3.Personal.UnlockAccount.SendRequestAsync(addressOwner, pass, new HexBigInteger(600));
                Assert.True(result, "Account should be unlocked");
                var newAddress = await web3.Personal.NewAccount.SendRequestAsync(pass);

                Assert.NotNull(newAddress);
                Console.WriteLine(newAddress);

                var transactionHash =
                    await
                        eth.DeployContract.SendRequestAsync(abi, contractByteCode, addressOwner,
                            new HexBigInteger(900000), totalSupply);

                result = await web3.Miner.Start.SendRequestAsync();
                Assert.True(result, "Mining should have started");

                //get the contract address 
                var receipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                var code = await web3.Eth.GetCode.SendRequestAsync(receipt.ContractAddress);

                if (String.IsNullOrEmpty(code))
                {
                    throw new Exception(
                        "Code was not deployed correctly, verify bytecode or enough gas was uto deploy the contract");
                }

                var tokenService = new StandardTokenService(web3, receipt.ContractAddress);

                var transfersEvent = tokenService.GetTransferEvent();
              

                var totalSupplyDeployed = await tokenService.GetTotalSupplyAsync<ulong>();
                Assert.Equal(totalSupply, totalSupplyDeployed);

                var ownerBalance = await tokenService.GetBalanceOfAsync<ulong>(addressOwner);
                Assert.Equal(totalSupply, ownerBalance);

               transactionHash = await tokenService.TransferAsync(addressOwner, newAddress, 1000);
              
               var transferReceipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                ownerBalance = await tokenService.GetBalanceOfAsync<ulong>(addressOwner);
                Assert.Equal(totalSupply - 1000, ownerBalance);

                var newAddressBalance = await tokenService.GetBalanceOfAsync<ulong>(newAddress);
                Assert.Equal((ulong) 1000, newAddressBalance);

                var allTransfersFilter = await transfersEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber));
                var eventLogsAll = await transfersEvent.GetAllChanges<Transfer>(allTransfersFilter);
                Assert.Equal(1, eventLogsAll.Count);
                var transferLog = eventLogsAll.First();
                Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue);
                Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue);
                Assert.Equal(transferLog.Event.AddressTo, newAddress);
                Assert.Equal(transferLog.Event.Value, (ulong)1000);

            }
            finally
            {
                var result = await web3.Miner.Stop.SendRequestAsync();
                Assert.True(result, "Mining should have stop");
                result = await web3.Personal.LockAccount.SendRequestAsync(addressOwner);
                Assert.True(result, "Account should be locked");
            }
           
        }