当前位置: 首页 > news >正文

Java基于Web3j调用智能智能合约案例

下面将提供一个完整的Java调用智能合约的示例,包括环境配置、合约部署和调用方法。

1. 环境准备

添加依赖

<!-- Maven 依赖 -->
<dependencies><dependency><groupId>org.web3j</groupId><artifactId>core</artifactId><version>4.9.7</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.30</version></dependency>
</dependencies>

2. 智能合约示例

Solidity合约代码

// SimpleStorage.sol
pragma solidity ^0.8.0;contract SimpleStorage {uint256 private value;string private text;event ValueChanged(uint256 newValue);event TextChanged(string newText);function setValue(uint256 _value) public {value = _value;emit ValueChanged(_value);}function getValue() public view returns (uint256) {return value;}function setText(string memory _text) public {text = _text;emit TextChanged(_text);}function getText() public view returns (string memory) {return text;}
}

3. Java调用代码

主要工具类

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.DefaultGasProvider;
import java.math.BigInteger;public class ContractCaller {private Web3j web3j;private Credentials credentials;private String contractAddress;public ContractCaller(String nodeUrl, String privateKey) {this.web3j = Web3j.build(new HttpService(nodeUrl));this.credentials = Credentials.create(privateKey);}/*** 部署合约*/public String deployContract() throws Exception {SimpleStorage contract = SimpleStorage.deploy(web3j, credentials, new DefaultGasProvider()).send();this.contractAddress = contract.getContractAddress();System.out.println("合约部署成功,地址: " + contractAddress);return contractAddress;}/*** 加载已部署的合约*/public SimpleStorage loadContract(String contractAddress) {return SimpleStorage.load(contractAddress, web3j, credentials, new DefaultGasProvider());}/*** 调用合约的写方法*/public void setValue(String contractAddress, BigInteger value) throws Exception {SimpleStorage contract = loadContract(contractAddress);TransactionReceipt receipt = contract.setValue(value).send();System.out.println("设置值成功,交易哈希: " + receipt.getTransactionHash());}/*** 调用合约的读方法*/public BigInteger getValue(String contractAddress) throws Exception {SimpleStorage contract = loadContract(contractAddress);BigInteger value = contract.getValue().send();System.out.println("获取的值: " + value);return value;}/*** 设置文本*/public void setText(String contractAddress, String text) throws Exception {SimpleStorage contract = loadContract(contractAddress);TransactionReceipt receipt = contract.setText(text).send();System.out.println("设置文本成功,交易哈希: " + receipt.getTransactionHash());}/*** 获取文本*/public String getText(String contractAddress) throws Exception {SimpleStorage contract = loadContract(contractAddress);String text = contract.getText().send();System.out.println("获取的文本: " + text);return text;}
}

测试类

import java.math.BigInteger;public class ContractCallerTest {public static void main(String[] args) {try {// 配置参数String nodeUrl = "https://mainnet.infura.io/v3/YOUR_PROJECT_ID"; // 以太坊节点String privateKey = "YOUR_PRIVATE_KEY"; // 私钥ContractCaller caller = new ContractCaller(nodeUrl, privateKey);// 1. 部署合约String contractAddress = caller.deployContract();// 2. 设置数值caller.setValue(contractAddress, BigInteger.valueOf(12345));// 3. 读取数值BigInteger value = caller.getValue(contractAddress);// 4. 设置文本caller.setText(contractAddress, "Hello Web3j!");// 5. 读取文本String text = caller.getText(contractAddress);} catch (Exception e) {e.printStackTrace();}}
}

4. 使用Web3j命令行工具生成Java包装类

生成Java包装类步骤:

# 1. 安装web3j命令行工具
curl -L get.web3j.io | sh# 2. 编译Solidity合约
solc SimpleStorage.sol --bin --abi --optimize -o build/# 3. 生成Java包装类
web3j generate solidity -b build/SimpleStorage.bin -a build/SimpleStorage.abi -o src/main/java -p com.yourpackage.contracts

生成的Java包装类(部分):

// 这是web3j自动生成的合约包装类
public class SimpleStorage extends Contract {public static final String BINARY = "0x606060..."; // 合约字节码public SimpleStorage(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {super(BINARY, contractAddress, web3j, credentials, contractGasProvider);}// 合约方法...
}

5. 高级功能示例

事件监听

public class EventListener {public void listenToEvents(String contractAddress, Web3j web3j, Credentials credentials) throws Exception {SimpleStorage contract = SimpleStorage.load(contractAddress, web3j, credentials, new DefaultGasProvider());// 监听ValueChanged事件contract.valueChangedEventFlowable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST).subscribe(event -> {System.out.println("值改变事件: " + event.newValue);});// 监听TextChanged事件contract.textChangedEventFlowable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST).subscribe(event -> {System.out.println("文本改变事件: " + event.newText);});}
}

错误处理

public class ContractCallerWithErrorHandling {public void safeContractCall(String contractAddress, BigInteger value) {try {ContractCaller caller = new ContractCaller("YOUR_NODE_URL", "YOUR_PRIVATE_KEY");caller.setValue(contractAddress, value);} catch (Exception e) {if (e.getMessage().contains("insufficient funds")) {System.out.println("余额不足");} else if (e.getMessage().contains("gas required exceeds allowance")) {System.out.println("Gas不足");} else {System.out.println("调用失败: " + e.getMessage());}}}
}

6. 配置说明

重要配置参数

public class Web3jConfig {// 不同的网络配置public static final String MAINNET = "https://mainnet.infura.io/v3/YOUR_PROJECT_ID";public static final String ROPSTEN = "https://ropsten.infura.io/v3/YOUR_PROJECT_ID";public static final String GANACHE = "http://localhost:7545";// Gas配置public static class CustomGasProvider extends DefaultGasProvider {@Overridepublic BigInteger getGasPrice() {return BigInteger.valueOf(20_000_000_000L); // 20 Gwei}@Overridepublic BigInteger getGasLimit() {return BigInteger.valueOf(300_000L);}}
}

注意事项

  1. 私钥安全: 永远不要在代码中硬编码私钥,使用环境变量或安全配置
  2. Gas费用: 合理设置Gas价格和限制
  3. 错误处理: 完善的异常处理机制
  4. 网络选择: 根据需求选择合适的网络(主网、测试网、本地网络)
http://www.dtcms.com/a/485761.html

相关文章:

  • 关于联想ThinkCentre M950t-N000 M大师电脑恢复预装系统镜像遇到的一点问题
  • 有关优化网站建设的书籍深圳网络推广方法
  • 招聘网站做竞品分析南昌网站seo多少钱
  • 【实战总结】Docker部署MySQL完整教程:附docker-compose模板与常用命令大全
  • C++ string类的使用
  • 【数据结构】:C 语言常见排序算法的实现与特性解析
  • C语言数据结构:算法复杂度(1)
  • 16km无人机WiFi中继图传模块,高速传输画质高清不卡顿
  • Linux系统C++开发环境搭建工具(二)—— etcd 使用指南
  • AI+大数据时代:如何从架构到生态重构时序数据库的价值?
  • 小小 Postgres,何以替代 Redis、MongoDB 甚至 ES?
  • Win10正式谢幕!附最后更新版本
  • 前端自动翻译插件webpack-auto-i18n-plugin的使用
  • 山东官方网站建设沧州网络推广渠成网络
  • 贺州网站建设公司家装设计需要学什么软件
  • 网站在百度上搜索不到丽水山耕品牌建设网站
  • 漂亮的门户网站dedecms游戏门户网站源码
  • thinkphp2.1网站挂文件国有企业投资建设项目
  • 网站首页的动态视频怎么做的建网站的流程和费用
  • 一些可以做翻译的网站微信小程序制作文档
  • 东莞公司网站开发首页制作教程
  • 河北大名网站建设招聘深圳网站设计首选柚米
  • 网站友链中英文外贸网站模版
  • html5企业网站模版经营一个网站要怎么做
  • 专业点网站制作公司龙泉市建设局网站
  • 网站设计资源seo优化网站的注意事项
  • 深圳网站运营托管163邮箱怎么申请企业邮箱
  • 孝感市门户网站传媒wordpress博客
  • 做网站推广的销售电话开场白wordpress注册邮箱怎么修改
  • 在哪公司建设网站东莞seo关键词搜索关键词