3

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.

2
  • what do you mean by "different account"? If you sign the transaction offline by one account, that's the account that will send the transaction, not another account
    – natewelch_
    Apr 5, 2019 at 19:10
  • I want to create a signed raw transaction that can be broadcast by a third-party (someone other than the user who created the transaction). I misspoke when I said "different account." Apr 5, 2019 at 20:34

3 Answers 3

5

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>);
1

You probably need to dig around SignedRawTransaction and TransactionEncoder classes.

1

answer from Majd TL is correct. Here is whole simple implementation with Web3j to create a raw transaction. I believe it can be handy for someone.

final Web3j web3j = Web3j.build(new HttpService("<node>"));

final Credentials credentials = Credentials.create("*******");
final String to = "0x*****";
final String amount = "0.1";
final long ropstenChainId = 3;

EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();

BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
BigInteger gasLimit = DefaultGasProvider.GAS_LIMIT;

RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger());

byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ropstenChainId, credentials);

String hexValue = Numeric.toHexString(signedMessage);
System.out.println(hexValue);

And the correct chainId you can find here - https://chainlist.org/

1
  • Full example helpful to newbies :-)
    – devdanke
    Mar 7, 2023 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.