智能合约 web3j Java_Java使用web3j调用智能合约

1.Java程序引入相关依赖,后面用于调用智能合约中的函数

org.web3j

core

5.0.0

org.web3j

codegen

5.0.0

org.fisco-bcos

solcJ

0.5.2.0

commons-io

commons-io

2.4

com.squareup.okhttp3

okhttp

4.4.0

com.squareup.okhttp3

okhttp-ws

3.4.2

2.将合约使用remix进行编译

智能合约 web3j Java_Java使用web3j调用智能合约_第1张图片

编译后,复制abi、Bytecode,放入指定位置,生成abi和bin文件

c4c62c3d04fea85444605213919f762c.png

@Test

void generateABIAndBIN() {

String abi = "abi复制放这里";

String bin = "bin复制过来放这里";

String abiFileName = "abi文件名.abi";

String binFileName = "bin文件名.bin";

File abiFile = new File("E:\\solidity\\xx\\xx\\"+ abiFileName);

File binFile = new File("E:\\solidity\\xx\\xx\\"+ binFileName);

if (!abiFile.getParentFile().exists()) {

boolean result = abiFile.getParentFile().mkdirs();

if (!result) {

System.out.println("创建失败");

}

}

BufferedOutputStream abiBos = null;

BufferedOutputStream binBos = null;

try {

FileOutputStream abiFos = new FileOutputStream(abiFile);

FileOutputStream binFos = new FileOutputStream(binFile);

abiBos = new BufferedOutputStream(abiFos);

binBos = new BufferedOutputStream(binFos);

abiBos.write(abi.getBytes());

abiBos.flush();

binBos.write(bin.getBytes());

binBos.flush();

}catch (Exception e) {

throw new RuntimeException("写入过程出现错误");

}finally {

if(abiBos != null) {

try {

abiBos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(binBos != null) {

try {

binBos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

@Test

public void generateClass() throws IOException, ClassNotFoundException {

String[] args = Arrays.asList(

"-a", "D:/solidity/xx/xx.abi",

"-b", "D:/solidity/xx/xx.bin",

"-p", "top.rhynie.xx.contract",

"-o", "D:/IDEA_Project/xx/src/main/java"

).toArray(new String[0]);

Stream.of(args).forEach(System.out::println);

SolidityFunctionWrapperGenerator.main(args);

}

4.注册infura获取免费节点

智能合约 web3j Java_Java使用web3j调用智能合约_第2张图片

5.java代码调用只能合约代码

@Test

void deployContract() throws Exception {

Web3j web3 = Web3j.build(new HttpService("https://ropsten.infura.io/v3/xxxx"));

String ownAddress = "0x119Eb8E686423E56b7cfc6F211C8CD4a9F71E3Cc";

// Credentials c = WalletUtils.loadCredentials("密码","keystore文件地址");

Credentials credentials = Credentials.create("私钥");

AWToken awToken = AWToken.deploy(web3, credentials, web3.ethGasPrice().send().getGasPrice(), Contract.GAS_LIMIT).send();

System.out.println(awToken.getContractAddress());

// 调用合约的函数

awToken.transfer("0x0", value);

}

你可能感兴趣的:(智能合约,web3j,Java)