web3j is a lightweight, type safe Java library for integrating with clients (nodes) on the Ethereum network:
[ JVM application ] + [ web3j ] <---> [ Ethereum node ]
This allows you to work with the Ethereum blockchain, without the additional overhead of having to write your own integration code for the platform.
- Complete implementation of Ethereum's JSON-RPC client API
- Ethereum wallet support
- Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart contracts from native Java code
- Support for Parity's Personal, and Geth's Personal client APIs
- Support for Infura, so you don't have to run an Ethereum client yourself
- Comprehensive integration tests demonstrating a number of the above scenarios
- Command line tools
It only has five runtime dependencies:
- Apache HTTP Client
- Jackson Core for fast JSON serialisation/deserialisation
- Bouncy Castle and Java Scrypt for crypto
- JavaPoet for generating smart contract wrappers
Full project documentation is available at Read the Docs.
Add the relevant dependency to your project:
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>1.0.3</version>
</dependency>
compile ('org.web3j:core:1.0.3')
Start up an Ethereum client if you don't already have one running, such as Geth:
$ geth --rpcapi personal,db,eth,net,web3 --rpc --testnet
Or Parity:
$ parity --chain testnet
Or use Infura, which provides clients running in the cloud. For further information refer to Using Infura with web3j.
To send asynchronous requests using a Future:
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
To send synchronous requests:
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
web3j provides support for both working with Ethereum wallet files and Ethereum client admin commands for sending transactions.
Using an Ethereum wallet file:
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile"); // get the next available nonce EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount( address, DefaultBlockParameterName.LATEST).sendAsync().get(); BigInteger nonce = ethGetTransactionCount.getTransactionCount(); // create our transaction RawTransaction rawTransaction = RawTransaction.createEtherTransaction( nonce, <gas price>, <gas limit>, <toAddress>, <value>); // sign & send our transaction byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials); String hexValue = Hex.toHexString(signedMessage); EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get(); // ...
Although it's far simpler using web3j's Java smart contract wrappers.
Using an Ethereum client's admin commands (make sure you have your wallet in the client's keystore):
Parity parity = Parity.build(new HttpService()); // defaults to http://localhost:8545/ PersonalUnlockAccount personalUnlockAccount = parity.personalUnlockAccount("0x000...", "a password").sendAsync().get(); if (personalUnlockAccount.accountUnlocked()) { // send a transaction, or use parity.personalSignAndSendTransaction() to do it all in one }
web3j can auto-generate smart contract wrapper code to deploy and interact with smart contracts without leaving Java.
To generate the wrapper code, compile your smart contract:
$ solc <contract>.sol --bin --abi --optimize -o <output-dir>/
Then generate the wrapper code using web3j's Command line tools:
web3j solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
Or in code:
org.web3j.codegen.SolidityFunctionWrapperGenerator /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
Now you can create and deploy your smart contract:
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile"); YourSmartContract contract = YourSmartContract.deploy( <web3j>, <credentials>, <initialEtherValue>, <param1>, ..., <paramN>).get(); // constructor params
Or use an existing:
YourSmartContract contract = YourSmartContract.load( "0x<address>", <web3j>, <credentials>);
To Transact with a smart contract:
TransactionReceipt transactionReceipt = contract.someMethod( new Type(...), ...).get();
To call a smart contract:
Type result = contract.someMethod(new Type(...), ...).get();
For more information refer to the documentation.
A web3j fat jar is distributed with each release providing command line tools. The command line tools allow you to use some of the functionality of web3j from the command line:
- Wallet creation
- Wallet password management
- Transfer of funds from one wallet to another
- Generate Solidity smart contract function wrappers
Please refer to the documentation for further information.
- web3j provides type safe access to all responses. Optional or null responses are wrapped in Java 8's Optional type.
- Async requests are handled using Java 8's CompletableFutures.
- Quantity payload types are returned as BigIntegers. For simple results, you can obtain the quantity as a String via Response.getResult().
See EventFilterIT for an example.
- Geth
- Parity
You can run the integration test class CoreIT to verify clients.
- External key store support
- IPC interface support
- WebSocket interface support
For a .NET implementation, check out Nethereum.
For a pure Java implementation of the Ethereum client, check out EthereumJ and the work of Ether.Camp.
web3j includes integration tests for running against a live Ethereum client. If you do not have a client running, you can exclude their execution as per the below instructions.
To run a full build including integration tests:
$ ./gradlew check
To run excluding integration tests:
$ ./gradlew -x integrationTest check
- The Nethereum project for the inspiration
- Othera for the great things they are building on the platform
- Finhaus guys for putting me onto Nethereum
- bitcoinj for the reference Elliptic Curve crypto implementation
- Everyone involved in the Ethererum project and its surrounding ecosystem
- And of course the users of the library, who've provided valuable input & feedback - @ice09, @adridadou, @nickmelis, @basavk, @kabl