新建合约项目
hvm的智能合约最好新建一个maven项目,一般通过模板来创建其中参数如下:
GroupId:cn.hyperchain
ArtifactId:java-contract-archetype
Version:1.0.2
项目中分为了两个部分:合约(SBank),调用接口(ISBank)
接口是提供给应用程序使用的
合约编译
使用命令:mvn compile
mvn jar
生成jar包即可部署
合约部署
直接读取jar包部署
代码如下
DefaultHttpProvider defaultHttpProvider=new DefaultHttpProvider.Builder().setUrl(url).build();
ProviderManager providerManager = ProviderManager.createManager(defaultHttpProvider);
ContractService contractService = ServiceManager.getContractService(providerManager);
AccountService accountService = ServiceManager.getAccountService(providerManager);
Account account = accountService.genAccount(Algo.ECRAW);
InputStream inputStream1 = new BufferedInputStream(new FileInputStream("target/TrainingPlatformContract-1.0-SNAPSHOT.jar"));
Transaction transaction=new Transaction.HVMBuilder(account.getAddress())
.deploy(inputStream1)
.build();
transaction.sign(account);
ReceiptResponse receiptResponse = contractService.deploy(transaction).send().polling();
String contractAddress = receiptResponse.getContractAddress();
System.out.println("contract address: " + contractAddress);
System.out.println("帐户地址:"+account.getAddress());
System.out.println("账户私钥:" + account.getPrivateKey());
合约调用
首先每个方法需要在应用程序中编写一个InvokeBean类,举例:
public class InvokeTransfer implements BaseInvoke<Boolean, ISBank> {
private String from;
private String to;
private int value;
public InvokeTransfer(){
}
public InvokeTransfer(String from,String to,int value){
this.from=from;
this.to=to;
this.value=value;
}
...
}
调用代码:
Transaction transaction1 = new Transaction.HVMBuilder(account.getAddress()).invoke(receiptResponse.getContractAddress(), new InvokeTransfer("1","2",1)).build();
transaction1.sign(account);
ReceiptResponse receiptResponse1 = contractService.invoke(transaction1).send().polling();
System.out.println(receiptResponse1.getRet());