以太坊 DAPP 到 HPB 区块链的平滑迁移案例

优质
小牛编辑
132浏览
2023-12-01

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/

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

2.4 重新编译HPB ERC20 Token源代码

点击查看详情

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

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

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

引入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开发者节点,发布智能合约和调用智能合约,代码如下

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实现部署和调用合约代码如下

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的智能合约。