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 ...
随机推荐
- asp.net core系列 71 Web架构分层指南
一.概述 本章Web架构分层指南,参考了“Microsoft应用程序体系结构指南”(该书是在2009年出版的,当时出版是为了帮助开发人员和架构师更快速,更低风险地使用Microsoft平台和.NET ...
- Flink的JobManager启动(源码分析)
都知道Flink中的角色分为Jobmanager,TaskManger 在启动脚本里面已经找到了jobmanager的启动类org.apache.flink.runtime.entrypoint.St ...
- c++json构建与解析组件 RapidJSON 没用过永远不会知道有多好用
参考资料: 官方文档 推荐[腾讯RapidJSON]学习笔记 原理请参考以上资料 构建json Document doc; Document::AllocatorType &allocator ...
- 漏洞挖掘技巧之利用javascript:
好久没更新博客了,更新一波. 场景: window.location.href=”” location=”” location.href=”” window.location.* 常见地点:任何二次跳 ...
- think in java 泛型
曾几何时,我们对java的泛型充满了好奇,但是感觉用起来有很爽,但又会在spring类型泛型的地方,遇到问题. 我第一次的遇到泛型是在使用别人的BaseDao的时候,这是一个java封装hiberna ...
- Azure DevOps vsts-agent-linux 安装出错, Must not run with sudo
在linux安装 vsts-agent-linux 在vsts-agent-linux的解压目录运行./config.sh, 提示"Must not run with sudo", ...
- 六大设计原则(C#)
为什么要有设计原则,我觉得一张图片就可以解释这一切 一.单一职责原则(SRP) 对于一个类而言,应该只有一个发生变化的原因.(单一职责不仅仅是指类) 如果一个模块需要修改,它肯定是有原因的,除此原因之 ...
- 【RabbitMQ】如何进行消息可靠投递【下篇】
说明 上一篇文章里,我们了解了如何保证消息被可靠投递到RabbitMQ的交换机中,但还有一些不完美的地方,试想一下,如果向RabbitMQ服务器发送一条消息,服务器确实也接收到了这条消息,于是给你返回 ...
- ZAO 换脸不安全?用 python 轻松实现 AI
最近两天一款名为 「ZAO」 的 App 刷爆了朋友圈,它的主打功能是 AI 换脸,宣称「只需一张照片,就能出演天下好戏」 : 现实中不能实现当明星的梦,在这个 App 里你可以,想演谁演谁.新鲜.好 ...
- Oracle大量数据更新策略
生产上要修改某个产品的产品代号, 而我们系统是以产品为中心的, 牵一发而动全身, 涉及表几乎覆盖全部, 有些表数据量是相当大的, 达到千万, 亿级别. 单纯的维护产品代号的 SQL 是不难的, 但是性 ...