How to convert a solidity contract to a Java contract class

Article content

If you want to use the contract used in solidity with web3j, you need to use Java classes to operate the contract.

Of course, it is possible to create a class that operates this contract from scratch, but I will leave a note because there was an easy way to create it.

environment

Download Web3j

A tool to convert sol files to java files is provided on the command line, so download it.

web3j

  1. There is a zip file at the link destination, so download it.
  2. Unzip the zip file and place it in any directory.
  3. Pass the path to the bin directory of the placed directory.
  4. At the command prompt, type web3j.

The setting is complete when the following display appears.


              _      _____ _     _
             | |    |____ (_)   (_)
__      _____| |__      / /_     _   ___
\ \ /\ / / _ \ '_ \     \ \ |   | | / _ \
 \ V  V /  __/ |_) |.___/ / | _ | || (_) |
  \_/\_/ \___|_.__/ \____/| |(_)|_| \___/
                         _/ |
                        |__/
Usage: web3j version|wallet|solidity ...

Create bin and abi files

First, prepare the sol file.

addition.sol


pragma solidity ^0.4.24;

contract Addition{
  int num = 0;
  function add(int a) public {
    num += a;
  }
  function get() public view returns(int)  {
    return num;
  }
}

Compile this sol file and extract the bin and abi.

solc --bin addition.sol > addition.bin
solc --abi addition.sol > addition.abi

The output files are as follows.

addition.bin


======= addition.sol:Addition =======
Binary: 
60806040526000805534801561001457600080fd5b5060e7806100236000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680636d4ce63c14604e57806387db03b7146076575b600080fd5b348015605957600080fd5b50606060a0565b6040518082815260200191505060405180910390f35b348015608157600080fd5b50609e6004803603810190808035906020019092919050505060a9565b005b60008054905090565b806000808282540192505081905550505600a165627a7a723058200522274b97a5967f28327168f4654fbd3921238ed6de8e155c966f7dad168e020029

addition.abi


======= addition.sol:Addition =======
Contract JSON ABI 
[{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"a","type":"int256"}],"name":"add","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]

For these two files, delete the first few lines (up to ~ Binary: / ~ JSON ABI) as they will be unnecessary for future processing.

Create a contract class

Create with the following command

web3j solidity generate -a=addition.abi -b=addition.bin -o=src -p=jp.ethereum.contracts

Execution result


              _      _____ _     _
             | |    |____ (_)   (_)
__      _____| |__      / /_     _   ___
\ \ /\ / / _ \ '_ \     \ \ |   | | / _ \
 \ V  V /  __/ |_) |.___/ / | _ | || (_) |
  \_/\_/ \___|_.__/ \____/| |(_)|_| \___/
                         _/ |
                        |__/

Generating jp.ethereum.contracts.Addition ... File written to src

If this result is obtained, the output is complete. It is output to the directory specified by the "-O" option. In this case, the "jp.ethereum.contracts" package specified by "-p" is created under the src directory, and Addtion.java is created under that package.

addtion.java


package jp.ethereum.contracts;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Int256;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.RemoteFunctionCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.ContractGasProvider;

/**
 * <p>Auto generated code.
 * <p><strong>Do not modify!</strong>
 * <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
 * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the 
 * <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
 *
 * <p>Generated with web3j version 4.5.0.
 */
public class Addition extends Contract {
    private static final String BINARY = "60806040526000805534801561001457600080fd5b5060e7806100236000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680636d4ce63c14604e57806387db03b7146076575b600080fd5b348015605957600080fd5b50606060a0565b6040518082815260200191505060405180910390f35b348015608157600080fd5b50609e6004803603810190808035906020019092919050505060a9565b005b60008054905090565b806000808282540192505081905550505600a165627a7a723058200522274b97a5967f28327168f4654fbd3921238ed6de8e155c966f7dad168e020029\r\n";

    public static final String FUNC_GET = "get";

    public static final String FUNC_ADD = "add";

    @Deprecated
    protected Addition(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    protected Addition(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
        super(BINARY, contractAddress, web3j, credentials, contractGasProvider);
    }

    @Deprecated
    protected Addition(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
        super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
    }

    protected Addition(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
        super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider);
    }

    public RemoteFunctionCall<BigInteger> get() {
        final Function function = new Function(FUNC_GET, 
                Arrays.<Type>asList(), 
                Arrays.<TypeReference<?>>asList(new TypeReference<Int256>() {}));
        return executeRemoteCallSingleValueReturn(function, BigInteger.class);
    }

    public RemoteFunctionCall<TransactionReceipt> add(BigInteger a) {
        final Function function = new Function(
                FUNC_ADD, 
                Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Int256(a)), 
                Collections.<TypeReference<?>>emptyList());
        return executeRemoteCallTransaction(function);
    }

    @Deprecated
    public static Addition load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return new Addition(contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    @Deprecated
    public static Addition load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
        return new Addition(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
    }

    public static Addition load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
        return new Addition(contractAddress, web3j, credentials, contractGasProvider);
    }

    public static Addition load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
        return new Addition(contractAddress, web3j, transactionManager, contractGasProvider);
    }

    public static RemoteCall<Addition> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
        return deployRemoteCall(Addition.class, web3j, credentials, contractGasProvider, BINARY, "");
    }

    @Deprecated
    public static RemoteCall<Addition> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return deployRemoteCall(Addition.class, web3j, credentials, gasPrice, gasLimit, BINARY, "");
    }

    public static RemoteCall<Addition> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
        return deployRemoteCall(Addition.class, web3j, transactionManager, contractGasProvider, BINARY, "");
    }

    @Deprecated
    public static RemoteCall<Addition> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
        return deployRemoteCall(Addition.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "");
    }
}

This class is required when executing a contract using Web3j. There are many deprecated methods, so be careful when using them.

reference

web3j docs

Recommended Posts

How to convert a solidity contract to a Java contract class
How to use java class
How to convert Java radix
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
How to make a Java container
How to disassemble Java class files
[Java] How to create a folder
How to decompile java class files
[Java] How to use LinkedHashMap class
How to use class methods [Java]
How to make a Java array
[Java] How to use Math class
[Java] How to convert a character string from String type to byte type
How to execute a contract using web3j
[Java] How to use the File class
[Java] How to use the HashMap class
How to make a Discord bot (Java)
[Processing × Java] How to use the class
How to print a Java Word document
How to use Java Scanner class (Note)
[Java] How to use the Calendar class
[Java] How to use FileReader class and BufferedReader class
[Android] How to convert a character string to resourceId
How to display a web page in Java
[Ethereum] How to execute a contract using web3j-Part 2-
How to create a class that inherits class information
How to get Class from Element in Java
How to find out the Java version of a compiled class file
[Java] How to get to the front of a specific string using the String class
[Java] How to use Calendar class and Date class
[Java] How to convert one element of a String type array to an Int type
How to create a Java environment in just 3 seconds
How to jump from Eclipse Java to a SQL file
java: How to write a generic type list [Note]
[Java] How to play rock-paper-scissors (equivalent to paiza rank A)
How to create a data URI (base64) in Java
[Java] How to get a request by HTTP communication
[Java] How to execute tasks on a regular basis
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
[Java] How to start a new line with StringBuilder
[Java] How to use Map
How to lower java version
[Java] How to use Map
Convert Java Powerpoint to XPS
How to uninstall Java 8 (Mac)
How to use java Optional
How to minimize Java images
How to write java comments
How to leave a comment
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
How to use Java variables
[Java] Convert ArrayList to array
[Java] How to implement multithreading
[Java] How to use Optional ①