java web3j infura_web3j是一个用于与Ethereum客户端集成的轻量级Java和Android库

web3j: Web3 Java Ethereum Ðapp API

68747470733a2f2f72656164746865646f63732e6f72672f70726f6a656374732f776562336a2f62616467652f3f76657273696f6e3d6c6174657374

68747470733a2f2f7472617669732d63692e6f72672f776562336a2f776562336a2e7376673f6272616e63683d6d6173746572

68747470733a2f2f636f6465636f762e696f2f67682f776562336a2f776562336a2f6272616e63682f6d61737465722f67726170682f62616467652e737667

68747470733a2f2f696d672e736869656c64732e696f2f646973636f757273652f75736572733f7365727665723d6874747073253341253246253246636f6d6d756e6974792e776562336c6162732e636f6d

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:

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

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

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 web3labs.com.

Quickstart

Install the Web3j binary.

To get the latest version on Mac OS or Linux, type the following in your terminal:

curl -L https://get.web3j.io | sh

Then follow the on-screen instructions or head here.

Alternatively, 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

Typically your application should depend on release versions of web3j, but you may also use snapshot dependencies for early access to features and fixes, refer to the Snapshot Dependencies section.

Add the relevant dependency to your project:

Maven

Java 8:

org.web3j

core

4.5.12

Android:

org.web3j

core

4.2.0-android

Gradle

Java 8:

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

Android:

compile ('org.web3j:core:4.2.0-android')

Plugins

There are also gradle and maven plugins to help you generate web3j Java wrappers for your Solidity smart contracts, thus allowing you to integrate such activities into your project lifecycle.

Take a look at the project homepage for the web3j-gradle-plugin and web3j-maven-plugin for details on how to use these plugins.

Start a client

Start up an Ethereum client if you don't already have one running.

$ geth --rpcapi personal,db,eth,net,web3 --rpc --testnet

$ besu ----network=dev

$ parity --chain testnet

Infura, Or use which provides free clients running in the cloud:

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:

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):

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 Flowable:

Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/

web3.web3ClientVersion().flowable().subscribe(x -> {

String clientVersion = x.getWeb3ClientVersion();

...

});

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:

// 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:

$ solc .sol --bin --abi --optimize -o /

Then generate the wrapper code using web3j's Command line tools:

web3j solidity generate -b /path/to/.bin -a /path/to/.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(

, ,

GAS_PRICE, GAS_LIMIT,

, ..., ).send(); // constructor params

Alternatively, if you use Truffle, you can make use of its .json output files:

# Inside your Truffle project

$ truffle compile

$ truffle deploy

Then generate the wrapper code using web3j's Command line tools:

$ 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:

YourSmartContract contract = YourSmartContract.load(

"0x

|", , , GAS_PRICE, GAS_LIMIT);

To transact with a smart contract:

TransactionReceipt transactionReceipt = contract.someMethod(

,

...).send();

To call a smart contract:

Type result = contract.someMethod(, ...).send();

To fine control your gas price:

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:

Subscription subscription = web3j.blockFlowable(false).subscribe(block -> {

...

});

To receive all new transactions as they are added to the blockchain:

Subscription subscription = web3j.transactionFlowable().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):

Subscription subscription = web3j.pendingTransactionFlowable().subscribe(tx -> {

...

});

Or, if you'd rather replay all blocks to the most current, and be notified of new subsequent blocks being created:

There are a number of other transaction and block replay Flowables described in the docs.

Topic filters are also supported:

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,

DefaultBlockParameterName.LATEST, )

.addSingleTopic(...)|.addOptionalTopics(..., ...)|...;

web3j.ethLogFlowable(filter).subscribe(log -> {

...

});

Subscriptions should always be cancelled when no longer required:

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:

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:

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 = Numeric.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):

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 Besu or Parity's Trace Module, or Geth Personal client APIs, you can use the org.web3j:besu, org.web3j:parity or org.web3j:geth modules.

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

Besu

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 an Ethereum client, check out Besu. Note: both EthereumJ and Ethereum Harmony have been depracated and should not be used in production.

Projects using web3j

Please submit a pull request if you wish to include your project on the list:

Companies using web3j

Please submit a pull request if you wish to include your company on the list:

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):

$ ./gradlew check

To run the integration tests:

$ ./gradlew -Pintegration-tests=true :integration-tests:test

Snapshot Dependencies

Snapshot versions of web3j follow the ..-SNAPSHOT convention, for example: 4.2.0-SNAPSHOT.

If you would like to use snapshots instead please add a new maven repository pointing to:

https://oss.sonatype.org/content/repositories/snapshots

Please refer to the maven or gradle documentation for further detail.

Sample gradle configuration:

repositories {

maven {

url "https://oss.sonatype.org/content/repositories/snapshots"

}

}

Sample maven configuration:

sonatype-snasphots

Sonatype snapshots repo

https://oss.sonatype.org/content/repositories/snapshots

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值