经过前面的环境搭建,现在开始通过web3j和web3.js来简单调用以太坊的api

web3j的使用

首先是新建一个maven工程
<?xml version="1.0" encoding="UTF-8"?> <project xmlns=
"http://maven.apache.org/POM/4.0.0" xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.cayden.ethereum</groupId> <
artifactId>ethsample</artifactId> <version>1.0-SNAPSHOT</version> <dependencies>
<dependency> <groupId>org.web3j</groupId> <artifactId>core</artifactId> <version
>2.2.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <
artifactId>slf4j-log4j12</artifactId> <version>1.7.2</version> </dependency> </
dependencies> </project>
然后新建Web3JClient.java
package com.cayden.ethereum.client; import org.web3j.protocol.Web3j; import
org.web3j.protocol.http.HttpService;/** * Created by cuiran on 18/7/6. */ public
class Web3JClient { private static String ip = "http://127.0.0.1:8545/"; private
Web3JClient(){} private volatile static Web3j web3j; public static Web3j
getClient(){ if(web3j==null){ synchronized (Web3JClient.class){ if(web3j==null
){ web3j = Web3j.build(new HttpService(ip)); } } } return web3j; } }
在新建ParityClient.java
package com.cayden.ethereum.client; import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.parity.Parity; /** * Created by cuiran on 18/7/6. */
public class ParityClient { private static String ip = "http://127.0.0.1:8545/";
private ParityClient(){} private static class ClientHolder{ private static final
Parity parity = Parity.build(new HttpService(ip)); } public static final Parity
getParity(){ return ClientHolder.parity; } }
然后创建一个AccountInfo类
package com.cayden.ethereum.pojo; /** * Created by cuiran on 18/7/6. */ public
class AccountInfo { private String userName; private String phone; private
String address;private String school; public String getUserName() { return
userName; }public void setUserName(String userName) { this.userName = userName;
}public String getPhone() { return phone; } public void setPhone(String phone) {
this.phone = phone; } public String getAddress() { return address; } public void
setAddress(String address) { this.address = address; } public String getSchool
() {return school; } public void setSchool(String school) { this.school =
school; } }
新建一个账户类Account
package com.cayden.ethereum; import com.cayden.ethereum.client.ParityClient;
import com.cayden.ethereum.client.Web3JClient; import
com.cayden.ethereum.pojo.AccountInfo;import org.web3j.protocol.Web3j; import
org.web3j.protocol.core.DefaultBlockParameter;import
org.web3j.protocol.core.DefaultBlockParameterNumber;import
org.web3j.protocol.core.methods.response.EthGetBalance;import
org.web3j.protocol.parity.Parity;import
org.web3j.protocol.parity.methods.response.NewAccountIdentifier;import
org.web3j.protocol.parity.methods.response.PersonalAccountsInfo;import
java.math.BigInteger;import java.util.HashMap; import java.util.List; import
java.util.Map;/** * Created by cuiran on 18/7/6. */ public class Account {
private static Parity parity = ParityClient.getParity(); private static Web3j
web3j = Web3JClient.getClient();/** * Life * Like this * Like that * Also *
It's not the same with you think * @Author cuiran * */ public List<String>
getAccountlist(){ try{ return
parity.personalListAccounts().send().getAccountIds(); }catch (Exception e){
e.printStackTrace(); }return null; } public String createAccount(String
accountName,String password,AccountInfo accountInfo){try { NewAccountIdentifier
newAccountIdentifier = parity.personalNewAccount(password).send();if
(newAccountIdentifier!=null){ String accountId =
newAccountIdentifier.getAccountId();
parity.personalSetAccountName(accountId,accountName); Map<String,Object>
account =new HashMap<String,Object>(); account.put(accountId,accountInfo);
parity.personalSetAccountMeta(accountId,account);return accountId; } } catch
(Exception e) { e.printStackTrace(); }return null; } public
PersonalAccountsInfo.AccountsInfogetAccountInfo(String accountId){ try{
PersonalAccountsInfo personalAccountsInfo =
parity.personalAccountsInfo().send();return
personalAccountsInfo.getAccountsInfo().get(accountId); }catch (Exception e){
e.printStackTrace(); }return null; } public BigInteger getBalance(String
accountId){try { DefaultBlockParameter defaultBlockParameter = new
DefaultBlockParameterNumber(58); EthGetBalance ethGetBalance =
parity.ethGetBalance(accountId,defaultBlockParameter).send();if(ethGetBalance!=
null){ return ethGetBalance.getBalance(); } }catch (Exception e){
e.printStackTrace(); }return null; } }
新建一个交易转账类
package com.cayden.ethereum; import com.cayden.ethereum.client.ParityClient;
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import
org.web3j.protocol.core.methods.request.Transaction;import
org.web3j.protocol.core.methods.response.EthSendTransaction;import
org.web3j.protocol.parity.Parity;import java.math.BigDecimal; import
java.math.BigInteger;/** * Created by cuiran on 18/7/6. */ public class Trade {
private static final Logger logger = LoggerFactory.getLogger(Trade.class);
private static BigInteger nonce = new BigInteger("0"); private static
BigInteger gasPrice =new BigInteger("1"); private static BigInteger gasLimit =
new BigInteger("50"); private Parity parity = ParityClient.getParity(); public
boolean trasfer(String accountId,String passsword,String toAccountId,
BigDecimal amount) { Transaction transaction =
Transaction.createEtherTransaction(accountId,null,null,null
,toAccountId,amount.toBigInteger());try{ EthSendTransaction ethSendTransaction
=parity.personalSignAndSendTransaction(transaction,passsword).send();if
(ethSendTransaction!=null){ String tradeHash =
ethSendTransaction.getTransactionHash(); logger.info(
"账户:[{}]转账到账户:[{}],交易hash:[{}]",accountId,toAccountId,tradeHash); } }catch
(Exception e){ logger.error("账户:[{}]交易失败!",accountId,e); } return false; } }
最后测试类如下
package com.cayden.ethereum; import com.cayden.ethereum.pojo.AccountInfo;
import org.web3j.protocol.parity.methods.response.PersonalAccountsInfo; import
java.math.BigDecimal;import java.math.BigInteger; import java.util.List; /** *
Created by cuiran on 18/7/6. */ public class AccountTest { public static void
main(String args[]) { // createAccount(); getBalance(); // queryAccount(); //
trade(); // getAccountInfo(); } public static void getBalance(){ Account
account =new Account(); BigInteger ba = account.getBalance(
"0xb258e5b1b30215b112881c13f22ab5a47a624b81"); System.out.print(ba); } public
static void getAccountInfo(){ Account account = new Account();
PersonalAccountsInfo.AccountsInfo accountsInfo = account.getAccountInfo(
"0x5bd2328251e8abd5bc39393a9549586634785938");
System.out.println(accountsInfo.toString()); }public static void queryAccount
(){ Account account =new Account(); List<String> accounts =
account.getAccountlist();for(String accountId:accounts){
System.out.println(accountId); } }public static void trade(){ Trade trade = new
Trade();boolean result=trade.trasfer(
"0x1a95f4df6dbf7511b8ec820833df628ea743c458","123456",
"0x91140c3170f4aa959f09aff9b5393e9d0cd2a54c",new BigDecimal(5));
System.out.println("trade:"+result); } public static void createAccount(){
Account account =new Account(); AccountInfo accountInfo = new AccountInfo();
accountInfo.setPhone("12345678901"); accountInfo.setAddress("北街家园");
accountInfo.setSchool("清华大学"); accountInfo.setUserName("cayden"); String
accountId = account.createAccount("cayden","123456",accountInfo);
System.out.println("注册账户成功:"+accountId); // PersonalAccountsInfo.AccountsInfo
accountsInfo =
account.getAccountInfo("0xad7bbca86e02e503076b06931e05938e51e49fb9"); //
System.out.println(accountsInfo.toString()); } }


web3.js的使用

先引入web3.js文件
然后新建index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</
title> </head> <body> <script src="js/web3.js"></script> <input type="button"
value="获取账号"> <input type="button" value="创建账号"> <input type="button" value=
"解锁账号"> <input type="button" value="获取余额"> <script> var web3 = new Web3(new
Web3.providers.HttpProvider("http://127.0.0.1:8545"));
document.querySelectorAll("input")[0].onclick=function(){ //使用web3 的api
去操作节点。jsonrpc web3.eth.getAccounts(function(error,result){ console.log(result);
var res="查询账号信息:<br>"; for (var i=0;i<result.length;i++){ res+="账号"+(i+1)+":"
+result[i]+"<br>"; } document.getElementById("result").innerHTML=res; }); }
document.querySelectorAll("input")[1].onclick=function(){ console.log("www");
web3.personal.newAccount("123456",function(error,result){ console.log(result);
}); } document.querySelectorAll("input")[2].onclick=function(){
web3.personal.unlockAccount("0x89ed26fe35814f839b8b62e5de09521280247cfd",
"123456",function(error,result){ console.log(result); console.log("解绑成功"); });
} document.querySelectorAll("input")[3].onclick=function(){ web3.eth.getBalance(
"0xb258e5b1b30215b112881c13f22ab5a47a624b81",function(error,result){
console.log(result); document.getElementById("result").innerHTML="余额:"+result.c[
0]; console.log("获取余额成功"); }); } </script> <div id="result"></div> </body> </
html>

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信