[Ethereum] How to make transaction using private key and address using web3j

go-ethereumjavaraw-transactiontransactionsweb3j

I have a private key and address . Is it possible to make transaction with these parameter using web3j.

Best Answer

Web3j web3j = Web3j.build(new HttpService(""));
    Credentials credentials = Credentials.create("privateKey");
    BigInteger nonce = web3j.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).sendAsync().get().getTransactionCount();
    BigInteger gasPrice = web3j.ethGasPrice().sendAsync().get().getGasPrice();
    RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, Constants.ETH_GAS_LIMIT, "address", Convert.toWei("amount", Convert.Unit.ETHER).toBigIntegerExact());
    EthSendTransaction response = web3j.ethSendRawTransaction(Numeric.toHexString(TransactionEncoder.signMessage(rawTransaction, credentials))).send();
    String hash = response.getTransactionHash();