小猿“思前享后”為大家分享優(yōu)質(zhì)內(nèi)容乘综!————Share猿
Hi大家好:
??我是Share猿,Share是英文(SHARE)套硼,猿是猿猴的猿卡辰,在微信公眾號(hào)、微博邪意、簡(jiǎn)書九妈、掘金、今日頭條雾鬼、CSDN都可以通過搜索“Share猿”找到我萌朱,我等你哦!小猿 “思前享后”為大家分享優(yōu)質(zhì)的內(nèi)容策菜!今天小猿為大家分享:開始
??大家可以用最新的web3j構(gòu)建項(xiàng)目晶疼。
2.1Maven(java8)
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
</dependency>
2.2.Gradle(java8)
java
compile ('org.web3j:core:3.3.1')
Android
compile ('org.web3j:core:3.3.1-android')
2.3.開始一個(gè)客戶端
??如果你還沒有運(yùn)行一個(gè)Ethereum客戶端,比如Geth可以如下運(yùn)行:
$ geth --rpcapi personal,db,eth,net,web3 --rpc --rinkeby
??Parity(錢包)
$ parity --chain testnet
??或者用Infura又憨,他提供了免費(fèi)的客戶端
Web3j web3 = Web3j.build(new HttpService("https://morden.infura.io/your-token"));
??想進(jìn)一步學(xué)習(xí)web3j和Infura翠霍,可以到運(yùn)用他們的章節(jié)去查看。
2.4.發(fā)送請(qǐng)求
??發(fā)送一個(gè)同步請(qǐng)求
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
??發(fā)送一個(gè)異步請(qǐng)求給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的運(yùn)用
Web3j web3 = Web3jFactory.build(new HttpService()); // defaults to http://localhost:8545/
2.5.IPC
web3j還支持通過文件套接字的快速進(jìn)程間通信(IPC)蠢莺,與web3j運(yùn)行在同一主機(jī)上的客戶端寒匙。在創(chuàng)建服務(wù)時(shí),只需使用相關(guān)的IpcService實(shí)現(xiàn)而不是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 不能應(yīng)用在web3j-android.
2.6.基于java包裝的智能合約的運(yùn)用
在JVM中web3j可以自動(dòng)生成智能合約躏将,部署運(yùn)行智能合約锄弱。
常用生成智能合約的相關(guān)代碼:
$ solc <contract>.sol --bin --abi --optimize -o <output-dir>/
運(yùn)用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
用java代碼實(shí)現(xiàn)智能合約
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
或者你可以用一個(gè)構(gòu)造好的方法去實(shí)現(xiàn)智能合約:
YourSmartContract contract = YourSmartContract.load(
"0x<address>|<ensName>", <web3j>, <credentials>, GAS_PRICE, GAS_LIMIT);
用一個(gè)智能合約去進(jìn)行交易
TransactionReceipt transactionReceipt = contract.someMethod(
<param1>,
...).send();
去訪問一個(gè)智能合約
Type result = contract.someMethod(<param1>, ...).send();
??更多的智能合約請(qǐng)參考Solidity的智能合約編寫方法。
2.7.過濾器
??web3j讓大家在區(qū)塊鏈上進(jìn)行開發(fā)變的更加簡(jiǎn)單耸携。
把一個(gè)新的區(qū)塊添加到區(qū)塊鏈中:
Subscription subscription = web3j.blockObservable(false).subscribe(block -> {
...
});
把收到的所有交易添加到區(qū)塊鏈中
Subscription subscription = web3j.transactionObservable().subscribe(tx -> {
...
});
接受一些待確認(rèn)的交易記錄
Subscription subscription = web3j.pendingTransactionObservable().subscribe(tx -> {
...
});
或者你已經(jīng)收到了所有的區(qū)塊鏈信息棵癣,同時(shí)又有新的區(qū)塊被創(chuàng)建:
Subscription subscription = catchUpToLatestAndSubscribeToNewBlocksObservable(
<startBlockNumber>, <fullTxObjects>)
.subscribe(block -> {
...
});
??區(qū)塊鏈和確認(rèn)交易中還有好多過濾器和方法辕翰。
??主流的一些過濾器也被支持
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,
DefaultBlockParameterName.LATEST, <contract-address>)
.addSingleTopic(...)|.addOptionalTopics(..., ...)|...;
web3j.ethLogObservable(filter).subscribe(log -> {
...
});
服務(wù)即是不用也要一直可以開著
subscription.unsubscribe();
注意:在Infura中不支持過濾器夺衍。
2.8.交易
??web3j可以為以太坊錢包和以太坊客戶端交易提供服務(wù)。
發(fā)送以太坊給另一個(gè)賬號(hào)通過你的以太坊錢包秘鑰
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();
創(chuàng)建自定義的交易
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進(jìn)行以太坊的交易和轉(zhuǎn)移很簡(jiǎn)單沟沙!
用管理員身份運(yùn)行以太坊命令行(確保你有你錢包的秘鑰)
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
}
??如果你想運(yùn)用Parity的命令行河劝、Trace、Geth命令行的API矛紫,你可以用 org.web3j:parity 和org.web3j:geth modules respectively.
2.9.命令行工具
??在每個(gè)web3j的jar中都有命令行工具赎瞎,命令行工具允許你通過一些簡(jiǎn)單的命令去操作web3j相關(guān)功能。
- 錢包的創(chuàng)建
- 錢包密碼管理
- 交易
- 一般的Solidity智能合約
2.10.更多詳情
在java 8中構(gòu)建:
- web3j提供安全的響應(yīng)類型颊咬,它的類型在java 8有都有封裝务甥。
- 異步請(qǐng)求被封裝到了java8的CompletableFutures。web3j提供了一個(gè)異步的封裝類喳篇,所有的異常都能被及時(shí)的捕獲到敞临,因?yàn)镃ompletableFutures對(duì)一些異常缺乏支持,經(jīng)常會(huì)造成捕捉不到異常麸澜。
java8和Android的構(gòu)建:
- 高負(fù)載的情況下返回BigInteger挺尿,對(duì)于簡(jiǎn)單的返回可以通過Response.getResual()獲得String。
- 還可以通過包容的響應(yīng)參數(shù)包括原始JSON有效負(fù)載炊邦,在HttpService和IpcService類中出現(xiàn)编矾。
→→→目錄閱讀(小猿英語沒過四級(jí),翻譯的過程中難免會(huì)有好多翻譯不到位的地方馁害,如果有錯(cuò)請(qǐng)?jiān)谠u(píng)論區(qū)及時(shí)指正窄俏!謝謝!碘菜!)
參考文章:
【1】web3j文檔·web3j
【2】區(qū)塊鏈編程一翻譯篇<一>:web3j介紹·Lucien_Lang
掃描以下公眾號(hào)關(guān)注小猿↓↓↓↓↓↓↓↓
更多資訊請(qǐng)?jiān)?strong>簡(jiǎn)書裆操、微博、今日頭條炉媒、掘金踪区、CSDN都可以通過搜索“Share猿”找到小猿哦!5踔琛缎岗!