http://www.7klian.com

HPB 智能合约最佳实践

//1通过 io.hpb.web3 来生成智能合约 sol 源码的的映射类然后把映射的类放到对应的 package GenContractJavaCode(packageName, binFilePath, abiFilePath, outDirPath) ; //2宣布智能合约并获取地点 String address = depolyUFOTokenTest(); //3获得智能合约的余额 getUFOTokenContractBalance(); // 查询指定地点的 erc20 余额 String queryAddress = "0xd8ACcED8A7A92b334007f9C6127A848fE51D3C3b"; //4校验智能合约并打印相关的信息 checkUFOTokenContract(queryAddress); //5转账 String toAddress = "0x6cb988b9ce48Fd3b5a328B582dd64F5C10d0E114"; transferUFOTokenContract(toAddress,"13333333000000000000000000"); //5.2 查询余额 //checkUFOTokenContract(contractAddress,toAddress); } /** * 通过智能合约的源码 .sol 文件和编译后的 .bin 文件生成 java 的源码 * String packageName:java 源码的 packagename * String binFileName:存放智能合约 bin 文件地点 * String abiFileName:存放智能合约的 abi 文件地点 * String outDirPath :java 源码输出地点 **/ public static void GenContractJavaCode(String packageName,String binFilePath,String abiFilePath,String outDirPath) { try { String SOLIDITY_TYPES_ARG = "--solidityTypes"; SolidityFunctionWrapperGenerator.main(Arrays.asList(SOLIDITY_TYPES_ARG, binFilePath,abiFilePath,"-p",packageName, "-o", outDirPath).toArray(new String[0])); } catch (Exception e) { e.printStackTrace(); } } /** * 通过编译智能合约源码获得合约映射的 java 类 **/ public static String depolyUFOTokenTest(){ Credentials credentials = null; Admin admin = null; String contractAddress = ""; try{ Web3Service web3Service = new HttpService(blockChainUrl, new OkHttpClient.Builder().build(), true); admin = Admin.build(web3Service); credentials = WalletUtils.loadCredentials(fromPassword, keyStoreAbsolutePath); RawTransactionManager transactionManager=new RawTransactionManager(admin, credentials, ChainId.MAINNET); // 1. 宣布 TOKEN UFOToken contract = UFOToken.deploy(admin, transactionManager, GAS_PRICE, GAS_LIMIT).send(); System.out.println(" 合约地点:" + contract.getContractAddress()); contractAddress = contract.getContractAddress(); }catch (Exception e){ e.printStackTrace(); } return contractAddress; } /** * 查询余额 **/ public static BigDecimal getUFOTokenContractBalance(){ Credentials credentials = null; Admin admin = null; BigDecimal balanceWeiAmt = null; try{ Web3Service web3Service = new HttpService(blockChainUrl, new OkHttpClient.Builder().build(), true); admin = Admin.build(web3Service); BigInteger balance = admin.hpbGetBalance(address, DefaultBlockParameterName.LATEST).send().getBalance(); balanceWeiAmt = Convert.fromWei(balance.toString(), Convert.Unit.HPB); System.out.println(address + " 账户余额:" + balanceWeiAmt); }catch (Exception e){ e.printStackTrace(); } return balanceWeiAmt; } /** * 校验智能合约并打印地点 ERC20 余额 **/ public static void checkUFOTokenContract(String queryAddress){ Credentials credentials = null; Admin admin = null; try{ Web3Service web3Service = new HttpService(blockChainUrl, new OkHttpClient.Builder().build(), true); admin = Admin.build(web3Service); credentials = WalletUtils.loadCredentials(fromPassword, keyStoreAbsolutePath); RawTransactionManager transactionManager=new RawTransactionManager(admin, credentials, ChainId.MAINNET); // 查抄合约是否可用 UFOToken contract = UFOToken.load(address, admin, transactionManager, GAS_PRICE, GAS_LIMIT); System.out.println(" 验证合约是否有效 :" +contract.isValid() ); if(contract.isValid()) { BigInteger totalSupply = contract.totalSupply().send().getValue().pide(new BigInteger("1000000000000000000")); System.out.println("UFOtoken 总供应量:"+totalSupply); System.out.println(address+" UFOToken 余额:"+contract.balanceOf(new Address(address)).sendAsync().get().getValue().pide(new BigInteger("1000000000000000000"))); System.out.println(queryAddress+" UFOToken 余额:"+contract.balanceOf(new Address(queryAddress)).sendAsync().get().getValue().pide(new BigInteger("1000000000000000000"))); } }catch (Exception e){ e.printStackTrace(); } } public String toDecimal(int decimal, BigInteger integer) { StringBuffer sbf = new StringBuffer("1"); for (int i = 0; i < decimal; i++) { sbf.append("0"); } String balance = new BigDecimal(integer).pide(new BigDecimal(sbf.toString()), 18, BigDecimal.ROUND_DOWN).toPlainString(); return balance; } /** * 转账 **/ public static void transferUFOTokenContract(String toAddress,String toValue){ //keystore 全路径 Credentials credentials = null; Admin admin = null; try{ Web3Service web3Service = new HttpService(blockChainUrl, new OkHttpClient.Builder().build(), true); admin = Admin.build(web3Service); credentials = WalletUtils.loadCredentials(fromPassword, keyStoreAbsolutePath); RawTransactionManager transactionManager=new RawTransactionManager(admin, credentials, ChainId.MAINNET); // 转账生意业务 UFOToken contract = UFOToken.load(address, admin, transactionManager, GAS_PRICE, GAS_LIMIT); TransactionReceipt receipt = contract.transfer(new Address(toAddress), new Uint256(new BigInteger(toValue))).send(); System.out.println(" 生意业务 Hash::::::"+receipt.getTransactionHash()); }catch (Exception e){ e.printStackTrace(); } } }

这里提供了一份刊行 ERC20 尺度 token 的合约代码。见文章末端附件(1)

install npm and node.js (see https://docs.npmjs.com/getting-started/installing-node), then do:

// 指定利用 solidity 开拓语言版本 pragma solidity ^0.4.19;/*@title SafeMath * @dev Math operations with safety checks that throw on error /library SafeMath { // 根基的算术要领库 // function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } // 除 function p(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when piding by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // 减 function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } // 加 function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }}/@title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */contract ERC20Basic { // 总供应量,也就是发币总量 uint256 public totalSupply; // 查询指定地点余额 function balanceOf(address who) public view returns (uint256); // 推荐的转账要领可以安详写入 function transfer(address to, uint256 value) public returns (bool); // 记录日志 //address indexed fromaddress indexed to, uint256 value: event Transfer(address indexed from, address indexed to, uint256 value);}/@title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */contract ERC20 is ERC20Basic { //,_owner_spender 查询可以或许从地点_owner 提出的代币数量 function allowance(address owner, address spender) public view returns (uint256); // A-B 从地点_from 转移代币到地点_to,必需触发 Transfer 事件 function transferFrom(address from, address to, uint256 value) public returns (bool); //_spender_value 乐成挪用 approve 时触发 function approve(address spender, uint256 value) public returns (bool); // 触发事件记录日志 event Approval(address indexed owner, address indexed spender, uint256 value);}/@title Basic token * @dev Basic version of StandardToken, with no allowances. */contract BasicToken is ERC20Basic { //SafeMathLibrary, using SafeMath for uint256; // mapping(address => uint256) balances; //_valuetoken_to /* @dev transfer token for a specified address * @param_to The address to transfer to. * @param_value The amount to be transferred. / function transfer(address_to, uint256_value) public returns (bool) { //require //address(0) 必需是有效地点 require(_to != address(0)); //balances: //msg.sender // 发送者余额不为 0 require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. // 发送者余额扣减 balances[msg.sender] = balances[msg.sender].sub(_value); // 接管者余额增加 balances[_to] = balances[_to].add(_value); // 举办生意业务 Transfer(msg.sender,_to,_value); return true; } //// balanceOffunctionbalanceOf(address_owner)constantreturns(uint256 balance) /** @dev Gets the balance of the specified address. * @param_owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. / function balanceOf(address_owner) public view returns (uint256 balance) { return balances[_owner]; }}/@title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /* @dev Transfer tokens from one address to another * @param_from address The address which you want to send tokens from * @param_to address The address which you want to transfer to * @param_value uint256 the amount of tokens to be transferred */ function transferFrom(address_from, address_to, uint256_value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from,_to,_value); return true; } /* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * * @param_spender The address which will spend the funds. * @param_value The amount of tokens to be spent. */ function approve(address_spender, uint256_value) public returns (bool) { allowed[msg.sender][_spender] =_value; Approval(msg.sender,_spender,_value); return true; } /* @dev Function to check the amount of tokens that an owner allowed to a spender. * @param_owner address The address which owns the funds. * @param_spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address_owner, address_spender) public view returns (uint256) { return allowed[_owner][_spender]; }}/// @title UFO Protocol Token./// For more information about this token, please visit UFOToken is StandardToken { string public name; string public symbol; uint public decimals; / CONSTRUCTOR * * @dev Initialize the UFO Token / function UFOToken() public { totalSupply = 10 * 10*26; balances[msg.sender] = totalSupply; name = "UFOToken"; symbol = "UFO"; decimals = 18; }}
[/code]

[code]

支持智能合约开拓 IDE,可以在欣赏器中快速陈设测试智能合约,支持 Solidity 语言。会见和利用地点: 可能 。

源码工程下载后需要转为 maven 范例工程,留意在 pom.xml 文件中,引入了 JAVA SDK 的包。这里提醒下,请利用最新的 2.0.3 版本,修复了一些生成 Java 代码的缺陷。

private static BigInteger GAS_LIMIT = new BigInteger("100000000"); public static void main(String[] args) { // 指定生成智能合约 java 映射类的 package 路径 String packageName = "io.hpb.web3.test"; // 指定生成智能合约 java 映射类源码的当地存放地点 String outDirPath = "//erc20//UFO//java"; // 指定智能合约源码的当地地点,这两个文件也放在本类的 package 下面,读者可以自行处理惩罚 String binFilePath = "//erc20//UFO//bin//UFOToken.bin"; String abiFilePath = "//erc20//UFO//bin//UFOToken.abi";

[/code]

HPB 芯链首创人,巴比特专栏作家。十余年金融大数据、区块链技能开拓履历,曾参加建设银联大数据。主创区块链解说视频节目《明说》30 多期,编写了《以太坊官网文档中文版》,并作为主要作者编写了《区块链开拓指南》,在中国区块链社区以 ID“蓝莲花”知名。

Solidity 是一种开源的智能合约高级语言,可以运行支持开源的 Ethereum 虚拟机(EVM)之上。详细的语言先容和进修入门,在以下的网址中有具体先容: https://solidity.readthedocs.io/en/v0.5.2/。

详情请前往 HPB 官网的接入详情界面,会指导你如何通过 RPC,SDK 等方法和主链交互。 https://www.hpb.io/client。

*Documentation

Then open your text editor and start developing. The browser will automatically refresh when files are saved.

*

Troubleshooting building Some things to consider if you have trouble building the package:

[code]

请查察 Java 最佳实践这篇文章

package io.hpb.web3.test;

1.2.3 HPB 主链接入指导

下载地点:https://github.com/ethereum/remix-ide

宣布合约到 HPB 主链,有两种方法,一种是通过 HPB 官方提供 JAVA SDK 来宣布;一种是通过安装节点后通过呼吁行来宣布。

[/code]

npm run serve # starts web server at localhost:8080

[/code]

*

*安装步调

[code]
import java.math.BigDecimal;import java.math.BigInteger;import java.util.Arrays;
[/code]

演示工程代码下载地点: https://github.com/loglos/web3-hpb-test.git

[code]

[code]
io.hpb.web3groupId>web3-hpbartifactId>2.0.3version>dependency>
[/code]

*Unit Testing Register new unit test files in test/index.js. The tests are written using tape.

Run npm start and open :8080 in your browser.

[/code]

2.2.3.1 筹备情况

node --versionnpm --versionnvm --version

Remix-ide has been published as an npm module:

To run the Selenium tests via Nightwatch serve the app through a local web server:

In Debian based OS such as Ubuntu 14.04LTS you may need to run apt-get install build-essential. After installing build-essential run npm rebuild.

[code]

通过 JAVA SDK 宣布智能合约教程,请见 HPB 主网最佳实践之 JAVA 版本。

git clone https://github.com/ethereum/remix-ide.gitgit clone https://github.com/ethereum/remix.git # only if you plan to link remix and remix-ide repositories and develop on it.cd remix-idenpm installnpm run setupremix # only if you plan to link remix and remix-ide repositories and develop on it.npm start

To see details about how to use Remix for developing and/or debugging Solidity contracts, please see our documentation page https://remix.readthedocs.io/en/latest/

Make sure that you have the correct version of node, npm and nvm. You can find the version that is tested on Travis CI by looking at the log in the build results. Run:

[/code]

import io.hpb.web3.codegen.SolidityFunctionWrapperGenerator;import io.hpb.web3.crypto.Credentials;import io.hpb.web3.crypto.WalletUtils;import io.hpb.web3.protocol.Web3;import io.hpb.web3.protocol.Web3Service;import io.hpb.web3.protocol.admin.Admin;import io.hpb.web3.protocol.core.DefaultBlockParameterName;import io.hpb.web3.protocol.core.methods.response.TransactionReceipt;import io.hpb.web3.protocol.http.HttpService;import io.hpb.web3.tx.ChainId;import io.hpb.web3.tx.RawTransactionManager;import io.hpb.web3.utils.Convert;import okhttp3.OkHttpClient;import io.hpb.web3.abi.datatypes.Address;import io.hpb.web3.abi.datatypes.generated.Uint256;

Or if you want to clone the github repository (wget need to be installed first) :

UFOToken.sol:本次演示的 ERC20 的智能合约源码。

Run the unit tests via: npm test

粘贴代码到编辑器中,,选择编译器编译版本为合约代码中指定的版本。

Then you will need to either:

[/code]

*DEVELOPING:

本文首发于汪晓明博客

点击查察详情。

请会见链接举办智能合约开拓 详细智能合约的开拓请见第 3 章节。

Run: sc -u-k(see .travis.yml for values)Run: npm run browser-test-sc

UFOToken.bin:智能合约编译后的 bin 文件。

For local headless browser tests run npm run test-browser (requires Selenium to be installed - can be done with npm run selenium-install)

https://github.com/loglos/web3-hpb-test.git

[code]

Most of the the time working with other modules (like debugger etc.) hosted in the Remix repository is not needed.

HPB 芯链官网

1.2.4 智能合约 Demo 地点

UFOTokenRun.java:Java 生成智能合约工具类的执行类。

If you would like to use this as a Chrome extension, you must either build it first or pull from the gh-pages branch, both described above. After that, follow these steps:

[/code]

2.1.1 通过在线 Remix 在线编译器举办智能合约开拓

1.Have a Selenium server running locally on port 4444.

开拓者可以直接执行 UFOTokenRun.java 内里的 main 要领,来举办调试。个中相关的地点的路径,请按照自身的开拓情况的实际挪用地点和 HPB 账号信息填写。

2 、开拓智能合约

2.1 情况筹备

package io.hpb.web3.test;
public class UFOTokenRun {

打开 solidity 智能合约在线编译器可能当地编辑器:

Running unit tests via npm test requires at least node v7.0.0

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

说点什么吧
  • 全部评论(0
    还没有评论,快来抢沙发吧!

相关文章阅读