SpringBoot区块链之以太坊开发(整合Web3j)
最近公司需要ETH兑换功能,ETH转账需要区块打包,这个时候就需要区块检测,目前只是简单整合,后面会将区块自动检测代码上传致QQ群
对于区块链开发不太熟悉的童鞋,可以看看:[区块链开发(零)如何开始学习以太坊及区块链](https://blog.csdn.net/sportshark/article/details/52351415)
欢迎大家加企鹅群一起讨论:260532022
首先引入一下依赖pom.xml,主要依赖是 org.web3j
```
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.8.RELEASE
com.xiaobin
eth-demo
0.0.1-SNAPSHOT
eth-demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.web3j
core
3.4.0
com.github.briandilley.jsonrpc4j
jsonrpc4j
1.4.6
com.mashape.unirest
unirest-java
1.4.9
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
```
接下来在application.yml文件中配置以太坊节点路径,这个节点可以使用测试节点
```
spring:
application:
name: xiaobin-eth-demo
server:
port: 8080
web3j:
client-address: http://localhost:8545
```
再就是需要将Web3j对象交给Spring进行管理
```
package com.xiaobin.ethdemo.config;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 创建时间: 2019/9/23 23:21
* 备注:
* 码农自学交流小群:260532022,欢迎大家的加入,分享学习是一件开心事
**/
@Configuration
public class EthConfig {
@Value("${web3j.client-address}")
private String rpc;
@Bean
public Web3j web3j() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30*1000, TimeUnit.MILLISECONDS);
builder.writeTimeout(30*1000, TimeUnit.MILLISECONDS);
builder.readTimeout(30*1000, TimeUnit.MILLISECONDS);
OkHttpClient httpClient = builder.build();
Web3j web3j = Web3j.build(new HttpService(rpc,httpClient,false));
return web3j;
}
}
```
Controller测试一下
```
package com.xiaobin.ethdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
/**
* 创建时间: 2019/9/23 23:32
* 备注:
* 码农自学交流小群:260532022,欢迎大家的加入,分享学习是一件开心事
**/
@RestController
@RequestMapping("/eth")
public class WalletController {
@Autowired
private Web3j web3j;
@GetMapping("height")
public long getHeight() {
try {
EthBlockNumber blockNumber = web3j.ethBlockNumber().send();
long blockHeight = blockNumber.getBlockNumber().longValue();
return blockHeight;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
```
获取当前以太坊节点高度,访问结果图

当然还有更多的方法,这里没有去测试了,大家有空可以自己测测哦
#### 获取账户的Nonce
```
public static BigInteger getNonce(Web3j web3j, String addr) {
try {
EthGetTransactionCount getNonce = web3j.ethGetTransactionCount(addr, DefaultBlockParameterName.PENDING).send();
if (getNonce == null){
throw new RuntimeException("net error");
}
return getNonce.getTransactionCount();
} catch (IOException e) {
throw new RuntimeException("net error");
}
}
```
#### 获取ETH余额
```
public static BigInteger getNonce(Web3j web3j, String addr) {
try {
EthGetTransactionCount getNonce = web3j.ethGetTransactionCount(addr, DefaultBlockParameterName.PENDING).send();
if (getNonce == null){
throw new RuntimeException("net error");
}
return getNonce.getTransactionCount();
} catch (IOException e) {
throw new RuntimeException("net error");
}
}
```
#### 获取代币余额
```
public static BigInteger getTokenBalance(Web3j web3j, String fromAddress, String contractAddress) {
String methodName = "balanceOf";
List inputParameters = new ArrayList();
List> outputParameters = new ArrayList();
Address address = new Address(fromAddress);
inputParameters.add(address);
TypeReference typeReference = new TypeReference() {
};
outputParameters.add(typeReference);
Function function = new Function(methodName, inputParameters, outputParameters);
String data = FunctionEncoder.encode(function);
Transaction transaction = Transaction.createEthCallTransaction(fromAddress, contractAddress, data);
EthCall ethCall;
BigInteger balanceValue = BigInteger.ZERO;
try {
ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
List results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
balanceValue = (BigInteger) results.get(0).getValue();
} catch (IOException e) {
e.printStackTrace();
}
return balanceValue;
}
```
#### 转账ETH
```
public static String transferETH(Web3j web3j, String fromAddr, String privateKey, String toAddr, BigDecimal amount, String data){
// 获得nonce
BigInteger nonce = getNonce(web3j, fromAddr);
// value 转换
BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();
// 构建交易
Transaction transaction = Transaction.createEtherTransaction(fromAddr, nonce, gasPrice, null, toAddr, value);
// 计算gasLimit
BigInteger gasLimit = getTransactionGasLimit(web3j, transaction);
// 查询调用者余额,检测余额是否充足
BigDecimal ethBalance = getBalance(web3j, fromAddr);
BigDecimal balance = Convert.toWei(ethBalance, Convert.Unit.ETHER);
// balance ChainId.NONE){
signMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);
} else {
signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
}
String signData = Numeric.toHexString(signMessage);
if (!"".equals(signData)) {
try {
EthSendTransaction send = web3j.ethSendRawTransaction(signData).send();
txHash = send.getTransactionHash();
System.out.println(JSON.toJSONString(send));
} catch (IOException e) {
throw new RuntimeException("交易异常");
}
}
return txHash;
}
```
有什么问题或者缺少什么依赖包,可以加QQ群哦
###### 码农自学交流小群:260532022,欢迎大家的加入,分享学习是一件开心事
SpringBoot区块链之以太坊开发(整合Web3j)的更多相关文章
- SpringBoot区块链之以太坊区块高度扫描(简洁版)
继续昨天的demo往下写写:[SpringBoot区块链之以太坊开发(整合Web3j)](https://juejin.im/post/5d88e6c1518825094f69e887),将复杂的逻辑 ...
- android和java以太坊开发区块链应用使用web3j类库
如何使用web3j为Java应用或Android App增加以太坊区块链支持,教程内容即涉及以太坊中的核心概念,例如账户管理包括账户的创建.钱包创建.交易转账,交易与状态.智能合约开发与交互.过滤器和 ...
- 以太坊开发DApp入门教程——区块链投票系统(一)
概述 对初学者,首先要了解以太坊开发相关的基本概念. 学习以太坊开发的一般前序知识要求,最好对以下技术已经有一些基本了解: 一种面向对象的开发语言,例如:Python,Ruby,Java... 前 ...
- 以太坊开发DApp实战教程——用区块链、星际文件系统(IPFS)、Node.js和MongoDB来构建电商平台(一)
第一节 简介 欢迎和我们一起来用以太坊开发构建一个去中心化电商DApp!我们将用区块链.星际文件系统(IPFS).Node.js和MongoDB来构建电商平台类似淘宝的在线电商应用,卖家可以自由地出售 ...
- 以太坊开发(二)使用Ganache CLI在私有链上搭建智能合约
以太坊开发(二)使用Ganache CLI在私有链上搭建智能合约 在上一篇文章中,我们使用Truffle自带的客户端Truffle Develop,在私有链上搭建并运行了官方提供的WebPack智能合 ...
- 如何从零开始学习区块链技术——推荐从以太坊开发DApp开始
很多人迷惑于区块链和以太坊,不知如何学习,本文简单说了一下学习的一些方法和资源. 一. 以太坊和区块链的关系 从区块链历史上来说,先诞生了比特币,当时并没有区块链这个技术和名词,然后业界从比特币中提取 ...
- [币严区块链]以太坊(ETH)Dapp开发入门教程之宠物商店领养游戏
阅读本文前,你应该对以太坊.智能合约有所了解,如果你还不了解,建议你先看以太坊是什么 除此之外,你最好还了解一些HTML及JavaScript知识. 本文通过实例教大家来开发去中心化应用,应用效果如图 ...
- 关于书籍《区块链以太坊DApp开发实战》的内容告示
书中所列举的以太坊 etherscan 浏览器,原链接已经不能使用国内网络正常访问了,需要翻墙,下面的链接不需要翻墙,也是 etherscan 的官方浏览器链接: 以太坊浏览器:https://cn. ...
- 基于以太坊开发的类似58同城的DApp开发与应用案例
今天,Origin开发团队很高兴地宣布在以太坊Rinkeby测试网络上推出Origin Protocol Demo DApp ! 在这个DApp中,你可以在不同垂直行业的solidarity econ ...
随机推荐
- PostgreSQL入门教程(命令行)
初次安装完成后 1.默认生成一个名为postgres的数据库 2.一个名为postgres的数据库用户 3.这里需要注意的是,同时还生成了一个名为postgres的Linux系统用户. 下面,我们使用 ...
- 关于 MySQL查询当天、本周,本月,上一个月的数据
今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ...
- Python循环语句及函数的定义
循环语句¶ 重复执行某一个固定的动作或者任务 语法 for 变量 in序列: 语句1 语句2 ..... In [2]: # 列表知识只是以后会讲 # 比如[1,2,3,4,5,6,7] list ...
- C++的精度控制
#include <iostream> #include <iomanip> using namespace std; int main( void ) { const dou ...
- 持续集成高级篇之Jekins脚本参数化构建
系列目录 本系列已经很久没有更新了,接前面基础篇,本系统主要介绍jenkins构建里的一些高级特性.包括脚本参数化,Jenkins Pipeline与及在PipeLine模式下如何执行常见的传统构建任 ...
- nsq源码分析
nsq的源码比较简单,值得一读,特别是golang开发人员,下面重点介绍nsqd,看完这篇文章希望你能对消息队列的原理和实现有一定的了解. nsqd是一个守护进程,负责接收,排队,投递消息给客户端,并 ...
- Unity Shader 卡通渲染 基于退化四边形的实时描边
从csdn转移过来,顺便把写过的文章改写一下转过来. 一.边缘检测算法 3D模型描边有两种方式,一种是基于图像,即在所有3D模型渲染完成一张图片后,对这张图片进行边缘检测,最后得出描边效果.一种是基于 ...
- centos7.2+jdk7.9搭建haddoop2.7.0伪分布式环境(亲测成功)
最近想研究下hadoop,玩一玩大数据,废话不多说,就此开始! 所用环境: xshell 5.0(ssh连接工具,支持ftp,可向虚拟机传文件) CentOS-7-x86_64-DVD-1511. ...
- 【CF #541 D】 Gourmet choice
link:https://codeforces.com/contest/1131 题意: 给定一些大小比较,输出排名. 思路: 这道题我用的是拓扑排序,又因为有等于号的存在,我用了并查集. 结束后这道 ...
- BZOJ-2743: [HEOI2012]采花 前缀和 树状数组
BZOJ-2743 LUOGU:https://www.luogu.org/problemnew/show/P4113 题意: 给一个n长度的序列,m次询问区间,问区间中出现两次及以上的数字的个数.n ...