Offline Transactions – How to Sign a Transaction with Web3j?

javatransactionsweb3j

I'd like to generate and sign a transaction offline and then send that transaction with a different account. I've found a few web3js sources and I've read the web3 documentation, but I haven't found any clear solutions for doing this in Java with web3j. Thanks for the help.

Best Answer

I think something like this should work

// Create the Transaction
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(<nonce>, <gasPrice>, 
       <gasLimit>, <to>, <value>);  

// Sign the Transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, <your-Credentials>);

String hexValue = Numeric.toHexString(signedMessage);

and then give the hexValue to the third-party to broadcast it to the network

Update: now you need the chain ID to the method singMessage, like this:

long chainId = <the id of the used chain>
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId , <you Credentials>);