craig

2 min read - Posted 18 Dec 19

Signing an Ethereum Transaction in Web3j

Web3j provides a bunch of helper classes to enable you to create and sign a transaction within your ethereum java code.

The transaction creation process involves a number of steps including obtaining the nonce for the sending user, and defining gas values. An example code snippet is provided below:

//Connect to node. Defaults to http://localhost:8545
Web3j web3 = Web3j.build(new HttpService());

//Generate wallet credentials from a mnemonic seed phrase
Credentials credentials = WalletUtils.loadBip39Credentials("password", "mnemonic");

//The transaction recipient address
String toAddress = "0xF0f15Cedc719B5A55470877B0710d5c7816916b1";

//The wei amount to transfer (1 ether)
BigInteger amountToTransferInWei = Convert.toWei(
        BigDecimal.ONE, Convert.Unit.ETHER).toBigInteger();

// Get nonce
BigInteger nonce = web3.ethGetTransactionCount(
        credentials.getAddress(), DefaultBlockParameterName.LATEST).send()
        .getTransactionCount();

// Gas Parameters
// Gas required for a standard ether transfer transaction
BigInteger gasLimit = BigInteger.valueOf(21000);
// 1 Gwei = 1,000,000,000 wei
BigInteger gasPrice = Convert.toWei(
        BigDecimal.ONE, Convert.Unit.GWEI).toBigInteger();

// Prepare the rawTransaction
RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(
        nonce,
        gasPrice,
        gasLimit,
        toAddress,
        amountToTransferInWei);

// Sign the transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexSignedMessage = Numeric.toHexString(signedMessage);

Thanks to Greg Jeanmart, and the article Managing an Ethereum Account with Java and Web3j.

Created with Sketch.Content is"CC-BY-SA 4.0" licensed
Article On-chain
0 Comments
Related Articles
Sending an Ether Transfer Transaction from One Account to Another in Web3j

To transfer ether from one account to another, a transaction must be sent to the ethereum network. The easiest way to achieve this within your java application

Web3j Transaction Managers

A Transaction Manager in Web3j is an abstraction that controls how transactions are signed and broadcast to the Ethereum network, via a connected client. You can pass an implementation to a smart contract wrapper when deploying or loading a contract, or you can use it to directly send transactions in a more manual way. There are multiple different Transaction Manager implementations included, all extending the TransactionManager abstract class. Each extending class must implement the abstract se