青年下载站
首页 > 区块链 > 区块链百科 > 

Java波场链交易入门

作者:佚名 来源:青年下载站 2023-11-21 21:00:27

由于最近做的项目是关于波场链的,所以写一下

波场链和以太坊有很大的不同,它没有开源节点,只能使用私有节点或者波场官方的节点,官方推荐的java客户端是trident-java。

1、安装trident-java

trident-java没有现成的maven包,需要用GitHub源码自行打包,Github源码地址:https://github.com/tronprotocol/trident

要编译打包trident项目,需要java 1.8.0_231版本,和Gradle 5.6.4版本,java和gradle的安装,请自行百度,这里就不多说。

将源码下载下来后,解压,然后需要把这些依赖包加入build.gradle配置文件中:
dependencies {
// protobuf & grpc
implementation 'com.google.protobuf:protobuf-java:3.11.0'

implementation 'io.grpc:grpc-netty-shaded:1.31.0'
implementation 'io.grpc:grpc-netty:1.31.0'
implementation 'io.grpc:grpc-protobuf:1.31.0'
implementation 'io.grpc:grpc-stub:1.31.0'

implementation "org.bouncycastle:bcprov-jdk15on:1.68"

implementation fileTree(dir:'../core')
implementation fileTree(dir:'../utils')
implementation fileTree(dir:'../abi')
//if you are using the *.jar files, ues the following line
implementation fileTree(dir:'your path', include: '*.jar')

implementation 'com.google.guava:guava:28.0-jre'
}
 

配置好之后,进入解压后的目录,运行命令:

gradle install

这个命令会直接将打包好的jar包,安装进本地maven仓库中,于是在本地的maven项目,就可以引用依赖:

 		<dependency>
			<groupId>org.tron.trident</groupId>
			<artifactId>abi</artifactId>
			<version>0.8.0</version>
		</dependency>
		<dependency>
			<groupId>org.tron.trident</groupId>
			<artifactId>utils</artifactId>
			<version>0.8.0</version>
		</dependency>
		<dependency>
			<groupId>org.tron.trident</groupId>
			<artifactId>core</artifactId>
			<version>0.8.0</version>
		</dependency>

 

2、使用trident-java

配置好maven依赖之后,就可以使用了,在trident-java中,ApiWrapper是访问波场api以及智能合约方法的入口:

可以有几种方法创建入口实体:

(1)如果你有自己的私有节点,那就使用这个方法

ApiWrapper wrapper = new ApiWrapper("grpc endpoint", "solidity grpc endpoint", "hex private key");

 

(2)如果你要使用波场公开的主网节点,需要去TronGrid注册一个ApiKey,并通过以下方式创建,TronGrid网址: https://www.trongrid.io/

ApiWrapper wrapper = ApiWrapper.ofMainnet("hex private key", "API key");

 

(3)对于只获取数据,非交易类型的接口,并不需要private key,那么"private key"可以随意填写64个字母长度的字符串替代

ApiWrapper wrapper = ApiWrapper.ofMainnet("64 characters", "API key");

 

这里写一个小应用案例,获取某个hash的交易详情:

public static void main(String[] args) throws IllegalException {
        String privateKey = "c71fcbba5e6e23944a9a339e4368afbb5549a16a348b30fdd91dfb05cfff6d05";
        String apiKey = "be40fbd3-0fa7-49ba-98fb-ddca96398ca8";
        String hash = "b989f26676e951906854f43315505275aa43c24e84a6f0060d3214961234d067";
        ApiWrapper apiWrapper = ApiWrapper.ofMainnet(privateKey, apiKey);
        Chain.Transaction transaction = apiWrapper.getTransactionById(hash);
        System.out.println("transaction: " + JSONUtil.toJsonStr(transaction));
}
网友评论
评论:
返回顶部