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 ...
随机推荐
- 如何将自己的代码发布到Maven中央仓库?
去年在公司做工作流相关业务时,当时使用flowable做引擎,中途涉及到一些业务上的需求,自己整理了一些代码,考虑到开源精神,当时就想着将于公司业务无关的代码抽离出来,放到Maven中央仓库中,以供别 ...
- vscode保存代码,自动按照eslint规范格式化代码设置
# vscode保存代码,自动按照eslint规范格式化代码设置 编辑器代码风格一致,是前端代码规范的一部分.同一个项目,或者同一个小组,保持代码风格一致很必要.就拿vue项目来说,之前做的几个项目, ...
- es6 个人笔记
1.package.json==>npm init node_modules==>npm install webpack -D webpack.config.js==> ...
- 枚举类&&注解&&反射
什么是枚举类? 枚举类是优化定义固定对象的一种特殊的类. 换句话说,在需要类的实例为一个或者多个并且相对固定的时候,使用枚举类.(枚举类可扩展) 类的实例相对来说固定的有日期,客观不变的一些数字等等. ...
- 驰骋工作流引擎与jFinal集成版本2.0
驰骋工作流引擎与jFinal集成版本2.0 发布说明 关键字: 驰骋工作流程快速开发平台 工作流程管理系统java工作流引擎. 使用协议:GPL. 关于JFinal: https://www.jfin ...
- 12款好用超赞的国外搜索资源网站 ,开发者们的标配,你都知道吗?不知道就OUT了
简介 看了 看了网上有好多推荐插件的文章,很少有推荐搜索资源网站,于是今天决定推荐一波搜索资源网站.这些网站带给我开阔视眼增长知识.所以在这里整理一下,分享给朋友和博友们. 学习技术过程我们经常需要使 ...
- cucumber测试框架
1.1 什么是BDD(行为驱动开发) 首先了解一个概念,BDD(BehaviorDrivenDevelopment:行为驱动开发)为用户提供了从 开发人员和客户的需求创建测试脚本的机会.因此,开始时 ...
- JSP学习笔记(1)——Jsp指令、动作元素和内置对象
简单来说,javaweb技术就是让服务器端能够执行Java代码,之后返回数据给客户端(浏览器)让客户端显示数据 jsp页面中可以嵌套java代码(java小脚本)和嵌套Web前端(html,css,j ...
- 【IDEA】在IDEA中使用@Slf4j报错,找不到log
题:在IDEA中使用@Slf4j报错,找不到log 解决方法:需要在IDEA中安装插件lombok 详细步骤: 1.File->Settings 2.Plugins->Browse rep ...
- Delphi - 互斥对象下实现系统的单例模式
使用CreateMutex函数创建互斥对象 利用Windows系统函数CreateMutex(),找出当前系统是否已经存在指定进程的实例,如果没有则创建一个互斥体. CreateMutex函数原型如下 ...