Web3J is a lightweight, highly modular, reactive, type-safe Java and Android library for handling smart contracts and integrating with clients (nodes) on the Ethereum network. This allows you to use the Ethereum blockchain without the additional overhead of writing your own integration code for the platform.

Functions provided

  • Complete implementation of ethereum JSON-RPC client API based on HTTP and IPC
  • Ethereum wallet support
  • Automatically generate Java smart contract wrappers to create, deploy, trade, and invoke smart contracts from native Java code (support Solidity and Truffle definition formats)
  • Ethereum Name Service (ENS) support
  • Alchemy and Infura are supported, so you don’t have to run the Ethereum client yourself
  • Android compatibility
  • Command line tool

How to use

<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.8.7</version>
</dependency>
Copy the code
public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Web3j client = Web3j.build(new HttpService("https://ropsten.infura.io/v3/You Infura Project Id"));
        Web3ClientVersion clientVersion = client.web3ClientVersion().sendAsync().get();
        System.out.println(clientVersion.getWeb3ClientVersion());
        / / = > Geth/v1.10.15 - omnibus - hotfix - f4decf48 / Linux - amd64 / go1.17.6}}Copy the code

Use Web3J to get the ethereum account balance

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Web3j client = Web3j.build(new HttpService("https://ropsten.infura.io/v3/You Infura Project Id"));
        EthGetBalance ethGetBalance = client.ethGetBalance(
                "0x64f44b31ad0ed4537f94a5c084cfba8945463345",
                DefaultBlockParameterName.fromString(DefaultBlockParameterName.LATEST.name())
        ).sendAsync().get();
        System.out.println(ethGetBalance.getBalance());
        / / = > 741270235881990866}}Copy the code

Use Web3J to get the current Gas price

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Web3j client = Web3j.build(new HttpService("https://ropsten.infura.io/v3/You Infura Project Id"));
        EthGasPrice ethGasPrice = client.ethGasPrice().sendAsync().get();
        System.out.println(ethGasPrice.getGasPrice());
        / / = > 41493167936}}Copy the code

Use Web3J to get transaction details through the transaction hash

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Web3j client = Web3j.build(new HttpService("https://ropsten.infura.io/v3/You Infura Project Id"));
        String transactionHash = "0x9030edd43f8ae6c4ed49bcbc11dd7d6f6ce2798e8bb1c5ea4f1e130780fec74a";
        EthGetTransactionReceipt ethGetTransactionReceipt = client.ethGetTransactionReceipt(transactionHash).sendAsync().get();
        TransactionReceipt transactionReceipt = ethGetTransactionReceipt.getTransactionReceipt().orElseThrow(RuntimeException::new);
        System.out.println(transactionReceipt);
        // => TransactionReceipt{transactionHash='0x9030edd43f8ae6c4ed49bcbc11dd7d6f6ce2798e8bb1c5ea4f1e130780fec74a', transactionIndex='0x27', blockHash='0xf0f28e6040d3440abb4abb1da59bf144fc2e210c4d321061d58da3fa3b011b0f', blockNumber='0xb84dee', cumulativeGasUsed='0x79d27a', gasUsed='0xc704', contractAddress='null', root='null', status='0x1', from='0x5ba191f4b0d70b778d9877e217dfb2c5daa353be', to='0xf80a32a835f79d7787e8a8ee5721d0feafd78108', logs=[Log{removed=false, logIndex='0x21', transactionIndex='0x27', transactionHash='0x9030edd43f8ae6c4ed49bcbc11dd7d6f6ce2798e8bb1c5ea4f1e130780fec74a', blockHash='0xf0f28e6040d3440abb4abb1da59bf144fc2e210c4d321061d58da3fa3b011b0f', blockNumber='0xb84dee', address='0xf80a32a835f79d7787e8a8ee5721d0feafd78108', data='0x00000000000000000000000000000000000000000000152d02c7e14af6800000', type='null', topics=[0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000005ba191f4b0d70b778d9877e217dfb2c5daa353be]}], logsBloom='0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000001000000008000000000000000000000000000000000000000000000000020000000000000000000800000 000000000000000000010000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000 400000000000000000000000000000000000000000002000000000000000200000000000000000000000000000000000020000000000200000000000 000000000000000000000000000000000000000000000', revertReason='null', type='0x2', effectiveGasPrice='0x15fb4c0517'}}}Copy the code

Subscribe to new blocks using Web3J

The functional programming nature of Web3J makes it easy to set up observers. We can set up subscribers and listen for things happening on the chain, such as blocks, transactions, logs, etc.

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException, ConnectException {
        WebSocketService webSocketService = new WebSocketService("wss://ropsten.infura.io/ws/v3/You Infura Project Id".true);
        webSocketService.connect();
        Web3j client = Web3j.build(webSocketService);
        Disposable subscribe = client.replayPastBlocksFlowable(DefaultBlockParameterName.fromString("earliest"), true).subscribe(ethBlock -> {
            System.out.println(ethBlock.getBlock());
            // => org.web3j.protocol.core.methods.response.EthBlock$Block@39fcf950}); }}Copy the code

Subscribe to new transactions using Web3J

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException, ConnectException {
        WebSocketService webSocketService = new WebSocketService("wss://ropsten.infura.io/ws/v3/You Infura Project Id".true);
        webSocketService.connect();
        Web3j client = Web3j.build(webSocketService);
        Disposable subscribe = client.replayPastTransactionsFlowable(DefaultBlockParameterName.fromString("earliest")).subscribe(transaction -> {
            System.out.println(transaction);
            // => org.web3j.protocol.core.methods.response.EthBlock$TransactionObject@47b0a71a}); }}Copy the code

Subscribe to new contract events using Web3J

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException, ConnectException {
        WebSocketService webSocketService = new WebSocketService("wss://ropsten.infura.io/ws/v3/You Infura Project Id".true);
        webSocketService.connect();
        Web3j client = Web3j.build(webSocketService);
        Disposable subscribe = client.ethLogFlowable(
                new EthFilter(
                        DefaultBlockParameterName.EARLIEST,
                        DefaultBlockParameterName.LATEST,
                        // Contract address
                        "0x7b52aae43e962ce6a9a1b7e79f549582ae8bcff9"
                )
        ).subscribe(event -> {
            System.out.println(event);
            // => Log{removed=false, logIndex='0x39', transactionIndex='0x13', transactionHash='0x9c3653c27946cb39c3a256229634cfedbca54f146a740f46b661b986590f8358', blockHash='0x1e674b9d111601519f977b75f9a1865ba359b474550ff5d0d87daec1f543d64d', blockNumber='0xb83ccd', address='0x7b52aae43e962ce6a9a1b7e79f549582ae8bcff9', data='0x', type='null', topics=[0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000006ab3d0bd875f8667026d2a9bb3060ec44380bcc2, 0x0000000000000000000000000000000000000000000000000000000000000017]}}, Throwable::printStackTrace); }}Copy the code

Use Web3J to sign and send transactions

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException, ConnectException {
        Web3j client = Web3j.build(new HttpService("https://ropsten.infura.io/v3/You Infura Project Id"));

        // Get the nonce value
        EthGetTransactionCount ethGetTransactionCount = client
                .ethGetTransactionCount("0x64f44b31ad0ed4537f94a5c084cfba8945463345", DefaultBlockParameterName.PENDING)
                .sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
        System.out.println(nonce);

        // Build the transaction
        RawTransaction etherTransaction = RawTransaction.createEtherTransaction(
                nonce,
                client.ethGasPrice().sendAsync().get().getGasPrice(),
                DefaultGasProvider.GAS_LIMIT,
                "0x64f44b31ad0ed4537f94a5c084cfba8945463345",
                Convert.toWei("0.001", Convert.Unit.ETHER).toBigInteger()
        );
        System.out.println(etherTransaction);

        // Load the private key
        Credentials credentials = Credentials.create("You Private Key");

        // Sign the transaction with the private key and send it
        byte[] signature = TransactionEncoder.signMessage(etherTransaction, credentials); String signatureHexValue = Numeric.toHexString(signature); EthSendTransaction ethSendTransaction = client.ethSendRawTransaction(signatureHexValue).sendAsync().get(); System.out.println(ethSendTransaction.getResult()); }}Copy the code

Generate contract wrapper classes using Web3J

Web3J can generate wrapper classes for smart contracts, making it easy to interact with contracts using pure Java code.

$ web3j generate solidity -a ./contract.abi -o ./ -p com.contract.proxy
              _      _____ _
             | |    |____ (_)
__      _____| |__      / /_
\ \ /\ / / _ \ '_ \     \ \ |
 \ V  V /  __/ |_) |.___/ / |
  \_/\_/ \___|_.__/ \____/| |
                         _/ |
                        |__/
by Web3Labs
Generating com.contract.proxy.Contract ...
Warning: Duplicate field(s) found: [FUNC_SAFETRANSFERFROM]. Please don't use names which will be the same in uppercase.
File written to .

$ tree comTXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXTCopy the code

Use Web3J to interact with contracts

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Web3j client = Web3j.build(new HttpService("https://ropsten.infura.io/v3/You Infura Project Id"));
        Credentials credentials = Credentials.create("You Private Key");
        BigInteger currentGasPrice = client.ethGasPrice().sendAsync().get().getGasPrice();
        Contract foundersKeyContract = Contract.load("0x7b52aae43e962ce6a9a1b7e79f549582ae8bcff9", client, credentials, new DefaultGasProvider() {
            /** * Use dynamically acquired Gas Price *@return* /
            @Override
            public BigInteger getGasPrice(a) {
                returncurrentGasPrice; }}); BigInteger balance = foundersKeyContract.balanceOf("0x64f44b31ad0ed4537f94a5c084cfba8945463345").send();
        System.out.println(balance);
        / / = > 41493167936}}Copy the code