How to execute a contract using web3j

Article content

It is a method to execute the contract created by solidity using web3j. Learn how to convert sol files to Java classes. The contracts used in this article use the contents described in the following articles.

How to convert solidity contract to Java contract class

code

sample.java


try {
  SampleGasProvider gasProvider = new SampleGasProvider(BigInteger.valueOf(500), BigInteger.valueOf(200000));

  Addition contract = Addition.deploy(
      web3j,
      credentials,
      gasProvider
      ).send();
  //Output the address of the contract
  System.out.println("contract address: " + contract.getContractAddress());
  //Method call (no transaction)
  System.out.println("get: " + contract.get().send());
  System.out.println("add: " + contract.add(BigInteger.valueOf(10)).sendAsync());
  System.out.println("get: " + contract.get().send());

} catch (Exception e) {
  e.printStackTrace();
}

SampleGasProvider.java


package jp.ethereum;

import java.math.BigInteger;
import org.web3j.tx.gas.ContractGasProvider;

public class SampleGasProvider implements ContractGasProvider{

  private BigInteger gasPrice;
  private BigInteger gasLimit;

  public SampleGasProvider(BigInteger gasPrice, BigInteger gasLimit) {
    this.gasPrice = gasPrice;
    this.gasLimit = gasLimit;
  }
  @Override
  public BigInteger getGasPrice(String contractFunc) {
    return this.gasPrice;
  }
  @Override
  public BigInteger getGasPrice() {
    return this.gasPrice;
  }
  @Override
  public BigInteger getGasLimit(String contractFunc) {
    return this.gasLimit;
  }
  @Override
  public BigInteger getGasLimit() {
    return this.gasLimit;
  }
}

The content of the code is simple. First, deploy the contract. When this process is complete, a transaction for deploying the contract is created, populated into the block, and then completed.

Sample.java


  Addition contract = Addition.deploy(
      web3j,
      credentials,
      gasProvider
      ).send();

Execution result (geth console)

INFO [09-16|17:19:41.983] Submitted contract creation              fullhash=0xd169416410c2e6e7bdc02a2a27384ed2425e1433f39117a3810675fcfed85353 contract=0xf5ad7542173e8944D1aE16B4394eAA34cfdA4814

Then execute the contract.

Sample.java


  System.out.println("get: " + contract.get().send());
  System.out.println("add: " + contract.add(BigInteger.valueOf(10)).sendAsync());

In this example, the get process of the contract is called first. Since get only refers to the value, no transaction is created and a response is returned immediately.

Since the next add process is the process of updating the value, a transaction is created. Since we are using "send Async", we get a response before it is populated into the block. In this example, the output will be as follows.

add: java.util.concurrent.CompletableFuture@18271936[Not completed]

If you need to wait for processing to be captured in the block, make the following changes:

Sample.java


  System.out.println("add: " + contract.add(BigInteger.valueOf(10)).send());

Load contract

The code above was to deploy and execute the contract, but there is also a way to execute the already deployed contract.

Sample.java


Addition contract = Addition.load(
  address,
  web3j,
  credentials,
  gasProvider
);

The deployment and arguments are almost the same, but the first argument is the address of the contract. (Including 0x) Subsequent operations will not change at all.

Recommended Posts

How to execute a contract using web3j
[Ethereum] How to execute a contract using web3j-Part 2-
How to sort a List using Comparator
How to execute and mock methods using JUnit
[Rails] How to create a graph using lazy_high_charts
How to delete a controller etc. using a command
How to convert a solidity contract to a Java contract class
How to generate a primary key using @GeneratedValue
How to leave a comment
How to delete custom Adapter elements using a custom model
[Java] How to execute tasks on a regular basis
How to convert A to a and a to A using AND and OR in Java
How to insert a video
How to create a method
[Rails] How to install a decorator using gem draper
How to authorize using graphql-ruby
How to output array values without using a for statement
How to join a table without using DBFlute and sql
How to register as a customer with Square using Tomcat
How to add columns to a table
How to make a Java container
How to sign a Minecraft MOD
How to make a JDBC driver
[Java] How to create a folder
How to write a ternary operator
[Swift] How to send a notification
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
How to make a Java array
How to execute Ruby irb (interactive ruby)
How to build CloudStack using Docker
How to create a jar file or war file using the jar command
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
How to run a mock server on Swagger-ui using stoplight/prism (using AWS/EC2/Docker)
[Rails 6] How to create a dynamic form input screen using cocoon
How to make a groundbreaking diamond using Java for statement wwww
[Xcode] How to add a README.md file
How to make a Java calendar Summary
A memorandum on how to use Eclipse
How to redo a deployment on Heroku
[Rails] How to upload images using Carrierwave
[Basic] How to write a Dockerfile Self-learning ②
How to insert a video in Rails
[Java] How to calculate age using LocalDate
How to add a new hash / array
[Introduction to Java] How to write a Java program
How to create a Maven repository for 2020
How to make a Discord bot (Java)
How to print a Java Word document
[Swift5] How to create a splash screen
[rails] How to create a partial template
[Swift5] How to implement animation using "lottie-ios"
How to implement image posting using rails
How to make asynchronous pagenations using Kaminari
How to publish a library in jCenter
[SpringBoot] How to write a controller test
[Rails] How to handle data using enum
How to execute multiple commands in docker-compose.yml
How to insert icons using Font awesome
How to return a value from Model to Controller using the [Swift5] protocol