Ethereum Wallet Creation and ETH Transfer Using Web3j

·

Creating and managing Ethereum wallets programmatically is a fundamental skill for blockchain developers. With the help of Web3j, a lightweight Java library for integrating with Ethereum nodes, developers can easily generate wallets, sign transactions, and transfer ETH—whether on the mainnet or testnet. This guide walks you through the complete process of Ethereum wallet creation and ETH transfer using Web3j, complete with code examples, best practices, and key considerations for secure development.

Whether you're building a decentralized application (dApp), a crypto wallet service, or integrating blockchain functionality into an enterprise system, understanding how to interact with Ethereum via Java is essential.

👉 Discover how to securely manage Ethereum transactions with powerful developer tools


Setting Up Web3j in Your Project

Before diving into wallet creation and fund transfers, you need to include the necessary dependencies in your pom.xml file if you're using Maven. These libraries enable cryptographic operations, Ethereum communication, and utility functions.

<dependency>
    <groupId>com.madgag.spongycastle</groupId>
    <artifactId>core</artifactId>
    <version>1.58.0.0</version>
</dependency>

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>utils</artifactId>
    <version>3.4.0</version>
</dependency>

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.8.7</version>
</dependency>
Note: It's recommended to use the latest stable version of web3j-core to benefit from security patches and improved functionality.

These dependencies provide:


How to Create an Ethereum Wallet Using Web3j

Generating a new Ethereum wallet involves creating a public-private key pair, deriving the wallet address, and securely storing or encrypting the private key.

Here’s a step-by-step implementation:

public static void create() throws InvalidAlgorithmParameterException, 
        NoSuchAlgorithmException, NoSuchProviderException, CipherException {
    
    // Generate ECDSA key pair
    ECKeyPair ecKeyPair = Keys.createEcKeyPair();
    
    // Create a lightweight wallet file (encrypted with password)
    WalletFile walletFile = Wallet.createLight("your-secure-password", ecKeyPair);
    
    // Derive Ethereum address
    String address = "0x" + walletFile.getAddress();
    
    // Extract private key (hex format)
    String privateKey = ecKeyPair.getPrivateKey().toString(16);
    
    // Optional: Encrypt private key with custom method (e.g., AES-CBC)
    String encryptPrivateKey = AesCBC.getInstance().simpleEncrypt(
        privateKey,
        AesCBC.makeKey(1 + "_" + 1)
    );
    
    System.out.println("Address: " + address);
    System.out.println("Encrypted Private Key: " + encryptPrivateKey);
}

Key Points:

👉 Learn how to securely handle private keys and manage digital assets


Sending ETH via Web3j: Step-by-Step Guide

Transferring ETH programmatically requires constructing and signing a raw transaction before broadcasting it to the network.

Prerequisites:

Here’s how to perform an ETH transfer:

public static void trans() throws ExecutionException, InterruptedException, 
        IOException, CipherException {
    
    // Connect to Ethereum network (e.g., Kovan testnet via Infura)
    Web3j web3j = Web3j.build(new HttpService("https://kovan.infura.io/v3/YOUR_PROJECT_ID"));
    
    // Define addresses
    String ownAddress = "0xSenderAddress";
    String toAddress = "0xRecipientAddress";
    
    // Amount in Ether
    String amount = "0.1";
    
    // Load sender credentials (from private key or Keystore)
    Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/keystore.json");
    
    // Get current nonce
    EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
            ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
    BigInteger nonce = ethGetTransactionCount.getTransactionCount();
    
    // Convert Ether to Wei
    BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();
    
    // Fetch current gas price
    EthGasPrice gasPrice = web3j.ethGasPrice().send();
    
    // Define gas limit (21,000 for simple ETH transfers)
    BigInteger gasLimit = BigInteger.valueOf(21000);
    
    // Create raw transaction
    RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
            nonce,
            gasPrice.getGasPrice(),
            gasLimit,
            toAddress,
            value);
    
    // Sign transaction
    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);
    
    // Broadcast transaction
    EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
    
    // Retrieve transaction hash
    String transactionHash = ethSendTransaction.getTransactionHash();
    
    System.out.println("Transaction Hash: " + transactionHash);
}

Transaction Lifecycle Overview:

  1. Nonce Retrieval: Ensures transaction order and prevents replay attacks.
  2. Gas Configuration: Gas price and limit determine transaction priority and cost.
  3. Signing: Locally signs the transaction using the private key—no sensitive data sent to the node.
  4. Broadcasting: Sends the signed transaction to the Ethereum network for mining.

Frequently Asked Questions (FAQ)

Q: Can I use Web3j for ERC-20 token transfers?

Yes. You can encode function calls using Function and FunctionEncoder to interact with smart contracts, such as transferring tokens via the transfer() method.

Q: Is it safe to store private keys in code?

No. Hardcoding private keys poses severe security risks. Always use encrypted keystores, environment variables, or hardware security modules (HSMs).

Q: What is the difference between createLight and createStandard wallets?

createLight uses fewer iterations for encryption (faster but less secure), while createStandard uses more iterations, offering stronger protection at the cost of performance.

Q: How do I check if a transaction was successful?

Use the transaction hash to query its status on block explorers like Etherscan or via eth.getTransactionReceipt.

Q: Can I use Web3j with the Ethereum mainnet?

Absolutely. Just replace the Infura endpoint with a mainnet URL (e.g., https://mainnet.infura.io/v3/YOUR_PROJECT_ID) and ensure your account has ETH.

Q: Why is my transaction stuck?

High network congestion or low gas price may delay confirmation. Monitor gas prices and consider increasing them during peak times.


Best Practices for Secure Blockchain Development


Core Keywords Summary

This article focuses on the following SEO-optimized keywords:

These terms reflect common search intents among developers exploring blockchain integration using Java-based tools.

👉 Explore advanced blockchain tools that support seamless Web3 integration


By mastering Ethereum wallet creation and ETH transfer using Web3j, developers gain critical skills for building secure, scalable blockchain applications. Whether you're handling user wallets or automating payments, Web3j provides a robust foundation for Java-based Ethereum interactions.

Always prioritize security, validate every step, and leverage trusted infrastructure to ensure reliability in production environments.