public async Task <OperationEstimationResult> EstimateTransactionExecutionCost(string from, string signedTrHex) { Nethereum.Signer.Transaction transaction = new Nethereum.Signer.Transaction(signedTrHex.HexToByteArray()); var increasedGas = new HexBigInteger(transaction.GasLimit.ToHexCompact()).Value + 1; var gasLimit = new HexBigInteger(increasedGas); var gasPrice = new HexBigInteger(transaction.GasPrice.ToHexCompact()); string hexValue = transaction.Value.ToHexCompact(); var value = new HexBigInteger(!string.IsNullOrEmpty(hexValue) ? hexValue : "0"); var to = transaction.ReceiveAddress.ToHex().EnsureHexPrefix(); var data = transaction?.Data?.ToHex()?.EnsureHexPrefix() ?? ""; var callInput = new CallInput(data, to, from, gasLimit, gasPrice, value); HexBigInteger response; try { var callResult = await _web3.Eth.Transactions.Call.SendRequestAsync(callInput); response = await _web3.Eth.Transactions.EstimateGas.SendRequestAsync(callInput); } catch (Exception e) { response = new HexBigInteger(gasLimit.Value); } return(new OperationEstimationResult() { GasAmount = response.Value, IsAllowed = response.Value < gasLimit.Value || response.Value == Constants.DefaultTransactionGas }); }
public async Task <bool> CheckTransactionSign(string from, string signedTrHex) { Nethereum.Signer.Transaction transaction = new Nethereum.Signer.Transaction(signedTrHex.HexToByteArray()); string signedBy = transaction.Key.GetPublicAddress(); return(_addressUtil.ConvertToChecksumAddress(from) == _addressUtil.ConvertToChecksumAddress(signedBy)); }
private async Task <string> SignTransaction(Profile profile, Nethereum.Signer.Transaction transaction) { string signature = await profile.SignTransaction(transaction.GetRLPEncodedRaw()); transaction.SetSignature(Nethereum.Signer.EthECDSASignatureFactory.ExtractECDSASignature(signature)); return(transaction.GetRLPEncoded().ToHex(true)); }
/// <summary> /// Utility to send ETH on blockchain signing it by given account /// </summary> /// <returns>Receipt of called transaction</returns> public static async Task <TransactionReceipt> EvaluateOnBC(Web3 web, Profile profile, string to, HexBigInteger amount) { Debug.Assert(profile != null); var nonceService = new InMemoryNonceService(profile.ID, web.Client); BigInteger nonce = await nonceService.GetNextNonceAsync(); var transaction = new Nethereum.Signer.Transaction(to, amount, nonce); var rlpEncodedTx = transaction.GetRLPEncodedRaw(); string signature = await profile.SignTransaction(rlpEncodedTx); transaction.SetSignature(Nethereum.Signer.EthECDSASignatureFactory.ExtractECDSASignature(signature)); var signedTransaction = transaction.GetRLPEncoded().ToHex(true); string txId = await web.Eth.Transactions.SendRawTransaction.SendRequestAsync(signedTransaction); TransactionReceipt receipt = await web.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txId); while (receipt == null) { Thread.Sleep(1000); receipt = await web.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txId); } return(receipt); }
private async Task <string> SendTransactionAsync(string from, string to, string data, BigInteger value, BigInteger?gasPrice, BigInteger?gasValue) { from = from == Constants.AddressForRoundRobinTransactionSending ? await _transactionRouter.GetNextSenderAddressAsync() : from; var semaphore = _semaphores.GetOrAdd(from, f => new SemaphoreSlim(1, 1)); try { await semaphore.WaitAsync(); (gasPrice, gasValue) = await GetGasPriceAndValueAsync(gasPrice, gasValue); var nonce = await _nonceCalculator.GetNonceAsync(from, true); var transaction = new Nethereum.Signer.Transaction(to, value, nonce.Value, gasPrice.Value, gasValue.Value, data); var signRequest = new EthereumTransactionSignRequest { FromProperty = new AddressUtil().ConvertToChecksumAddress(from), Transaction = transaction.GetRLPEncoded().ToHex() }; var signResponse = await _signingApi.ApiEthereumSignPostAsync(signRequest); var txHash = await _sendRawTransaction.SendRequestAsync(signResponse.SignedTransaction.EnsureHexPrefix()); return(txHash); } finally { semaphore.Release(); } }
/// <summary> /// Utility to call functions on blockchain signing it by given account /// </summary> /// <returns>Receipt of called transaction</returns> public static async Task <TransactionReceipt> EvaluateOnBC(Web3 web, Profile profile, Function function, params object[] functionInput) { Debug.Assert(profile != null); var gasPrice = await web.Eth.GasPrice.SendRequestAsync(); HexBigInteger gas = await function.EstimateGasAsync(profile.ID, gasPrice, new HexBigInteger(0), functionInput); var nonceService = new InMemoryNonceService(profile.ID, web.Client); BigInteger nonce = await nonceService.GetNextNonceAsync(); string data = function.GetData(functionInput); var transaction = new Nethereum.Signer.Transaction(function.ContractAddress, BigInteger.Zero, nonce, gasPrice, gas.Value, data); var rlpEncodedTx = transaction.GetRLPEncodedRaw(); string signature = await profile.SignTransaction(rlpEncodedTx); transaction.SetSignature(Nethereum.Signer.EthECDSASignatureFactory.ExtractECDSASignature(signature)); var signedTransaction = transaction.GetRLPEncoded().ToHex(true); string txId = await web.Eth.Transactions.SendRawTransaction.SendRequestAsync(signedTransaction).ConfigureAwait(false); TransactionReceipt receipt = await web.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txId); while (receipt == null) { Thread.Sleep(1000); receipt = await web.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txId); } return(receipt); }
public async Task <bool> IsTransactionErc20Transfer(string transactionHex) { Nethereum.Signer.Transaction transaction = new Nethereum.Signer.Transaction(transactionHex.HexToByteArray()); string erc20InvocationData = transaction.Data?.ToHexCompact().EnsureHexPrefix(); return(erc20InvocationData?.IndexOf(Constants.Erc20TransferSignature, StringComparison.OrdinalIgnoreCase) >= 0); }
public string GetTransactionSigner(string signedTxData) { var signedTransaction = new Transaction(CommonUtils.HexToArray(signedTxData)); var signerPublicAddress = signedTransaction.Key?.GetPublicAddress().ToLowerInvariant(); return(signerPublicAddress); }
public async Task <string> CreateAsync( string task_uuid, string pid, string psn, string tenant_id, string start_date_time, string end_date_time, string start_date_time_local, string end_date_time_local, BigInteger?nonce = null) { _logger.LogDebug("FDBC_Nethereum.SmartContracts.Policy.CreateAsync({task_uuid})", task_uuid); string sender_address = _settings.default_sender_address; string contract_abi = _settings.policy_contract_abi; string contract_bytecode = _settings.policy_contract_bytecode; ////==================================== //// deploy contract var from = sender_address; var gasLimit = new HexBigInteger(4700000); var wei = new HexBigInteger(0); object[] values = new object[] { task_uuid, pid, psn, tenant_id, start_date_time, end_date_time, start_date_time_local, end_date_time_local }; string tx_hash = ""; if (nonce != null) { string data = web3geth.Eth.DeployContract.GetData(contract_bytecode, contract_abi, values); Nethereum.Signer.Transaction signable_transcation = new Nethereum.Signer.Transaction( to: null, amount: wei, nonce: (BigInteger)nonce, gasPrice: Nethereum.Signer.Transaction.DEFAULT_GAS_PRICE, gasLimit: gasLimit.Value, data: data ); tx_hash = await _blockchain_manager.SignAndSendRawTransaction(signable_transcation); } else { tx_hash = await web3geth.Eth.DeployContract.SendRequestAsync( abi : contract_abi, contractByteCode : contract_bytecode, from : from, gas : gasLimit, value : wei, values : values); } return(tx_hash); }
/// <inheritdoc /> public string BuildTransaction(string to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasAmount) { var transaction = new Transaction ( to, amount, nonce, gasPrice, gasAmount, null ); return(transaction.GetRLPEncoded().ToHex()); }
/// <summary> /// Creates transactin passing typed argument /// </summary> /// <typeparam name="TFunctionInput"></typeparam> /// <param name="web"></param> /// <param name="addressFrom"></param> /// <param name="amount"></param> /// <param name="function"></param> /// <param name="functionInput"></param> /// <returns></returns> public static async Task <Nethereum.Signer.Transaction> CreateTransaction <TFunctionInput>(Web3 web, string addressFrom, BigInteger amount, Function <TFunctionInput> function, TFunctionInput functionInput) { var gasPrice = await web.Eth.GasPrice.SendRequestAsync(); HexBigInteger gas = await function.EstimateGasAsync(functionInput, addressFrom.EnsureHexPrefix(), gasPrice, new HexBigInteger(amount)); var nonceService = new InMemoryNonceService(addressFrom.EnsureHexPrefix(), web.Client); BigInteger nonce = await nonceService.GetNextNonceAsync(); string data = function.GetData(functionInput); var transaction = new Nethereum.Signer.Transaction(function.ContractAddress, amount, nonce, gasPrice, gas.Value, data); return(transaction); }
public async Task <string> GetTransactionForSigning(EthTransaction ethTransaction, bool useTxPool = false) { string from = ethTransaction.FromAddress; var gas = new Nethereum.Hex.HexTypes.HexBigInteger(ethTransaction.GasAmount); var gasPrice = new Nethereum.Hex.HexTypes.HexBigInteger(ethTransaction.GasPrice); var nonce = await _nonceCalculator.GetNonceAsync(from, useTxPool); var to = ethTransaction.ToAddress; var value = new Nethereum.Hex.HexTypes.HexBigInteger(ethTransaction.Value); var tr = new Nethereum.Signer.Transaction(to, value, nonce, gasPrice, gas); var hex = tr.GetRLPEncoded().ToHex(); return(hex); }
public async Task ValidateInputForSignedAsync(string fromAddress, string signedTransaction) { Nethereum.Signer.Transaction transaction = new Nethereum.Signer.Transaction(signedTransaction.HexToByteArray()); bool isSignedRight = await _signatureChecker.CheckTransactionSign(fromAddress, signedTransaction); string valueHex = transaction.Value.ToHex(); string gasLimit = transaction.GasLimit.ToHex(); string gasPrice = transaction.GasPrice.ToHex(); await this.ThrowOnExistingHashAsync(transaction.Hash.ToHex()); ThrowOnWrongSignature(isSignedRight); await ValidateAddressBalanceAsync(fromAddress, new HexBigInteger(transaction.Value.ToHex()), new HexBigInteger(gasLimit), new HexBigInteger(gasPrice)); }
/// <inheritdoc /> public string UnsignTransaction(string signedTxData) { var signedTransaction = new Transaction(CommonUtils.HexToArray(signedTxData)); if (signedTransaction.Data != null) { throw new NotSupportedException("Transactions with data are not supported."); } var to = signedTransaction.ReceiveAddress.ToHex(true); var amount = signedTransaction.Value.ToBigIntegerFromRLPDecoded(); var nonce = signedTransaction.Nonce.ToBigIntegerFromRLPDecoded(); var gasPrice = signedTransaction.GasPrice.ToBigIntegerFromRLPDecoded(); var gasLimit = signedTransaction.GasLimit.ToBigIntegerFromRLPDecoded(); return(BuildTransaction(to, amount, nonce, gasPrice, gasLimit)); }
/// Example for debugging purpose: signedTransaction - 0xa9059cbb000000000000000000000000aa4981d084120aef4bbaeecb9abdbc7d180c7edb000000000000000000000000000000000000000000000000000000000000000a public async Task ValidateInputForSignedAsync(string fromAddress, string signedTransaction) { await _transactionValidationService.ValidateInputForSignedAsync(fromAddress, signedTransaction); Nethereum.Signer.Transaction transaction = new Nethereum.Signer.Transaction(signedTransaction.HexToByteArray()); string erc20Address = transaction.ReceiveAddress.ToHex().EnsureHexPrefix(); string erc20InvocationData = transaction.Data.ToHex().EnsureHexPrefix(); if (!await _transactionValidationService.IsTransactionErc20Transfer(signedTransaction)) { throw new ClientSideException(ExceptionType.WrongParams, "Transaction is not a erc20 transfer"); } string parametrsString = erc20InvocationData.Replace(Constants.Erc20TransferSignature, ""); var amount = parametrsString.Substring(64, 64); HexBigInteger tokenAmount = new HexBigInteger(amount); await ValidateTokenAddressBalanceAsync(fromAddress, erc20Address, tokenAmount); }
/// <summary> /// Prepare deposit with given tokens to the child chain /// </summary> /// <param name="profileFrom">profile of the sender</param> /// <param name="currency">transaction currency</param> /// <param name="data">data to prepare (amount for ERC20, tokenid for ERC721)</param> /// <returns></returns> public async Task <BCTransaction> PrepareDeposit(Profile profileFrom, string currency, BigInteger data) { if (rootChainContract != null) { Nethereum.Signer.Transaction approveTx = null; var currencyType = await GetCurrencyType(currency); var tokenHandler = web3.Eth.GetContractHandler(currency); if (!IsFungibleCurrency(currencyType)) { // TODO approve one item (ApproveFunction) or all (SetApprovalForAllFunction)? var approveFunc = tokenHandler.GetFunction <Nethereum.StandardNonFungibleTokenERC721.ContractDefinition.ApproveFunction>(); var approveInput = new Nethereum.StandardNonFungibleTokenERC721.ContractDefinition.ApproveFunction(); approveInput.To = rootChainContract.Address; approveInput.TokenId = data; approveTx = await ContractHelper.CreateTransaction(web3, profileFrom.ID, BigInteger.Zero, approveFunc, approveInput); } else { var approveFunc = tokenHandler.GetFunction <Nethereum.StandardTokenEIP20.ContractDefinition.ApproveFunction>(); var approveInput = new Nethereum.StandardTokenEIP20.ContractDefinition.ApproveFunction(); approveInput.Spender = rootChainContract.Address; approveInput.Value = data; approveTx = await ContractHelper.CreateTransaction(web3, profileFrom.ID, BigInteger.Zero, approveFunc, approveInput); } string signedApproveTx = await SignTransaction(profileFrom, approveTx); return(await SubmitTransactionOnRootChain(web3, signedApproveTx)); } return(null); }
public async Task <string> SetPolicyAllAttributes( string contract_address, string task_uuid, string start_date_time, string end_date_time, string start_date_time_local, string end_date_time_local, string status, string deleted, BigInteger?nonce = null) { // SmartContract function doesn't take null as input for string start_date_time = start_date_time ?? ""; end_date_time = end_date_time ?? ""; start_date_time_local = start_date_time_local ?? ""; end_date_time_local = end_date_time_local ?? ""; status = status ?? ""; deleted = deleted ?? ""; // Web3 string sender_address = _settings.default_sender_address; string contract_abi = _settings.policy_contract_abi; Contract contract = web3geth.Eth.GetContract(contract_abi, contract_address); string task_uuid_sha3 = $"0x{_web3geth.Sha3(task_uuid)}"; byte[] task_uuid_sha3_bytes32 = task_uuid_sha3.HexToByteArray(); Function set_function = contract.GetFunction("set_all"); var from = sender_address; var gasLimit = new HexBigInteger(4700000); var wei = new HexBigInteger(0); object[] values = new object[] { task_uuid, start_date_time, end_date_time, start_date_time_local, end_date_time_local, status, deleted }; string tx_hash = ""; if (nonce != null) { string data = set_function.GetData(values); Nethereum.Signer.Transaction signable_transcation = new Nethereum.Signer.Transaction( to: contract_address, amount: wei, nonce: (BigInteger)nonce, gasPrice: Nethereum.Signer.Transaction.DEFAULT_GAS_PRICE, gasLimit: gasLimit.Value, data: data ); tx_hash = await _blockchain_manager.SignAndSendRawTransaction(signable_transcation); } else { tx_hash = await set_function.SendTransactionAsync( from : from, gas : gasLimit, value : wei, functionInput : values); } return(tx_hash); }