Skip to content

Latest commit

 

History

History
281 lines (180 loc) · 9.24 KB

README.rst

File metadata and controls

281 lines (180 loc) · 9.24 KB

web3j: Web3 Java Ethereum Ðapp API

Documentation Status Build Status codecov Join the chat at https://gitter.im/web3j/web3j

web3j is a lightweight, type safe Java library for integrating with clients (nodes) on the Ethereum network:

[ JVM application ] + [ web3j ] <---> [ Ethereum node ]

It can generate Java smart contract wrappers so you can interact with a smart contract like it's native Java code.

Features

  • Full support for the Ethereum JSON-RPC specification
  • Full Ethereum wallet support for transaction signing
  • Generation of Java smart contract wrappers to create, deploy, transact and call smart contracts via native Java code
  • Support for Parity's Personal, and Geth's Personal 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

It only has five runtime dependencies:

Full project documentation is available at Read the Docs.

Getting Started

Add the relevant dependency to your project:

Maven

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

Gradle

compile ('org.web3j:core:1.0.0')

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

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();

Sending transactions

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 & sendn 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
}

Java smart contract wrappers

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:

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

Then you can then create and deploy a 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.

Further Details

  • 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().

Working with filters

See EventFilterIT for an example.

Tested Clients

Geth

  • 1.4.18-stable-ef9265d0

Parity

  • Parity/v1.3.8-beta/x86_64-linux-gnu/rustc1.12.0

You can run the integration test class CoreIT to verify clients.

Coming Soon

  • External key store support
  • IPC interface support
  • WebSocket interface support

Related Projects

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.

Build Instructions

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

Thanks and Credits

  • 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