汪晓明对区块链、以太坊的思考

记录创业、生活的所思所感,探讨去中心化思想,推动区块链的发展。

HPB67:ETH DAPP到HPB主网平滑迁移攻略

1 概述

1.1 前言

本文档主要从技术角度对HPB区块链去中心化应用(以下简称“DAPP”)项目常用的演示案例,包括Web3js,JAVA

文档阅读人员:社区开发人员、测试人员、运维人员。

1.2 项目背景

为全面推进DAPP系统建设,落实软件产品线和领域工程的具体要求,形成自主产权基础框架和领域构件库,设立了DAPP项目。

2 把基于以太坊的ERC20的HPB代币平滑迁移到HPB区块链上

2.1 迁移流程如下

2.2 在太坊浏览器查询HPB ERC20 Token

进入以太坊浏览器查询HPB ERC20 Token

https://etherscan.io/tokens

在搜索框输入HPB,选择HPBCoin

2.3 复制HPB ERC20 Token源代码到remix

点击HPBERC20的智能合约地址

然后点击Code查看HPB ERC20的源代码

点击Copy复制源代码

打开solidity智能合约在线编译器

https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.11+commit.68ef5810.js

粘贴代码到编辑器中,选择编译器编译版本为v0.4.11

2.4 重新编译HPB ERC20 Token源代码

点击查看详情

2.5 通过HPB版本的javaSDK部署合约到HPB区块链然后调用智能合约

通过生成智能合约对应的java包装类面向对象式的运行智能合约

分别新建HPBToken.abi和HPBToken.bin文件并把以上复制的abi和bin代码复制到对应的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
引入HPB的java SDk

<dependency>

    <groupId>io.hpb.web3</groupId>

    <artifactId>web3-hpb</artifactId>

    <version>1.2.0</version>

</dependency> 

//新建生成合约包装类GenContract

import java.util.Arrays;

import io.hpb.web3.codegen.SolidityFunctionWrapperGenerator;

public class GenContract {

                  public static void main(String[] args) {

                                    try {

                                    String SOLIDITY_TYPES_ARG = "--solidityTypes";

                                    String packageName = "io.hpb.web3.contracts";

                                    String outDirPath = "D:/contracts/java/";

                                    String binDirPath = "D:/contracts/HPBToken.bin";

                                    String abiDirPath = "D:/contracts/HPBToken.abi";

                                                                                          SolidityFunctionWrapperGenerator.main(Arrays.asList(SOLIDITY_TYPES_ARG,
                                                                                      binDirPath,
                                                                                  abiDirPath,
                                                                                       "-p", packageName, "-o", outDirPath).toArray(new String[0]));

                                    } catch (Exception e) {

                                                      e.printStackTrace();
                                    }

                  }

}

   

//生成后的类为HPBToken.java

//删除掉所有构造方法

protected HPBToken(String contractAddress, Web3 web3, Credentials credentials,

            BigInteger gasPrice, BigInteger gasLimit) {

        super(BINARY, contractAddress, web3, credentials, gasPrice, gasLimit);

}

protected HPBToken(String contractAddress, Web3 web3, TransactionManager transactionManager,BigInteger gasPrice, BigInteger gasLimit) {

        super(BINARY, contractAddress, web3, transactionManager, gasPrice, gasLimit);

}

//添加新的构造方法

protected HPBToken(String contractAddress, Web3 web3, Credentials credentials,

        BigInteger gasPrice, BigInteger gasLimit) {

     super(BINARY, contractAddress, web3, new RawTransactionManager(web3, credentials), new StaticGasProvider(gasPrice, gasLimit));

}

 

protected HPBToken(String contractAddress, Web3 web3, TransactionManager transactionManager,BigInteger gasPrice, BigInteger gasLimit) {

     super(BINARY, contractAddress, web3, transactionManager, new StaticGasProvider(gasPrice, gasLimit));

}

protected HPBToken(String contractAddress,

            Web3 web3, TransactionManager transactionManager,ContractGasProvider gasProvider) {

                  super(BINARY, contractAddress, web3, transactionManager, gasProvider);

}

自行在本地建立HPB开发者节点,发布智能合约和调用智能合约,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
private static final int WEB3J_TIMEOUT = 800;

                  public static void main(String[] args) throws Exception{

                                    BigInteger gasPrice = Convert.toWei("18", Convert.Unit.GWEI).toBigInteger();

                                    BigInteger gasLimit = new BigInteger("99000000");

                                    Credentials credentials = WalletUtils.loadCredentials(password,keyStorePath);

                                    Web3Service web3Service = buildService(clientAddress);

                                    Admin admin = Admin.build(web3Service);

                                    RawTransactionManager transactionManager=new RawTransactionManager(admin, credentials, ChainId.MAINNET);

                                    Address _target=new Address(address);

                                    HPBToken hpbTokenDeploy = HPBToken.deploy(admin, transactionManager, gasPrice, gasLimit, _target).

                                    sendAsync().get(WEB3J_TIMEOUT, TimeUnit.MINUTES);

                                    String contractAddress=hpbTokenDeploy.getContractAddress();

                                    log.info("发布智能合约成功,合约地址为:"+contractAddress);

                                    HPBToken hpbToken = HPBToken.load(contractAddress, admin, transactionManager, gasPrice, gasLimit);

                                    Bool bool = hpbToken.saleStarted().sendAsync().get(WEB3J_TIMEOUT, TimeUnit.MINUTES);

                                    log.info(bool);

TransactionReceipt receipt = hpbToken.transfer(new Address("0x09fe745cff05b35cb06da6768586279018c08d7f"), 

                                                                        new Uint256(Convert.toWei("10", Convert.Unit.HPB).toBigInteger())).sendAsync()

                                    .get(WEB3J_TIMEOUT, TimeUnit.MINUTES);

                                    log.info(receipt.isStatusOK());

                  }

                  private static Web3Service buildService(String clientAddress) {

                                    Web3Service Web3Service;

                                    if (clientAddress == null || clientAddress.equals("")) {

                                    Web3Service = new HttpService(createOkHttpClient());

                                    } else if (clientAddress.startsWith("http")) {

                                    Web3Service = new HttpService(clientAddress,       createOkHttpClient(), false);

                                    } else if (System.getProperty("os.name").toLowerCase().startsWith("win")) {

                                    Web3Service = new WindowsIpcService(clientAddress);

                                    } else {

                                   Web3Service = new UnixIpcService(clientAddress);

                                    }

 

                                    return Web3Service;

                  }

 

                  private static OkHttpClient createOkHttpClient() {

                          OkHttpClient.Builder builder = new OkHttpClient.Builder();

                           configureLogging(builder);

                           configureTimeouts(builder);

                           return builder.build();

                  }

 

                  private static void configureTimeouts(OkHttpClient.Builder builder) {

                           builder.connectTimeout(WEB3J_TIMEOUT, TimeUnit.SECONDS);

                           builder.readTimeout(WEB3J_TIMEOUT, TimeUnit.SECONDS); 
                           // Sets the socket timeout too

                           builder.writeTimeout(WEB3J_TIMEOUT, TimeUnit.SECONDS);

                  }


                  private static void configureLogging(OkHttpClient.Builder builder) {

                       if (log.isDebugEnabled()) {

                         HttpLoggingInterceptor logging = new HttpLoggingInterceptor(log::debug);
                                                   logging.setLevel(HttpLoggingInterceptor.Level.BODY);

                        builder.addInterceptor(logging);

                                    }

                  }

2.6 通过PB版本的Web3js部署合约到HPB区块链然后调用智能合约

Web3.js实现部署和调用合约代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var Web3ForHpb = require('web3_hpb');

var web3Hpb = new Web3ForHpb();

web3Hpb.setProvider(new web3Hpb.providers.HttpProvider("http://localhost:8545"));

web3Hpb.hpb.contract(abi).new({

    data: '0x' + bytecode,

    from: "",

    gas: 1000000

}, (err, res) => {

    if (err) {

        console.log(err);

        return;

    }

    console.log(res.transactionHash);

    // If we have an address property, the contract was deployed

    if (res.address) {

        console.log('Contract address: ' + res.address);

    }

});
 var hpbTestContract = web3Hpb.hpb.contract(abi).at(contractAddress);

console.log(hpbTestContract.getContractAddr.call());

3 迁移总结

任何基于以太坊区块链的Dapp的合约代码都可以通过相同的流程平滑迁移到HPB的区块链上;复制原始智能合约代码,利用remix来重新编译,拷贝对应的编译好的bin和abi文件,通过HPB版本的javaSDK和HPB版本的web3js来发布和调用该DAPP的智能合约。

感谢HPB技术团队整理。

关于我

蓝莲花(汪晓明):HPB芯链(hpb.io)创始人,巴比特专栏作家。十余年金融大数据、区块链技术开发经验,曾参与创建银联大数据。主创区块链教学视频节目《明说》30多期,编写了《以太坊官网文档中文版》,并作为主要作者编写了《区块链开发指南》,在中国区块链社区以ID“蓝莲花”知名。2018年6月9日, HPB芯链荣登《2018胡润区块链企业排行榜》区块链创新企业TOP50。

公众号
小明微思考公众号

HPB

« HPB66:HPB钱包和中间件接口介绍 HPB68:HPB DAPP 介绍 »