# web3j
**Repository Path**: Juvenile_developer/web3j
## Basic Information
- **Project Name**: web3j
- **Description**: web3j 是一个轻量级、高度模块化、响应式、类型安全的 Java 和 Android 库,用于与智能合约以及与以太坊网络上的客户端(节点)进行集成: 可以通过它进行以太坊区块链的
- **Primary Language**: Unknown
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 19
- **Created**: 2018-06-28
- **Last Updated**: 2024-06-16
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
.. To build this file locally ensure docutils Python package is installed and run:
$ rst2html.py README.rst README.html
web3j: Web3 Java Ethereum Ðapp API
==================================
.. image:: https://readthedocs.org/projects/web3j/badge/?version=latest
:target: http://docs.web3j.io
:alt: Documentation Status
.. image:: https://travis-ci.org/web3j/web3j.svg?branch=master
:target: https://travis-ci.org/web3j/web3j
:alt: Build Status
.. image:: https://codecov.io/gh/web3j/web3j/branch/master/graph/badge.svg
:target: https://codecov.io/gh/web3j/web3j
:alt: codecov
.. image:: https://badges.gitter.im/web3j/web3j.svg
:target: https://gitter.im/web3j/web3j?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
:alt: Join the chat at https://gitter.im/web3j/web3j
web3j is a lightweight, highly modular, reactive, type safe Java and Android library for working with
Smart Contracts and integrating with clients (nodes) on the Ethereum network:
.. image:: https://raw.githubusercontent.com/web3j/web3j/master/docs/source/images/web3j_network.png
This allows you to work with the `Ethereum `_ blockchain, without the
additional overhead of having to write your own integration code for the platform.
The `Java and the Blockchain `_ talk provides an
overview of blockchain, Ethereum and web3j.
Features
--------
- Complete implementation of Ethereum's `JSON-RPC `_
client API over HTTP and IPC
- Ethereum wallet support
- Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart
contracts from native Java code
(`Solidity `_
and
`Truffle `_ definition formats supported)
- Reactive-functional API for working with filters
- `Ethereum Name Service (ENS) `_ support
- 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
- Android compatible
- Support for JP Morgan's Quorum via `web3j-quorum `_
It has five runtime dependencies:
- `RxJava `_ for its reactive-functional API
- `OKHttp `_ for HTTP connections
- `Jackson Core `_ for fast JSON
serialisation/deserialisation
- `Bouncy Castle `_
(`Spongy Castle `_ on Android) for crypto
- `Jnr-unixsocket `_ for \*nix IPC (not available on
Android)
It also uses `JavaPoet `_ for generating smart contract
wrappers.
Full project documentation is available at
`docs.web3j.io `_.
Donate
------
You can help fund the development of web3j by donating to the following wallet addresses:
+----------+--------------------------------------------+
| Ethereum | 0x2dfBf35bb7c3c0A466A6C48BEBf3eF7576d3C420 |
+----------+--------------------------------------------+
| Bitcoin | 1DfUeRWUy4VjekPmmZUNqCjcJBMwsyp61G |
+----------+--------------------------------------------+
Commercial support and training
-------------------------------
Commercial support and training is available from `blk.io `_.
Quickstart
----------
A `web3j sample project `_ is available that
demonstrates a number of core features of Ethereum with web3j, including:
- Connecting to a node on the Ethereum network
- Loading an Ethereum wallet file
- Sending Ether from one address to another
- Deploying a smart contract to the network
- Reading a value from the deployed smart contract
- Updating a value in the deployed smart contract
- Viewing an event logged by the smart contract
Getting started
---------------
Add the relevant dependency to your project:
Maven
-----
Java 8:
.. code-block:: xml
org.web3j
core
3.4.0
Android:
.. code-block:: xml
org.web3j
core
3.3.1-android
Gradle
------
Java 8:
.. code-block:: groovy
compile ('org.web3j:core:3.4.0')
Android:
.. code-block:: groovy
compile ('org.web3j:core:3.3.1-android')
Start a client
--------------
Start up an Ethereum client if you don't already have one running, such as
`Geth `_:
.. code-block:: bash
$ geth --rpcapi personal,db,eth,net,web3 --rpc --testnet
Or `Parity `_:
.. code-block:: bash
$ parity --chain testnet
Or use `Infura `_, which provides **free clients** running in the cloud:
.. code-block:: java
Web3j web3 = Web3j.build(new HttpService("https://ropsten.infura.io/your-token"));
For further information refer to
`Using Infura with web3j `_
Instructions on obtaining Ether to transact on the network can be found in the
`testnet section of the docs `_.
Start sending requests
----------------------
To send synchronous requests:
.. code-block:: java
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
To send asynchronous requests using a CompletableFuture (Future on Android):
.. code-block:: java
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
To use an RxJava Observable:
.. code-block:: java
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
web3.web3ClientVersion().observable().subscribe(x -> {
String clientVersion = x.getWeb3ClientVersion();
...
});
**Note:** for Android use:
.. code-block:: java
Web3j web3 = Web3jFactory.build(new HttpService()); // defaults to http://localhost:8545/
...
IPC
---
web3j also supports fast inter-process communication (IPC) via file sockets to clients running on
the same host as web3j. To connect simply use the relevant *IpcService* implementation instead of
*HttpService* when you create your service:
.. code-block:: java
// OS X/Linux/Unix:
Web3j web3 = Web3j.build(new UnixIpcService("/path/to/socketfile"));
...
// Windows
Web3j web3 = Web3j.build(new WindowsIpcService("/path/to/namedpipefile"));
...
**Note:** IPC is not currently available on web3j-android.
Working with smart contracts with Java smart contract wrappers
--------------------------------------------------------------
web3j can auto-generate smart contract wrapper code to deploy and interact with smart contracts
without leaving the JVM.
To generate the wrapper code, compile your smart contract:
.. code-block:: bash
$ solc .sol --bin --abi --optimize -o /
Then generate the wrapper code using web3j's `Command line tools`_:
.. code-block:: bash
web3j solidity generate /path/to/.bin /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name
Now you can create and deploy your smart contract:
.. code-block:: java
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");
YourSmartContract contract = YourSmartContract.deploy(
, ,
GAS_PRICE, GAS_LIMIT,
, ..., ).send(); // constructor params
Alternatively, if you use `Truffle `_, you can make use of its `.json` output files:
.. code-block:: bash
# Inside your Truffle project
$ truffle compile
$ truffle deploy
Then generate the wrapper code using web3j's `Command line tools`_:
.. code-block:: bash
$ cd /path/to/your/web3j/java/project
$ web3j truffle generate /path/to/.json -o /path/to/src/main/java -p com.your.organisation.name
Whether using `Truffle` or `solc` directly, either way you get a ready-to-use Java wrapper for your contract.
So, to use an existing contract:
.. code-block:: java
YourSmartContract contract = YourSmartContract.load(
"0x|", , , GAS_PRICE, GAS_LIMIT);
To transact with a smart contract:
.. code-block:: java
TransactionReceipt transactionReceipt = contract.someMethod(
,
...).send();
To call a smart contract:
.. code-block:: java
Type result = contract.someMethod(, ...).send();
To fine control your gas price:
.. code-block:: java
contract.setGasProvider(new DefaultGasProvider() {
...
});
For more information refer to `Smart Contracts `_.
Filters
-------
web3j functional-reactive nature makes it really simple to setup observers that notify subscribers
of events taking place on the blockchain.
To receive all new blocks as they are added to the blockchain:
.. code-block:: java
Subscription subscription = web3j.blockObservable(false).subscribe(block -> {
...
});
To receive all new transactions as they are added to the blockchain:
.. code-block:: java
Subscription subscription = web3j.transactionObservable().subscribe(tx -> {
...
});
To receive all pending transactions as they are submitted to the network (i.e. before they have
been grouped into a block together):
.. code-block:: java
Subscription subscription = web3j.pendingTransactionObservable().subscribe(tx -> {
...
});
Or, if you'd rather replay all blocks to the most current, and be notified of new subsequent
blocks being created:
.. code-block:: java
Subscription subscription = catchUpToLatestAndSubscribeToNewBlocksObservable(
, )
.subscribe(block -> {
...
});
There are a number of other transaction and block replay Observables described in the
`docs `_.
Topic filters are also supported:
.. code-block:: java
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,
DefaultBlockParameterName.LATEST, )
.addSingleTopic(...)|.addOptionalTopics(..., ...)|...;
web3j.ethLogObservable(filter).subscribe(log -> {
...
});
Subscriptions should always be cancelled when no longer required:
.. code-block:: java
subscription.unsubscribe();
**Note:** filters are not supported on Infura.
For further information refer to `Filters and Events `_ and the
`Web3jRx `_
interface.
Transactions
------------
web3j provides support for both working with Ethereum wallet files (recommended) and Ethereum
client admin commands for sending transactions.
To send Ether to another party using your Ethereum wallet file:
.. code-block:: java
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");
TransactionReceipt transactionReceipt = Transfer.sendFunds(
web3, credentials, "0x|",
BigDecimal.valueOf(1.0), Convert.Unit.ETHER)
.send();
Or if you wish to create your own custom transaction:
.. code-block:: java
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, , , , );
// sign & send our transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Hex.toHexString(signedMessage);
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();
// ...
Although it's far simpler using web3j's `Transfer `_
for transacting with Ether.
Using an Ethereum client's admin commands (make sure you have your wallet in the client's
keystore):
.. code-block:: java
Admin web3j = Admin.build(new HttpService()); // defaults to http://localhost:8545/
PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount("0x000...", "a password").sendAsync().get();
if (personalUnlockAccount.accountUnlocked()) {
// send a transaction
}
If you want to make use of Parity's
`Personal `__ or
`Trace `_, or Geth's
`Personal `__ client APIs,
you can use the *org.web3j:parity* and *org.web3j:geth* modules respectively.
Command line tools
------------------
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.
Further details
---------------
In the Java 8 build:
- web3j provides type safe access to all responses. Optional or null responses
are wrapped in Java 8's
`Optional `_ type.
- Asynchronous requests are wrapped in a Java 8
`CompletableFutures `_.
web3j provides a wrapper around all async requests to ensure that any exceptions during
execution will be captured rather then silently discarded. This is due to the lack of support
in *CompletableFutures* for checked exceptions, which are often rethrown as unchecked exception
causing problems with detection. See the
`Async.run() `_ and its associated
`test `_ for details.
In both the Java 8 and Android builds:
- Quantity payload types are returned as `BigIntegers `_.
For simple results, you can obtain the quantity as a String via
`Response `_.getResult().
- It's also possible to include the raw JSON payload in responses via the *includeRawResponse*
parameter, present in the
`HttpService `_
and
`IpcService `_
classes.
Tested clients
--------------
- Geth
- Parity
You can run the integration test class
`CoreIT `_
to verify clients.
Related projects
----------------
For a .NET implementation, check out `Nethereum `_.
For a pure Java implementation of the Ethereum client, check out
`EthereumJ `_ and
`Ethereum Harmony `_.
Projects using web3j
--------------------
Please submit a pull request if you wish to include your project on the list:
- `ERC-20 RESTful Service `_
- `Ether Wallet `_ by
`@vikulin `_
- `eth-contract-api `_ by
`@adridadou `_
- `Ethereum Paper Wallet `_ by
`@matthiaszimmermann `_
- `Trust Ethereum Wallet `_
- `Presto Ethereum `_
- `Kundera-Ethereum data importer and sync utility `_ by `@impetus-opensource `_
- `Ethereum Tool `_ for secure offline key management.
- `Ethereum Java EE JCA Resource Adapter `_ provides integration of Ethereum within Java EE 6+.
Companies using web3j
---------------------
Please submit a pull request if you wish to include your company on the list:
- `Amberdata `_
- `blk.io `_
- `comitFS `_
- `ConsenSys `_
- `ING `_
- `Othera `_
- `Pactum `_
- `TrustWallet `_
- `Impetus `_
- `Argent Labs `_
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 (excluding integration tests):
.. code-block:: bash
$ ./gradlew check
To run the integration tests:
.. code-block:: bash
$ ./gradlew -Pintegration-tests=true :integration-tests:test
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