Skip to content

Best Practice of HPB Main Network Access Java Version

Nicemanss edited this page Aug 20, 2019 · 3 revisions

1 Preparation

1.1 Learning threshold

  • Familiar with the basic syntax and use of Java
  • Familiar with the basic use of Java IDE tools (Eclipse, IDEA)
  • Familiar with the basic syntax and use of Git version management
  • Familiar with the SpingBoot development (this demo is provided based on Springboot source code)
  • Familiar with the basic principles of blockchain
  • As for how to access HPB main network, please visit https://www.hpb.io/developer

1.2 Environment preparation

  • JDK1.8 or above versions
  • Eclipse4.7 or above version
  • Eclipse is equipped with Git plugin
  • Eclipse is equipped with Spring plugin
  • JAVA SDK for HPB main network can be downloaded here: https://www.hpb.io/developer
  • Since it is a maven project, it downloads jars necessary for the project from network, so the machine needs to have internet connection.

1.3 Source code address

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

2 Start practicing

2.1 Demo code via Eclipse Import

  • Open Eclipse, click on the menu bar to open: File/Import/Git/Projects form Git/
  • Select import via Clone URI and enter the source code of Github address in the import interface;
  • Next, select master main branch
  • Next, specify the path to download the code.
  • Next, choose Import as general project
  • Then, specify the project name, the default name is Github source project name which can do without modifying and click finish.

2.2 Change the properties of the code project

  • Since codes uploaded to Github do not include code engineering configuration information, simple adjustment is required.
  • Source project is based on maven type, you can right click the project code and select "configure/convert to maven projects"
  • After successful conversion, the system can recognize the project as a maven type.
  • Hint: After converting to maven project, many packages rely on jar to configure and manage via pom.xml. If there is no local maven repository installed, it will pull dependent jar packages from the remote at the first time and the speed will be low. If the project reports an error, please try a few times.

2.3 Description on source code configuration information

Open maven configuration file pom.xml

<!--
Other configurations do not need to be modified, here please notes that JAVA version SDK of HPB main network is used
-->
		<dependency>
			<groupId>io.hpb.web3</groupId>
			<artifactId>web3-hpb</artifactId>
			<version>1.0.0</version>
		</dependency>
		

Open application.properties file, and configuration file can be modified as needed. Here are a few important configuration properties to explain

#Access name published by specified project
spring.application.name=HpbWeb3Test

#Access server interface published by project
server.port=9988
server.servlet.path=/
server.use-forward-headers=true
server.servlet.context-path=/HpbWeb3Test
server.servlet.application-display-name=hpb web3 test application
web3.admin-client=true
web3.httpTimeoutSeconds=600

# Specify the RPC URL to connect with HPB main network. Here is the open RPC address of the official network of main network.
# By accessing this address, you can perform RPC commands through Java and directly interact with HPB main network.
web3.client-address=http://pub.node.hpb.io/

Open the HpbWeb3Controller.java file, here is the specific code of this demo, here is the explanation for the key code.

//Here please note it uses Java SDK package provided by HPB main network, in which methods on how to interact with the base via RPC are embedded

import io.hpb.web3.abi.datatypes.Address;
import io.hpb.web3.abi.datatypes.DynamicArray;
import io.hpb.web3.abi.datatypes.generated.Bytes32;
import io.hpb.web3.contract.HpbNodes;
import io.hpb.web3.crypto.Credentials;
import io.hpb.web3.crypto.RawTransaction;
import io.hpb.web3.crypto.WalletUtils;
import io.hpb.web3.protocol.admin.Admin;
import io.hpb.web3.protocol.core.DefaultBlockParameterName;
import io.hpb.web3.protocol.core.methods.response.HpbBlockNumber;
import io.hpb.web3.protocol.core.methods.response.HpbGetBalance;
import io.hpb.web3.protocol.core.methods.response.HpbGetTransactionCount;
import io.hpb.web3.protocol.core.methods.response.HpbGetTransactionReceipt;
import io.hpb.web3.protocol.core.methods.response.HpbSendTransaction;
import io.hpb.web3.protocol.core.methods.response.TransactionReceipt;
import io.hpb.web3.tuples.generated.Tuple4;
import io.hpb.web3.tx.ChainId;
import io.hpb.web3.tx.RawTransactionManager;
import io.hpb.web3.utils.Convert;
import io.hpb.web3.utils.Numeric;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/")
public class HpbWeb3Controller{
    
    //output log
	private static Log log = LogFactory.getLog(HpbWeb3Controller.class);
	//overdue time
	private final long WEB3J_TIMEOUT = 3;
	
	//demon HPB account address
	private final String contractAddr = "0x7be6aa25600feed355b79b6a4e14dcdb0bd529cb";
	
	//set account balance unit as 18GWEI
	private final BigInteger gasPrice = Convert.toWei("18", Convert.Unit.GWEI).toBigInteger();

	//set default GasLimit
	private final BigInteger gasLimit = new BigInteger("95000000");
	
	
	@Autowired
	private Admin admin;
	@ApiOperation(value="check transaction receipt via transaction hash",notes = "check transaction receipt via transaction hash"
			+ " reqStrList [  parameter 1: transaction hash]")
	@PostMapping("/QueryByHash")
	public List<Object> QueryByHash(@RequestBody List<String> reqStrList)throws Exception{
		List<Object> list=new ArrayList<Object>();
		if(reqStrList!=null&&reqStrList.size()>0) {
			String transactionHash = reqStrList.get(0);
			
			//Method intially embedded in Java SDK package; get the transaction date of designated account by initializing HpbGetTransactionReceipt
			HpbGetTransactionReceipt receipt = admin.hpbGetTransactionReceipt(transactionHash).send();
			if(!receipt.hasError()) {
				TransactionReceipt transactionReceipt = receipt.getResult();
				if(transactionReceipt.isStatusOK()) {
					list.add(transactionReceipt);
				}
			}
		}
		return list;
	}
	
	
	@ApiOperation(value="get current block number",notes = "get current block number")
	@PostMapping("/getCurrentBlock")
	public List<Object> getCurrentBlock()throws Exception{
		List<Object> list=new ArrayList<Object>();
		
		//Method initially embedded in Java SDK package;get the object of current block via HpbBlockNumber
		HpbBlockNumber blockNumber = admin.hpbBlockNumber().sendAsync().get(WEB3J_TIMEOUT, TimeUnit.MINUTES);
		list.add(blockNumber);
		return list;
	}
	@ApiOperation(value="get Nonce of current account",notes = "get Nonce of current account"
			+ " reqStrList [ parameter 1: account address;")
	@PostMapping("/getCurrentNonce")
	public List<Object> getCurrentNonce(@RequestBody List<String> reqStrList)throws Exception{
		List<Object> list=new ArrayList<Object>();
		if(reqStrList!=null&&reqStrList.size()>0) {
			String address =reqStrList.get(0);
			
			//Method initially embedded in Java SDK package;get Nonce of current block via HpbGetTransactionCount
			//Nonce is a random number in the account to prevent multiple transaction in an account
			HpbGetTransactionCount transactionCount = admin.hpbGetTransactionCount(address, 
					DefaultBlockParameterName.PENDING).sendAsync().get(WEB3J_TIMEOUT, TimeUnit.MINUTES);
			BigInteger nonce = transactionCount.getTransactionCount();
			log.info(nonce);
			list.add(nonce);
		}
		return list;
	}
	
	
	@ApiOperation(value="get the balance of current account",notes = "get the balance of current account"
			+ " reqStrList [ parameter 1: account address]")
	@PostMapping("/getBalance")
	public List<Object> getBalance(@RequestBody List<String> reqStrList)throws Exception{
		List<Object> list=new ArrayList<Object>();
		if(reqStrList!=null&&reqStrList.size()>0) {
			String address =reqStrList.get(0);
			
			//Method initially embedded in Java SDK package; get the balance of current account via HpbGetBalance
			HpbGetBalance balance = admin.hpbGetBalance(address, DefaultBlockParameterName.LATEST).send();
			log.info(balance);
			list.add(balance);
		}
		return list;
	}
	
	
	@ApiOperation(value="send transaction",notes = "send transaction"
			+ " reqStrList [ parameter 1: account keystore address; parameter 2:password; parameter 3: receving account address;parameter 4: transfer amount;]")
	@PostMapping("/sendTransaction")
	public List<Object> sendTransaction(@RequestBody List<String> reqStrList)throws Exception{
		List<Object> list=new ArrayList<Object>();
		if(reqStrList!=null&&reqStrList.size()>3) {
		    //keystore get the keystore of designated account
			String keystore =reqStrList.get(0);
			
			//get the password and account the user input for transaction
			String password =reqStrList.get(1);
			
			//loan private key object
			Credentials credentials = WalletUtils.loadCredentials(password, keystore);
			
			//launch transaction management object
			RawTransactionManager transactionManager=new RawTransactionManager(admin, credentials, ChainId.MAINNET);
			
			//get nonce
			HpbGetTransactionCount transactionCount = admin.hpbGetTransactionCount(credentials.getAddress(), 
					DefaultBlockParameterName.PENDING).sendAsync().get(WEB3J_TIMEOUT, TimeUnit.MINUTES);
			
			BigInteger nonce = transactionCount.getTransactionCount();
			
			//get target address
			String to =reqStrList.get(2);
			
			//transfer amount
			String value =reqStrList.get(3);
			
			//launch transaction object
			RawTransaction rawTransaction = RawTransaction.createTransaction(
					nonce,
					gasPrice,
					gasLimit,
					to,
					Convert.toWei(value, Convert.Unit.HPB).toBigInteger(),
					"");
				
		    //signature and send transaction
			HpbSendTransaction transaction = transactionManager.signAndSend(rawTransaction);
			log.info(transaction.getTransactionHash());
			list.add(transaction);
		}
		return list;
	}
	
	
	
	@ApiOperation(value="call HpbNodes smart contract",notes = "call HpbNodes smart contract"
			+ " reqStrList [ parameter 1: account keystore address; parameter 2:password]")
	@PostMapping("/invokeHpbNodes")
	public List<Object> invokeHpbNodes(@RequestBody List<String> reqStrList)throws Exception{
		List<Object> list=new ArrayList<Object>();
		if(reqStrList!=null&&reqStrList.size()>1) {
			String keystore =reqStrList.get(0);
			String password =reqStrList.get(1);
			Credentials credentials = WalletUtils.loadCredentials(password, keystore);
			RawTransactionManager transactionManager=new RawTransactionManager(admin, credentials, ChainId.MAINNET);
			HpbNodes hpbNodes = HpbNodes.load(contractAddr, admin, transactionManager, gasPrice, gasLimit);
			//call smart contract
			Tuple4<DynamicArray<Address>, DynamicArray<Bytes32>, DynamicArray<Bytes32>, DynamicArray<Bytes32>> send = 
					hpbNodes.getAllHpbNodes().send();
			Bytes32 bytes32 = send.getValue2().getValue().get(1);
			log.info(Numeric.toHexStringNoPrefix(bytes32.getValue()));
			Bytes32 bytes321 = send.getValue3().getValue().get(1);
			log.info(Numeric.toHexStringNoPrefix(bytes321.getValue()));
			Bytes32 bytes322 = send.getValue3().getValue().get(1);
			log.info(Numeric.toHexStringNoPrefix(bytes322.getValue()));
			list.add(send);
		}
		return list;
	}
	
}

2.4 Running programs and debugging

1.Publishing

Find and select the Web3HpbTestApplication category and right click "Run as /Spring Boot App" After successful startup, the system displays similar prompts as follows:

2019-01-09 10:49:18.538 HpbWeb3Test [main] INFO  io.hpb.web3.Web3HpbTestApplication Caller+0	 at org.springframework.boot.StartupInfoLogger.logStarting(StartupInfoLogger.java:50)
 - Starting Web3HpbTestApplication on jason-hpbdeMBP with PID 46179 (/Users/hpb2017/git/web3-hpb-test/target/classes started by hpb2017 in /Users/hpb2017/git/web3-hpb-test)
2019-01-09 10:49:18.540 HpbWeb3Test [main] DEBUG io.hpb.web3.Web3HpbTestApplication Caller+0	 at org.springframework.boot.StartupInfoLogger.logStarting(StartupInfoLogger.java:53)
 - Running with Spring Boot v2.1.1.RELEASE, Spring v5.1.3.RELEASE
2019-01-09 10:49:18.542 HpbWeb3Test [main] INFO  io.hpb.web3.Web3HpbTestApplication Caller+0	 at org.springframework.boot.SpringApplication.logStartupProfileInfo(SpringApplication.java:675)
 - No active profile set, falling back to default profiles: default
2019-01-09 10:49:20.818 HpbWeb3Test [main] INFO  i.h.w.c.Web3AutoConfiguration Caller+0	 at io.hpb.web3.configure.Web3AutoConfiguration.admin(Web3AutoConfiguration.java:51)
 - Building admin service for endpoint: http://pub.node.hpb.io/
2019-01-09 10:49:21.406 HpbWeb3Test [main] INFO  i.h.w.c.Web3AutoConfiguration Caller+0	 at io.hpb.web3.configure.Web3AutoConfiguration.Web3(Web3AutoConfiguration.java:42)
 - Building service for endpoint: http://pub.node.hpb.io/
2019-01-09 10:49:22.057 HpbWeb3Test [main] INFO  io.hpb.web3.Web3HpbTestApplication Caller+0	 at org.springframework.boot.StartupInfoLogger.logStarted(StartupInfoLogger.java:59)
 - Started Web3HpbTestApplication in 3.943 seconds (JVM running for 5.429)
 

2.Test Verification Interface

Springboot's interface can be accessed and tested via its own swagger plugin. Open the local access address: http://localhost:9988/HpbWeb3Test/swagger-ui.html#/ It will display open test interface in the current system, and then click “hpb-web-3-controller” to access the specific method test interface. Click the "/getBalance" method, and click "Try it out" to get into the edit mode. Enter the HPB address you want to check the balance; then click "Execute" to start. The system will display execution results, please note that the balance here is presented in scientific notation. Other interfaces can be tested in turn based on interface contents.

Clone this wiki locally