How to interact with Smart contract using JAVA
This article focus on how to interact with smart contract, call function, deploy new smart contract to ethereum network through Web3j
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:
<!-- https://mvnrepository.com/artifact/org.web3j/core -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/parity -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>parity</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/parity -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>crypto</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/parity -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>abi</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/parity -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>codegen</artifactId>
<version>3.5.0</version>
</dependency>
This is an example initiate web3j client interact with network:
package org.blockchain.services.ethereum;
import org.blockchain.config.AppContext;
import org.web3j.crypto.WalletFile;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jService;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.parity.Parity;
import org.web3j.protocol.parity.methods.response.ParityExportAccount;
import org.web3j.protocol.parity.methods.response.ParityTracesResponse;
import org.web3j.protocol.parity.methods.response.Trace;
import java.util.List;
public class Web3JClient {
private static Web3jService service = new HttpService("http://localhost:8545"); // put fullnode url here
private static Web3j web3j = Web3j.build(service);
private static Parity parity = Parity.build(service);
public static List<Trace> getCallActionsInBlock(long blockNum) throws Exception {
DefaultBlockParameterNumber number = new DefaultBlockParameterNumber(blockNum);
Request<?, ParityTracesResponse> request = parity.traceBlock(number);
ParityTracesResponse response = request.send();
return response.getTraces();
}
public static List<Trace> getCallAction(String hash) throws Exception {
Request<?, ParityTracesResponse> request = parity.traceTransaction(hash);
ParityTracesResponse response = request.send();
return response.getTraces();
}
public static WalletFile exportAccount(String address, String password) throws Exception {
Request<?, ParityExportAccount> request = parity.parityExportAccount(address, password);
ParityExportAccount response = request.send();
return response.getWallet();
}
public static void main(String[] args) throws Exception {
// test function here }
}
Interact with Smart Contract
- 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:
solc <contract>.sol --bin --abi --optimize -o <output-dir>/
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:
web3j solidity generate [--javaTypes|--solidityTypes] /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
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.
package org.blockchain.services.ethereum;
import org.blockchain.model.ethereum.ERC20;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.WalletFile;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jService;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.parity.Parity;
import org.web3j.protocol.parity.methods.response.ParityExportAccount;
import org.web3j.protocol.parity.methods.response.ParityTracesResponse;
import org.web3j.protocol.parity.methods.response.Trace;
import org.web3j.tx.FastRawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.tx.response.NoOpProcessor;
import java.math.BigInteger;
import java.util.List;
public class Web3JClient { private static Web3jService service = new HttpService("http://localhost:8545");
private static Web3j web3j = Web3j.build(service);
private static Parity parity = Parity.build(service); public static void main(String[] args) throws Exception {
/**
* TEST DEPLOY AND CALL CONTRACT FUNCTION
*/
// load private key into eckey to sign
String privatekey = "***********************************";
BigInteger privkey = new BigInteger(privatekey, 16);
ECKeyPair ecKeyPair = ECKeyPair.create(privkey);
Credentials credentials = Credentials.create(ecKeyPair);
NoOpProcessor processor = new NoOpProcessor(web3j);
//deploy new contract
TransactionManager txManager = new FastRawTransactionManager(web3j, credentials, processor);
RemoteCall<ERC20> request = ERC20.deploy(web3j, txManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT);
ERC20 token = request.send();
String contractAddress = token.getDeployedAddress("3"); // 3 is ropsten testnet
// load existing contract by address
// ERC20 token = ERC20.load(contractAddress, web3j, txManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT);
// create transaction transfer token to receiver
String receiver = "0xa107483c8a16a58871182a48d4ba1fbbb6a*****";
BigInteger value = new BigInteger("10000000000000");
TransactionReceipt receipt = token.transfer(receiver, value).send();
// get transaction result
System.out.println(receipt.getTransactionHash());
}
}
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
- Copy Trading | Crypto Tax Software
- Grid Trading | Crypto Hardware Wallet
- Crypto Telegram Signals | Crypto Trading Bot
- Best Crypto Exchange | Best Crypto Exchange in India
- Best Crypto APIs for Developers
- Best Crypto Lending Platform
- Free Crypto Signals | Crypto Trading Bots
- An ultimate guide to Leveraged Token