How to Use Web3j for Basic and Token Transfers in Java

·

Introduction

Web3j is a lightweight Java library for integrating with Ethereum clients, enabling developers to interact with the Ethereum blockchain. This guide covers both basic ETH transfers and ERC-20 token transactions using Web3j.


Project Setup

Maven Dependency

Add this to your pom.xml:

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

Basic ETH Transfer

Code Implementation

public static void transfer() throws Exception {
    Web3j web3j = Web3j.build(new HttpService("INFURA_NODE_URL"));
    BigInteger privateKey = new BigInteger("YOUR_PRIVATE_KEY", 16);
    ECKeyPair ecKeyPair = ECKeyPair.create(privateKey);
    Credentials credentials = Credentials.create(ecKeyPair);
    
    TransactionReceipt receipt = Transfer.sendFunds(
        web3j, 
        credentials, 
        "RECIPIENT_ADDRESS", 
        BigDecimal.valueOf(0.001), 
        Convert.Unit.ETHER
    ).send();
    
    System.out.println(receipt);
}

Key Parameters

👉 Optimize gas fees for ETH transfers


ERC-20 Token Transfer

Code Implementation

public static void transferToken() throws Exception {
    Web3j web3j = Web3j.build(new HttpService("INFURA_NODE_URL"));
    BigInteger privateKey = new BigInteger("YOUR_PRIVATE_KEY", 16);
    Credentials credentials = Credentials.create(ECKeyPair.create(privateKey));
    
    String fromAddress = credentials.getAddress();
    BigInteger nonce = web3j.ethGetTransactionCount(
        fromAddress, 
        DefaultBlockParameterName.LATEST
    ).send().getTransactionCount();
    
    Function function = new Function(
        "transfer",
        Arrays.asList(
            new Address("RECIPIENT_ADDRESS"),
            new Uint256(new BigInteger("AMOUNT_IN_WEI"))
        ),
        Collections.emptyList()
    );
    
    String encodedFunction = FunctionEncoder.encode(function);
    RawTransaction rawTransaction = RawTransaction.createTransaction(
        nonce,
        DefaultGasProvider.GAS_PRICE,
        new BigInteger("210000"),
        "TOKEN_CONTRACT_ADDRESS",
        encodedFunction
    );
    
    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    EthSendTransaction response = web3j.ethSendRawTransaction(
        Numeric.toHexString(signedMessage)
    ).send();
    
    System.out.println("Tx Hash: " + response.getTransactionHash());
}

Critical Components

👉 Best practices for token contract interactions


FAQs

1. How do I get an Infura node URL?

Sign up at Infura.io, create a project, and use the provided Ethereum endpoint.

2. What’s the difference between ETH and token transfers?

ETH transfers move native currency, while token transfers interact with smart contracts that manage token balances.

3. How can I estimate gas costs?

Use web3j.ethEstimateGas() or check current rates on Etherscan.

4. Why is my token transfer failing?

Common issues:


References


This Markdown-formatted guide: