web3j是一個輕量級、高度模塊化、響應式、類型安全的Java和Android類庫提供豐富API,用於處理以太坊智能合約及與以太坊網絡上的客戶端(節點)進行集成。html
能夠經過它進行以太坊區塊鏈的開發,而無需爲你的應用平臺編寫集成代碼。java
想要快速啓動的話,有一個Web3j demo示例項目可用,演示了經過Web3j開發以太坊的許多核心特徵,其中包括:node
首先將最新版本的web3j安裝到項目中。android
Java 8:git
<dependency> <groupId>org.web3j</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency>
Android:程序員
<dependency> <groupId>org.web3j</groupId> <artifactId>core</artifactId> <version>3.3.1-android</version> </dependency>
Java 8:github
compile ('org.web3j:core:3.4.0')
Android:web
compile ('org.web3j:core:3.3.1-android')
須要啓動一個以太坊客戶端,固然若是你已經啓動了就不須要再次啓動。mongodb
若是是geth的話這麼啓動:api
$ geth --rpcapi personal,db,eth,net,web3 --rpc --rinkeby
若是是Parity啓動:
$ parity --chain testnet
若是使用Infura客戶端提供的免費的雲端服務,這麼啓動:
Web3j web3 = Web3j.build(new HttpService("https://morden.infura.io/your-token"));
若是想進一步的瞭解infura,請參閱Using Infura with web3j。
在網絡上如何得到以太幣的相關文檔能夠看這個:testnet section of the docs。
當不須要Web3j實例時,須要調用shutdown
方法來釋放它所使用的資源。
web3.shutdown()
發送同步請求
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send(); String clientVersion = web3ClientVersion.getWeb3ClientVersion();
** 使用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();
*使用RxJava的Observable
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ web3.web3ClientVersion().observable().subscribe(x -> { String clientVersion = x.getWeb3ClientVersion(); ... });
注意Android使用方式
Web3j web3 = Web3jFactory.build(new HttpService()); // defaults to http://localhost:8545/ ...
Web3j還支持經過文件套接字快速運行進程間通訊(IPC),支持客戶端在相同的主機上同時運行Web3j。在建立服務時,使用相關的IPCService
就能夠實現而不須要經過HTTPService
。
// OS X/Linux/Unix: Web3j web3 = Web3j.build(new UnixIpcService("/path/to/socketfile")); ... // Windows Web3j web3 = Web3j.build(new WindowsIpcService("/path/to/namedpipefile")); ...
須要注意:IPC通訊在web3j-android中不可用。
Web3j能夠自動打包智能合同代碼,以便在不脫離JVM的狀況下進行以太坊智能合同部署和交互。
要打包代碼,須要先編譯智能合同:
$ solc <contract>.sol --bin --abi --optimize -o <output-dir>/
而後用web3j的命令行工具打包代碼:
web3j solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
接下來就能夠新建和部署智能合約了:
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>, GAS_PRICE, GAS_LIMIT, <param1>, ..., <paramN>).send(); // constructor params
或者使用一個現有的智能合約:
YourSmartContract contract = YourSmartContract.load( "0x<address>|<ensName>", <web3j>, <credentials>, GAS_PRICE, GAS_LIMIT);
而後就能夠進行智能合約的交互了:
TransactionReceipt transactionReceipt = contract.someMethod( <param1>, ...).send();
調用智能合約:
Type result = contract.someMethod(<param1>, ...).send();
更多關於打包的資料能夠看這裏:Solidity smart contract wrappers
web3j的響應式函數可使觀察者經過事件去通知消息訂閱者變得很簡單,並可以記錄在區塊鏈中。接收全部新的區塊並把它們添加到區塊鏈中:
Subscription subscription = web3j.blockObservable(false).subscribe(block -> { ... });
接收全部新的交易並把它們添加到區塊鏈中:
Subscription subscription = web3j.transactionObservable().subscribe(tx -> { ... });
接收全部已經提交到網絡中等待處理的交易。(他們被統一的分配到一個區塊以前。)
Subscription subscription = web3j.pendingTransactionObservable().subscribe(tx -> { ... });
或者你重置全部的區塊到最新的位置,那麼當有新建區塊的時候會通知你。
Subscription subscription = catchUpToLatestAndSubscribeToNewBlocksObservable( <startBlockNumber>, <fullTxObjects>) .subscribe(block -> { ... });
主題過濾也被支持:
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, <contract-address>) .addSingleTopic(...)|.addOptionalTopics(..., ...)|...; web3j.ethLogObservable(filter).subscribe(log -> { ... });
當再也不須要時,訂閱也應該被取消:
subscription.unsubscribe();
**注意:Infura中不支持filters。 **
須要瞭解更多有關過濾器和事件的信息能夠查看Filters and Events和Web3jRx的接口。
Web3j支持使用以太坊錢包文件(推薦的)和用於發送事務的以太坊客戶端管理命令。
使用以太錢包文件發送以太幣給其餘人:
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<address>|<ensName>", BigDecimal.valueOf(1.0), Convert.Unit.ETHER) .send();
或者你但願創建你本身定製的交易:
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).send(); 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 = Numeric.toHexString(signedMessage); EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send(); // ...
使用Web3j的Transfer進行以太幣交易要簡單得多。
使用以太坊客戶端的管理命令(若是你的錢包密鑰已經在客戶端存儲):
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 }
若是你想使用 Parity’s Personal 或者 Trace 功能, 或者 Geth’s Personal 客戶端 APIs,可使用org.web3j:parity
和org.web3j:geth
模塊。
web3j的jar包爲每個版本都提供命令行工具。命令行工具容許你直接經過一些命令使用web3j的一些功能:
請參閱文檔以得到命令行相關的進一步的信息。
java8 bulid:
在java 8的Android版本:
Response.getResult()
獲取字符串類型的數量結果。includeRawResponse
參數將原生的JSON包放置在響應中。匯智網原創翻譯,轉載請標明出處,官方原文web3j。