How to interact with Smart contract using JAVA

Cau Ta
Coinmonks
4 min readOct 25, 2018

--

This article focus on how to interact with smart contract, call function, deploy new smart contract to ethereum network through Web3j

Kết quả hình ảnh cho ethereum smart contract java
https://web3j.readthedocs.io/en/latest/index.html

WEB3J

this SDK is a strong framework to develop software connect with ethereum blockchain network

Prepare an ethereum fullnode to connect with ethereum blockchain network or you can use Infura instead of build your own node.

Add Web3j dependency into pom file:

This is an example initiate web3j client interact with network:

Interact with Smart Contract

  1. Prepare:
  • Prepare Contract. for example i will use ERC20.sol to interact with erc20 token smart contract. It can be found here
  • Download solidity compiler, extract and add export environment variable. The compiler is used to compile from ERC20.sol to binary format.
  • Download, extract and add environment variable for web3j script. This script can generate java class from solidity binary. It includes both version script for linux and windows.

2. Translate Solidity contract into Java class:

First, we need to compile a solidity code to binary and abi format.

  • use solc in solidity compiler package to compile contract first:
compile contract into folder ../compiled
After compile

after compile we will have 2 files: ERC20.abi and ERC20.bin

  • use web3j.bat (windows) to import the compiled contract into your project. General command:
generate java class from compiled contract
this is java contract class

Deploy and Call function in contract:

*Note: Erc20 i used here is interface, so the deploy step is the example and it doesn’t work. Try your own contract to see the difference.

Conclusion

The example above is a simple demo to interact with ethereum smart contract by Java. Hope this help.

There are a lot of features in Web3j support us to connect with ethereum blockchain network. You can find here: https://web3j.readthedocs.io/en/latest/index.html

Leave your comment below :).

Thanks for your claps! :)

Join Coinmonks Telegram Channel and Youtube Channel get daily Crypto News

Also, Read

--

--

Cau Ta
Coinmonks

Blockchain expert, Cryptos Researcher, Software Engineering. Founder Crypitor Service.