代码示例
接口使用流程示例
说明:为了更好的理解接口的使用,本示例将从创建账户、编译合约、部署合约、调用合约和返回值解析这个大致流程作介绍,具体详细接口可参考API接口。
1 初始化服务
首先获取对应的Service服务,在获取Service服务时需要指定一个ProviderManager实例。
// 获取providerManager
DefaultHttpProvider defaultHttpProvider = new DefaultHttpProvider.Builder().setUrl(DEFAULT_URL).build();
ProviderManager providerManager = ProviderManager.createManager(defaultHttpProvider);
// 获取对应的服务
ContractService contractService = ServiceManager.getContractService(providerManager);
AccountService accountService = ServiceManager.getAccountService(providerManager);
2 创建账户
使用初始化好的AccountService创建一个账户
Account account = accountService.genSM2Account();
3 构造交易
构造交易传入需要的交易参数,详细使用见交易封装
Transaction transaction = new Transaction.HVMBuilder(account.getAddress())
.deploy("hvm-jar/hvmbasic-1.0.0-student.jar")
.build();
4 发送请求
使用初始化好的ContractService完成请求的发送,需要指定交易,拿到结果
ReceiptResponse receiptResponse = contractService.deploy(transaction).send().polling();
5 解析结果
使用Decoder中的方法进行对应的解码操作
Decoder.decodeHVM(receiptResponse.getRet(), String.class);
HVM合约完整示例
// 初始化服务
DefaultHttpProvider defaultHttpProvider = new DefaultHttpProvider.Builder().setUrl(DEFAULT_URL).build();
ProviderManager providerManager = ProviderManager.createManager(defaultHttpProvider);
ContractService contractService = ServiceManager.getContractService(providerManager);
AccountService accountService = ServiceManager.getAccountService(providerManager);
// 创建账户
Account account = accountService.genSM2Account();
// 构造交易
Transaction transaction = new Transaction.HVMBuilder(account.getAddress())
.deploy("hvm-jar/hvmbasic-1.0.0-student.jar")
.build();
// 发送部署请求
ReceiptResponse receiptResponse = contractService.deploy(transaction).send().polling();
System.out.println("合约地址: " + receiptResponse.getContractAddress());
System.out.println("部署返回(未解码): " + receiptResponse.getRet());
System.out.println("部署返回(解码):" + Decoder.decodeHVM(receiptResponse.getRet(), String.class));
// 调用合约
Transaction transaction1 = new Transaction.HVMBuilder(account.getAddress()).invoke(receiptResponse.getContractAddress(), new StudentInvoke()).build();
ReceiptResponse receiptResponse1 = contractService.invoke(transaction1).send().polling();
// 结果解码
System.out.println("调用返回(未解码): " + receiptResponse1.getRet());
System.out.println("调用返回(解码):" + Decoder.decodeHVM(receiptResponse1.getRet(), String.class));