public async Task <HexBigInteger> GetNonceAsync(string fromAddress, bool checkTxPool) { if (checkTxPool) { var txPool = await _client.SendRequestAsync <JObject>(new RpcRequest($"{Guid.NewGuid()}", "txpool_inspect")); var maxNonce = txPool["pending"] .Cast <JProperty>() .FirstOrDefault(x => x.Name.Equals(fromAddress, StringComparison.OrdinalIgnoreCase))? .FirstOrDefault()? .Cast <JProperty>() .Select(x => long.Parse(x.Name)) .Max(); if (maxNonce.HasValue) { return(new HexBigInteger(new BigInteger(maxNonce.Value + 1))); } } return(await _getTransactionCount.SendRequestAsync(fromAddress, BlockParameter.CreatePending())); }
public static async Task <List <string> > Exchangetoken(string PrivateKey, CoinType TokenTo, float Value) { //get the function from meaktoken var function_meakToken = meaToken.Contract.GetFunction("transfer"); var dataM = function_meakToken.GetData(new object[] { accountA, new BigInteger(Value) }); // if (TokenTo.Equals(CoinType.CoinB)) // { //get fthe function from tokenB var function_tokenB = tokenB.Contract.GetFunction("transfer"); var dataB = function_tokenB.GetData(new object[] { EthECKey.GetPublicAddress(PrivateKey), new BigInteger(Value) }); // } var txCountM = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(EthECKey.GetPublicAddress(PrivateKey), BlockParameter.CreatePending()); var txCountB = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(accountB, BlockParameter.CreatePending()); var encodedM = transactionSigner.SignTransaction(PrivateKey, meaToken.Contract.Address, 0, txCountM.Value, 1000000000000L, 900000, dataM); var encodedB = transactionSigner.SignTransaction(accountB_privateKey, TokenB_Contract_Address, 0, txCountB.Value, 1000000000000L, 900000, dataB); var txIdM = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encodedM); var txIdB = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encodedB); var statusM = transactionSigner.VerifyTransaction(encodedM); var statusB = transactionSigner.VerifyTransaction(encodedB); List <string> res = new List <string>(); res.Add(txIdM); res.Add(txIdB); return(res); }
/////////////////////////////////////////////////////////////////////////////////////// public static async Task <string> SendToken(string PrivateKeyFrom, string PublicKeyTo, float value) { //get the function var function = meaToken.Contract.GetFunction("transfer"); //get the data var data = function.GetData(new object[] { PublicKeyTo, new BigInteger(value) }); // var estimatedGaz = await function.EstimateGasAsync(new object[] { PublicKeyTo, new BigInteger(value) }); //Console.WriteLine("Estimated Gaz : " + estimatedGaz); //nonce var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(EthECKey.GetPublicAddress(PrivateKeyFrom), BlockParameter.CreatePending()); //signing the transaction var encoded = transactionSigner.SignTransaction(PrivateKeyFrom, meaToken.Contract.Address, 1, txCount.Value, 1000000000000L, 900000, data); //estimate gaz var GasEstimated = await web3.Eth.TransactionManager.EstimateGasAsync(new CallInput("0x" + encoded, PublicKeyTo)); Console.WriteLine("Estimated Gas is : " + GasEstimated.Value.ToString()); Console.WriteLine("My balance : " + web3.Eth.GetBalance.SendRequestAsync(EthECKey.GetPublicAddress(PrivateKeyFrom)).Result.Value.ToString()); //transaction hash var bal = await get_MeaToken_Account_Balance(EthECKey.GetPublicAddress(PrivateKeyFrom)); Console.WriteLine("bal : " + bal); var txId = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded); //verify transaction var status = transactionSigner.VerifyTransaction(encoded); Console.WriteLine("Status : " + status); //returning transaction hash isMined(txId); return(txId); }
public async Task <OperationEstimationV2Result> EstimateTransactionExecutionCostAsync( string fromAddress, string toAddress, BigInteger amount, BigInteger gasPrice, string transactionData) { var fromAddressBalance = await _web3.Eth.GetBalance.SendRequestAsync(fromAddress, BlockParameter.CreatePending()); //var currentGasPrice = await _web3.Eth.GasPrice.SendRequestAsync(); var value = new HexBigInteger(amount); CallInput callInput; HexBigInteger estimatedGas; bool isAllowed = true; callInput = new CallInput(transactionData, toAddress, value); callInput.From = fromAddress; try { //Throws on wrong call if (await IsSmartContracAsync(toAddress)) { var callResult = await _web3.Eth.Transactions.Call.SendRequestAsync(callInput); //Get amount of gas for smart contract execution estimatedGas = await _web3.Eth.Transactions.EstimateGas.SendRequestAsync(callInput); } else { estimatedGas = new HexBigInteger(Lykke.Service.EthereumCore.Core.Constants.DefaultTransactionGas); } //Recalculate transaction eth Amount var diff = fromAddressBalance - (amount + estimatedGas.Value * gasPrice); if (diff < 0) { amount += diff; } if (string.IsNullOrEmpty(transactionData)) { if (amount <= 0) { throw new ClientSideException(ExceptionType.NotEnoughFunds, $"Not enough Ethereum on {fromAddress}"); } } else if (diff < 0) { throw new ClientSideException(ExceptionType.NotEnoughFunds, $"Not enough Ethereum on {fromAddress}"); } callInput.Value = new HexBigInteger(amount); callInput.GasPrice = new HexBigInteger(gasPrice); //reestimate with new arguments estimatedGas = await _web3.Eth.Transactions.EstimateGas.SendRequestAsync(callInput); } catch (Nethereum.JsonRpc.Client.RpcResponseException rpcException) { var rpcError = rpcException?.RpcError; if (rpcError != null && rpcError.Code == -32000) { estimatedGas = new HexBigInteger(0); isAllowed = false; } else { throw new ClientSideException(ExceptionType.CantEstimateExecution, rpcException.Message); } } catch (ClientSideException e) { throw; } catch (Exception e) { throw new ClientSideException(ExceptionType.None, e.Message); } return(new OperationEstimationV2Result() { GasAmount = estimatedGas.Value, GasPrice = gasPrice, EthAmount = amount, IsAllowed = isAllowed }); }
private static void ShowPendingTransactionsAmount() { var web3 = ServiceProvider.GetService <Web3>(); var block = web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(BlockParameter.CreatePending()).Result; var transactionsCount = block.Transactions.Count(); Console.WriteLine($"Transactions Count = {transactionsCount}"); }
public async Task PrivateWalletServiceTest_GetPendingTransactions() { var block = await _web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(BlockParameter.CreatePending()); foreach (var transaction in block.Transactions) { Trace.TraceInformation($"from: {transaction.From} - trHash: {transaction.TransactionHash}"); } }
public IEnumerator LogsGetAllChangesFilteredTest() { return(testContext.ContractTest(async() => { BroadcastTxResult firstEvent1Result = await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", 1); await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", 2); await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", 3); EvmEvent <EvmTestContext.TestIndexedEvent1> event1 = this.testContext.Contract.GetEvent <EvmTestContext.TestIndexedEvent1>("TestIndexedEvent1"); NewFilterInput filterInput = event1.EventAbi.CreateFilterInput(2, new BlockParameter(firstEvent1Result.Height), BlockParameter.CreatePending()); List <EventLog <EvmTestContext.TestIndexedEvent1> > decodedEvents = await event1.GetAllChanges(filterInput); Assert.NotZero(decodedEvents.Count); decodedEvents.ForEach(log => Assert.AreEqual((BigInteger)2, log.Event.Number1)); Debug.Log(JsonConvert.SerializeObject(decodedEvents, Formatting.Indented)); }, 20000)); }
public async Task <TransactionReturnInfo> CreateTransactionAsync(string ContractAddress, ContractInfo contractInfo, string FunctionName, Account account, object[] inputParams = null, List <string> PrivateFor = null) { if (web3 == null) { throw new Exception("web3 handler has not been set - please call SetWeb3Handler First"); } if (PrivateFor != null && PrivateFor?.Count != 0) { web3.ClearPrivateForRequestParameters(); web3.SetPrivateRequestParameters(PrivateFor); } var contract = web3.Eth.GetContract(contractInfo.ContractABI, ContractAddress); if (contract == null) { throw new Exception("Could not find contract with ABI at specified address"); } var contractFunction = contract.GetFunction(FunctionName); if (contractFunction == null) { throw new Exception("Could not find function with name " + FunctionName); } try { // var gasCallFunction = await contractFunction.EstimateGasAsync( // from: account.Address, // gas: null, // value: null, // functionInput: inputParams == null ? new object[]{} : inputParams // ); // --- the above call consistently fails - might be because of Web3Quorum --- // //var realGas = new HexBigInteger(gasCallFunction.Value + 500000); // Seems to be deprecated, using transactionmanager service instead // // -- set signer as the account that is sending the transaction --// // web3.Client.OverridingRequestInterceptor = new AccountTransactionSigningInterceptor(account.PrivateKey, web3.Client); var realGas = new HexBigInteger(500000); var txManager = new AccountSignerTransactionManager(web3.Client, account.PrivateKey); var txInput = contractFunction.CreateTransactionInput(account.Address, realGas, new HexBigInteger(0), new HexBigInteger(0), inputParams); var txCountNonce = await txManager.GetNonceAsync(txInput); //--- get transaction count to set nonce ---// var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(account.Address, BlockParameter.CreatePending()); txInput.Nonce = txCountNonce; var supposedNextNonce = await account.NonceService.GetNextNonceAsync(); Console.WriteLine("Nonce txInput Value: " + txCountNonce.Value + "\nNonceManager Value: " + txCount.Value); var transactionReceipt = await txManager.SendTransactionAndWaitForReceiptAsync(txInput, null); // var transactionReceipt = await TransactionService.SendRequestAndWaitForReceiptAsync(() => // contractFunction.SendTransactionAsync( // account.Address, // gas: realGas, // gasPrice: new HexBigInteger(0), // value: new HexBigInteger(0), // functionInput: inputParams) // ); if (transactionReceipt != null) { Console.WriteLine($"Processed Transaction - txHash: {transactionReceipt.TransactionHash}"); return(new TransactionReturnInfo { TransactionHash = transactionReceipt.TransactionHash, BlockHash = transactionReceipt.BlockHash, BlockNumber = transactionReceipt.BlockNumber.Value, ContractAddress = ContractAddress }); } return(null); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
public IEnumerator LogsGetAllChangesTest() { return(ContractTest(async() => { await this.contract.CallAsync("emitTestIndexedEvent1", 1); await this.contract.CallAsync("emitTestIndexedEvent1", 2); await this.contract.CallAsync("emitTestIndexedEvent1", 3); EvmEvent <TestIndexedEvent1> event1 = this.contract.GetEvent <TestIndexedEvent1>("TestIndexedEvent1"); List <EventLog <TestIndexedEvent1> > decodedEvents = await event1.GetAllChanges(event1.CreateFilterInput(BlockParameter.CreateEarliest(), BlockParameter.CreatePending())); Assert.AreEqual(1, decodedEvents[decodedEvents.Count - 3].Event.Number1); Assert.AreEqual(2, decodedEvents[decodedEvents.Count - 2].Event.Number1); Assert.AreEqual(3, decodedEvents[decodedEvents.Count - 1].Event.Number1); })); }
public BlockchainManager(Web3Geth web3geth, BlockchainSettings settings, ILogger logger) { _web3geth = web3geth; _settings = settings; _logger = logger; string sender_address = _settings.default_sender_address; string password = _settings.default_sender_password; _sender_private_key = DecryptPrivateKeyFromScryptKeystore(_settings.default_sender_scrypt_keystore_json, password); _inital_main_account_nonce = _web3geth.Eth.Transactions.GetTransactionCount.SendRequestAsync(sender_address, BlockParameter.CreatePending()).Result.Value; }
public async Task <(string status, string transaction)> CheckStatusAsync(string address, BigInteger fromBlock) { (string status, string transaction)result = ("error", ""); if (fromBlock < 0) { fromBlock = (await _web3.Eth.Blocks.GetBlockNumber.SendRequestAsync()).Value - 50; //var res = await _web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(BlockParameter.CreatePending()); //var tx = res.Transactions.Where(t => t != null && t.To != null && t.To.ToUpperInvariant() == address.ToUpperInvariant()).FirstOrDefault(); //if (tx == null) //{ // result = ("recieved", ""); //} //else //{ // result = ("complete", tx.TransactionHash); //} } //else //{ List <Task <BlockWithTransactions> > tasks = new List <Task <BlockWithTransactions> >(); for (BigInteger i = fromBlock; i < (await _web3.Eth.Blocks.GetBlockNumber.SendRequestAsync()).Value; i++) { tasks.Add(_web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(new HexBigInteger(i))); } tasks.Add(_web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(BlockParameter.CreatePending())); var allTransactions = (await Task.WhenAll(tasks)).SelectMany(t => t.Transactions).Distinct(new TransactionComparer()); var tx = allTransactions.Where(t => t != null && t.To != null && t.To.ToUpperInvariant() == address.ToUpperInvariant()).FirstOrDefault(); if (tx == null) { result = ("recieved", ""); } else { result = ("complete", tx.TransactionHash); } //} return(result); }
public async Task <BigInteger> GetAddressBalancePendingInWei(string address) { var balance = await _web3.Eth.GetBalance.SendRequestAsync(address, BlockParameter.CreatePending()); return(balance.Value); }
public void EventFilterInputTest() { ContractBuilder contractBuilder = new ContractBuilder(this.testContext.TestsAbi, Address.FromPublicKey(CryptoUtils.PublicKeyFromPrivateKey(CryptoUtils.GeneratePrivateKey())).LocalAddress); EvmEvent <EvmTestContext.TestIndexedEvent1> event1 = new EvmEvent <EvmTestContext.TestIndexedEvent1>(null, contractBuilder.GetEventAbi("TestIndexedEvent1")); NewFilterInput filterInput = event1.EventAbi.CreateFilterInput(2, new BlockParameter(3), BlockParameter.CreatePending()); Assert.NotNull(filterInput); }
public static async Task <string> Meacoin_Offline_Transaction(string privateKey, string _addressFrom, string _addressTo, int amount) { //get the function var function = meaToken.Contract.GetFunction("transfer"); //get the data var data = function.GetData(new object[] { _addressTo, new BigInteger(amount) }); //nonce var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(_addressFrom, BlockParameter.CreatePending()); //signing the transaction var encoded = transactionSigner.SignTransaction(privateKey, meaToken.Contract.Address, 0, txCount.Value, 1000000000000L, 900000, data); //transaction hash var txId = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded); //verify transaction var status = transactionSigner.VerifyTransaction(encoded); Console.WriteLine("Status : " + status); //returning transaction hash return(txId); }
public IEnumerator LogsGetAllChangesFilteredTest() { return(ContractTest(async() => { await this.contract.CallAsync("emitTestIndexedEvent1", 1); await this.contract.CallAsync("emitTestIndexedEvent1", 2); await this.contract.CallAsync("emitTestIndexedEvent1", 3); EvmEvent <TestIndexedEvent1> event1 = this.contract.GetEvent <TestIndexedEvent1>("TestIndexedEvent1"); List <EventLog <TestIndexedEvent1> > decodedEvents = await event1.GetAllChanges(event1.CreateFilterInput(new object[] { 2 }, BlockParameter.CreateEarliest(), BlockParameter.CreatePending())); Assert.NotZero(decodedEvents.Count); decodedEvents.ForEach(log => Assert.AreEqual(2, log.Event.Number1)); Debug.Log(JsonConvert.SerializeObject(decodedEvents, Formatting.Indented)); })); }
public async Task <TransactionReturnInfo> CreateContractWithExternalAccountAsync(ContractInfo contractInfo, ExternalAccount externalAccount, object[] inputParams = null, List <string> PrivateFor = null) { if (web3 == null) { throw new Exception("web3 handler has not been set - please call SetWeb3Handler First"); } if (PrivateFor != null && PrivateFor?.Count != 0) { web3.ClearPrivateForRequestParameters(); web3.SetPrivateRequestParameters(PrivateFor); } await externalAccount.InitialiseAsync(); Console.WriteLine("externalAccount InitializeAsync() completed"); externalAccount.InitialiseDefaultTransactionManager(web3.Client); Console.WriteLine("externalAccount.InitialiseDefaultTransactionManager() completed"); //--- get transaction count to set nonce ---// var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(externalAccount.Address, BlockParameter.CreatePending()); Console.WriteLine("web3.Eth.Transactions.GetTransactionCount.SendRequestAsync() completed"); try { var gasDeploy = await web3.Eth.DeployContract.EstimateGasAsync( abi : contractInfo.ContractABI, contractByteCode : contractInfo.ContractByteCode, from : externalAccount.Address, values : inputParams == null?new object[] {} : inputParams); Console.WriteLine("Creating new contract and waiting for address"); // Gas estimate is usually low - with private quorum we don't need to worry about gas so lets just multiply it by 5. var realGas = new HexBigInteger(gasDeploy.Value * 5); Console.WriteLine("About to call web3.Eth.DeployContract.GetData"); var txData = web3.Eth.DeployContract.GetData( contractInfo.ContractByteCode, contractInfo.ContractABI, inputParams ); Console.WriteLine("Returned from web3.Eth.DeployContract.GetData with the returned data of: {0}", txData); var txInput = new TransactionInput( txData, externalAccount.Address, realGas, new HexBigInteger(0) ); Console.WriteLine("About to call externalAccount.TransactionManager.SendTransactionAndWaitForReceiptAsync"); var transactionReceipt = await externalAccount.TransactionManager.SendTransactionAndWaitForReceiptAsync(txInput, null); Console.WriteLine("Returned from externalAccount.TransactionManager.SendTransactionAndWaitForReceiptAsync"); Console.WriteLine(transactionReceipt.ContractAddress); return(new TransactionReturnInfo { TransactionHash = transactionReceipt.TransactionHash, BlockHash = transactionReceipt.BlockHash, BlockNumber = transactionReceipt.BlockNumber.Value, ContractAddress = transactionReceipt.ContractAddress }); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
/// <inheritdoc /> public async Task <BigInteger> GetPendingBalanceAsync(string address) { var block = BlockParameter.CreatePending(); return(await GetBalanceAsync(address, block)); }
public async Task <TransactionReturnInfo> CreateContractAsync(ContractInfo contractInfo, Account account, object[] inputParams = null, List <string> PrivateFor = null) { if (web3 == null) { throw new Exception("web3 handler has not been set - please call SetWeb3Handler First"); } if (PrivateFor != null && PrivateFor?.Count != 0) { web3.ClearPrivateForRequestParameters(); web3.SetPrivateRequestParameters(PrivateFor); } //--- get transaction count to set nonce ---// var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(account.Address, BlockParameter.CreatePending()); // -- set signer as the account that is sending the transaction --// web3.Client.OverridingRequestInterceptor = new AccountTransactionSigningInterceptor(account.PrivateKey, web3.Client); try { var gasDeploy = await web3.Eth.DeployContract.EstimateGasAsync( abi : contractInfo.ContractABI, contractByteCode : contractInfo.ContractByteCode, from : account.Address, values : inputParams == null?new object[] {} : inputParams); Console.WriteLine("Creating new contract and waiting for address"); // COULD ALSO USE TransactionService.DeployContractAndWaitForAddress // Gas estimate is usually low - with private quorum we don't need to worry about gas so lets just multiply it by 5. var realGas = new HexBigInteger(gasDeploy.Value * 5); var transactionReceipt = await TransactionService.DeployContractAndWaitForReceiptAsync(() => web3.Eth.DeployContract.SendRequestAsync( contractInfo.ContractABI, contractInfo.ContractByteCode, account.Address, gas: realGas, gasPrice: new HexBigInteger(0), value: new HexBigInteger(0), nonce: txCount, values: inputParams) ); Console.WriteLine(transactionReceipt.ContractAddress); return(new TransactionReturnInfo { TransactionHash = transactionReceipt.TransactionHash, BlockHash = transactionReceipt.BlockHash, BlockNumber = transactionReceipt.BlockNumber.Value, ContractAddress = transactionReceipt.ContractAddress }); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
public IEnumerator LogsGetAllChangesTest() { return(testContext.ContractTest(async() => { BigInteger bigValue = new BigInteger(ulong.MaxValue) * ulong.MaxValue; BroadcastTxResult firstEvent1Result = await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", 1); await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", 2); await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", 3); await this.testContext.Contract.CallAsync("emitTestIndexedEvent1", bigValue); EvmEvent <EvmTestContext.TestIndexedEvent1> event1 = this.testContext.Contract.GetEvent <EvmTestContext.TestIndexedEvent1>("TestIndexedEvent1"); List <EventLog <EvmTestContext.TestIndexedEvent1> > decodedEvents1 = await event1.GetAllChanges(event1.EventAbi.CreateFilterInput(new BlockParameter(firstEvent1Result.Height), BlockParameter.CreatePending())); Assert.AreEqual((BigInteger)1, decodedEvents1[0].Event.Number1); Assert.AreEqual((BigInteger)2, decodedEvents1[1].Event.Number1); Assert.AreEqual((BigInteger)3, decodedEvents1[2].Event.Number1); Assert.AreEqual(bigValue, decodedEvents1[3].Event.Number1); BroadcastTxResult firstEvent2Result = await this.testContext.Contract.CallAsync("emitTestIndexedEvent2", 4, 5); await this.testContext.Contract.CallAsync("emitTestIndexedEvent2", 6, 7); await this.testContext.Contract.CallAsync("emitTestIndexedEvent2", 8, 9); EvmEvent <EvmTestContext.TestIndexedEvent2> event2 = this.testContext.Contract.GetEvent <EvmTestContext.TestIndexedEvent2>("TestIndexedEvent2"); List <EventLog <EvmTestContext.TestIndexedEvent2> > decodedEvents2 = await event2.GetAllChanges(event2.EventAbi.CreateFilterInput(new BlockParameter(firstEvent2Result.Height), BlockParameter.CreatePending())); Assert.AreEqual((BigInteger)4, decodedEvents2[0].Event.Number1); Assert.AreEqual((BigInteger)5, decodedEvents2[0].Event.Number2); Assert.AreEqual((BigInteger)6, decodedEvents2[1].Event.Number1); Assert.AreEqual((BigInteger)7, decodedEvents2[1].Event.Number2); Assert.AreEqual((BigInteger)8, decodedEvents2[2].Event.Number1); Assert.AreEqual((BigInteger)9, decodedEvents2[2].Event.Number2); }, 20000)); }