How to invoke smart contract based on Java code

  • Java is generally based on the Web3J toolkit to invoke smart contracts in Ethereum, a similar Web toolkit.
  • See also:

[hanksandy/eth-web3j-samples​

gitee.com

] (link.zhihu.com/?target=htt…).

Ii. Example project construction

1. Install NodeJS (support solc build and install) 2. Install Solc (Solc Smart Contract Build environment) 3. Install Web3j (web3j command line works for automatic Generation of Java code)

Command line tool download address: github.com/web3j/web3j… Sol –optimize –bin –abi — output-dir./ – Generate Java call classes: solcjs. / filehashContract. sol –optimize –bin –abi — output-dir. Web3j solidity generate filehashContract.bin filehashContract.abi-o./ -p com.hanko.contract www.jianshu.com/p/734995ca4…

Three, sample code description

  • This sample project implements a simple file hash storage function

    The entrance of this test class to invoke: com. Hanko. Contract. FileHashContractTest

    Connect the blockchain and obtain the geTH client version number. * @throws IOException */ @test void getVersion() throws IOException {String Version = web3j.web3ClientVersion().send().getWeb3ClientVersion(); log.info(“>>>>>version is {}”,version); Assert.assertThat(version,startsWith( “Geth/” )); }

    /** * * @throws IOException */ @Test void deploy() throws Exception { FileHashContract fileHashContract = FileHashContract.deploy(web3j,Copy the code

    credentials,contractGasProvider).send(); System.out.println(“fileHashContract.getContractAddress() = ” + fileHashContract.getContractAddress());

    * @throws IOException */ @test void sethash () throws Exception {FileHashContract fileHashContract = FileHashContract.load(Copy the code

    web3jProperties.getContractAddress(), web3j, credentials, contractGasProvider); fileHashContract.setHash(“12345678”).send(); }

    * @throws IOException */ @test void gethash () throws Exception {FileHashContract fileHashContract = FileHashContract.load(Copy the code

    web3jProperties.getContractAddress(), web3j, credentials, contractGasProvider); String hash = fileHashContract.getHash().send(); Assert.assertEquals(hash,”12345678″); log.info(“>>>>>hash is {}”,hash); }

P.s. Com. Hanko. Contract. FileHashContract is called core classes, generated directly by web3j command line tools.

// Simple file hash store pragma solidity >= 0.4.0; contract FileHashContract { string fileHash; function setHash(string memory hash) public { fileHash = hash; } function getHash() public view returns(string memory){ return fileHash; }}Copy the code

Development of the P.S. contract can be done using the idea plugin _intellij_-solidity of course compilation is available in the IDEA configuration for External Tools in the Setting. Of course, you can also choose remix-IDE and other IDES.