Git Product home page Git Product logo

web3j-maven-plugin's Introduction

web3j-maven-plugin

build status codecov License

web3j maven plugin is used to create java classes based on the solidity contract files.

Usage

The base configuration for the plugin will take the solidity files from src/main/resources and generates the java classes into the folder src/main/java.

<build>
    <plugins>
        <plugin>
            <groupId>org.web3j</groupId>
            <artifactId>web3j-maven-plugin</artifactId>
            <version>4.11.3</version>
            <configuration>
                <soliditySourceFiles/>
            </configuration>
        </plugin>
    </plugins>
</build>

to run the plugin execute the goal generate-sources

mvn web3j:generate-sources

Configuration

The are several variable to select the solidity source files, define a source destination path or change the package name.

Name Format Default value
<packageName/> valid java package name org.web3j.model
<outputDirectory><java/></outputDirectory> relative or absolute path of the generated for 'Java files value in <sourceDestination/>
<outputDirectory><bin/></outputDirectory> relative or absolute path of the generated for 'Bin' files value in <sourceDestination/>
<outputDirectory><abi/></outputDirectory> relative or absolute path of the generated for 'ABI' files value in <sourceDestination/>
<sourceDestination/> relative or absolute path of the generated files (java, bin, abi) src/main/java
<outputFormat/> generate Java Classes(java), ABI(abi) and/or BIN (bin) Files (comma separated) java
<nativeJavaType/> Creates Java Native Types (instead of Solidity Types) true
<outputJavaParentContractClassName/> Sets custom(? extends org.web3j.tx.Contract) class as a parent for java generated code org.web3j.tx.Contract
<soliditySourceFiles> Standard maven fileset <soliditySourceFiles>
<directory>src/main/resources</directory>
<includes>
<include>**/*.sol</include>
</includes>
</soliditySourceFiles>
<abiSourceFiles> Standard maven fileset <abiSourceFiles>
<directory>src/main/resources</directory>
<includes>
<include>**/*.json</include>
</includes>
</abiSourceFiles>
<contract> Filter (<include> or <exclude>) contracts based on the name. <contract>
<includes>
<include>greeter</include>
</includes>
<excludes>
<exclude>mortal</exclude>
<excludes>
</contracts>
<pathPrefixes> A list (<pathPrefixe>) of replacements of dependency replacements inside Solidity contract.

Configuration of outputDirectory has priority over sourceDestination

Getting Started

Create a standard java maven project. Add following <plugin> - configuration into the pom.xml file:

<plugin>
    <groupId>org.web3j</groupId>
    <artifactId>web3j-maven-plugin</artifactId>
    <version>4.11.1</version>
    <configuration>
        <packageName>com.zuehlke.blockchain.model</packageName>
        <sourceDestination>src/main/java/generated</sourceDestination>
        <nativeJavaType>true</nativeJavaType>
        <outputFormat>java,bin</outputFormat>
        <soliditySourceFiles>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.sol</include>
            </includes>
        </soliditySourceFiles>
        <abiSourceFiles>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.json</include>
            </includes>
        </abiSourceFiles>
        <outputDirectory>
            <java>src/java/generated</java>
            <bin>src/bin/generated</bin>
            <abi>src/abi/generated</abi>
        </outputDirectory>
        <contract>
            <includes>
                <include>greeter</include>
            </includes>
            <excludes>
                <exclude>mortal</exclude>
            </excludes>
        </contract>
        <pathPrefixes>
            <pathPrefix>dep=../dependencies</pathPrefix>
        </pathPrefixes>
    </configuration>
</plugin>

Add your solidity contract files into the folder src/main/resources. Make sure that the solidity files ends with .sol.

Start the generating process:

> mvn web3j:generate-sources

[INFO] --- web3j-maven-plugin:0.1.2:generate-sources (default-cli) @ hotel-showcase ---
[INFO] process 'HotelShowCaseProxy.sol'
[INFO] 	Built Class for contract 'HotelShowCaseProxy'
[INFO] 	Built Class for contract 'HotelShowCaseV2'
[INFO] 	Built Class for contract 'Owned'
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.681 s
[INFO] Finished at: 2017-06-13T07:07:04+02:00
[INFO] Final Memory: 14M/187M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

You find the generated java classes inside the directory src/main/java/generated/.

Next step is to interact with the smart contract. See for that deploying and interacting with smart contracts in the official web3j documentation.

For a multi module project configuration see following post from @fcorneli. In short: For pick up the generated java source files, you need the build-helper-maven-plugin configuration. Also, ${basedir} prefix is required within a multi-module project.

web3j-maven-plugin's People

Contributors

alexandrour avatar andrii-kl avatar antonydenyer avatar benwheeler avatar dependabot[bot] avatar flefevre avatar gtebrean avatar h2mch avatar hendrikebbers avatar josh-richardson avatar mohamedelshami avatar mykolamarkov avatar nicksneo avatar rach-id avatar ricardolyn avatar snazha-blkio avatar truthslie avatar xaviarias avatar xilis avatar zebraofjustice avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web3j-maven-plugin's Issues

Filters do not work with Ganache/TestRPC with leading "0x" contract addresses

This is a reference to hyperledger/web3j#405 as users of the Maven Plugin will most likely experience this problem when using Filters with Ganache/TestRPC.

Important: If you want to use Ganache/TestRPC and Filters, do not use the generated
EventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock)
since the wrong address format is used, create the Filter yourself and use
EventObservable(EthFilter filter)
instead.
Remember to adjust the address when using Ganache/Geth, otherwise it won't work.

doesn't support "pure" and similar newer reserved words

solc compiles this fine, but the plugin errors out.

Solidity:

pragma solidity ^0.4.2;

library ConvertLib{
	function convert(uint amount,uint conversionRate) pure public returns (uint convertedAmount)
	{
		return amount * conversionRate;
	}
}

[ERROR] Failed to execute goal org.web3j:web3j-maven-plugin:0.1.2:generate-sources (default-cli) on project cannabium-ico: Could not compile solidity files
[ERROR] <stdin>:4:52: Error: Expected token LBrace got reserved keyword 'Pure'
[ERROR] function convert(uint amount,uint conversionRate) pure public returns (uint convertedAmount)

why generate java class failure

image
i generate contract class by abi file.
but some generate success.some generate failure.

[
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "token0",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "token1",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "address",
        "name": "pair",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "name": "PairCreated",
    "type": "event"
  },
  {
    "constant": true,
    "inputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "name": "allPairs",
    "outputs": [
      {
        "internalType": "address",
        "name": "pair",
        "type": "address"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "allPairsLength",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": false,
    "inputs": [
      {
        "internalType": "address",
        "name": "tokenA",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "tokenB",
        "type": "address"
      }
    ],
    "name": "createPair",
    "outputs": [
      {
        "internalType": "address",
        "name": "pair",
        "type": "address"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "feeTo",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "feeToSetter",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [
      {
        "internalType": "address",
        "name": "tokenA",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "tokenB",
        "type": "address"
      }
    ],
    "name": "getPair",
    "outputs": [
      {
        "internalType": "address",
        "name": "pair",
        "type": "address"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": false,
    "inputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "name": "setFeeTo",
    "outputs": [],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "constant": false,
    "inputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "name": "setFeeToSetter",
    "outputs": [],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  }
]

Error on mvn call

I am using maven with gradle this way:

repositories {
    mavenCentral()
    maven { url 'https://dl.bintray.com/ethereum/maven/' }
}

dependencies {
    ...
    compile 'org.web3j:core:3.2.0'
    compile 'org.web3j:web3j-maven-plugin:0.1.4'
    ...
}

I have a problem:

$ mvn web3j:generate-sources
[INFO] Scanning for projects...
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml (14 kB at 24 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml (20 kB at 37 kB/s)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.308 s
[INFO] Finished at: 2018-02-06T19:57:07+03:00
[INFO] Final Memory: 11M/206M
[INFO] ------------------------------------------------------------------------
[ERROR] No plugin found for prefix 'web3j' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/k06a/.m2/repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException

Failed to build solidity interface

Building of solidity interface failed on version 0.3.0
Example:

pragma solidity ^0.4.18;

interface InterCheck {
    function check() public;
}

contract ChecImpl is InterCheck {
    function check() public {
        uint256 i = 0;
        i++;
    }
}

Output:

[INFO] --- web3j-maven-plugin:0.3.0:generate-sources (default-cli) @ Solidity-interface ---
[INFO] Adding to process 'Inter.sol'
[INFO] Solidity Compiler not installed.
[INFO] Solidity Compiler from library is used
[INFO] 	Compile Warning:
Warning: This is a pre-release compiler version, please do not use it in production.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.460 s
[INFO] Finished at: 2018-05-15T09:49:45-07:00
[INFO] Final Memory: 16M/248M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.web3j:web3j-maven-plugin:0.3.0:generate-sources (default-cli) on project Solidity-interface: Could not parse SolC result: SyntaxError: Invalid JSON: <json>:1:0 Expected json literal but found u
[ERROR] undefined
[ERROR] ^ in <eval> at line number 1
[ERROR] -> [Help 1]

Generated Java file contains issue of unresolvable dependencies

My pom.xml looks like this

<dependency>
            <groupId>org.web3j</groupId>
    <artifactId>web3j-spring-boot-starter</artifactId>
    <version>1.6.0</version>
</dependency>
<plugin>
    <groupId>org.web3j</groupId>
    <artifactId>web3j-maven-plugin</artifactId>
    <version>4.2.0</version>
    <executions>
        <execution>
            <id>generate-sources-web3j</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate-sources</goal>
            </goals>
            <configuration>
                <soliditySourceFiles/>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${project.basedir}/src/main/java/generated</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>


On executing mvn web3j:generate-sources generates the src/main/java/org/web3J/model/CryptoPunkMarket which is the java wrappeer of the solidity contract ,

But in this java file , 2 dependenciees are not resolveable which are
io.reactivex.Flowable and org.web3j.tx.gas.ContractGasProvider .Taking a closer look found that they are not even in the external dependencies (there is not gas package inside org.web3J.tx) . Likewise for io.reactivex . there is no Flowable. I am using java 1.8 , smart contract version is solidity 0.4.8 and solidity local compiler version is 0.4.26+

Thanks ,

Inconsistent behavior in a OSX context

Hello,

I've cloned the 0.1.2 version and tried a mvn clean install.

Here is my mvn banner (-version):

Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T21:39:06+02:00)
Maven home: /Users/oschmitt/java/tools/maven/apache-maven-3.5.0
Java version: 1.8.0_131, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre
Default locale: fr_FR, platform encoding: UTF-8
OS name: "mac os x", version: "10.12.5", arch: "x86_64", family: "mac"

One test does not pass, an assertion failed with a strange compiler output :
/private/var/folders/86/kjgz0dfn7gb9y4pp6dcw_vqw0000gn/T/solc/solc: /private/var/folders/86/kjgz0dfn7gb9y4pp6dcw_vqw0000gn/T/solc/solc: cannot execute binary file

It's the SolidityCompilerTest and the compileContract method.

If if run the test alone with IntelliJ for instance, the test passes.

Regards.

Contract.deploy creates type 0 transactions (not EIP-1559)

When deploying a smart contract using the auto-generated deploy method, a legacy transaction is created. Considering that contract depoyments typically consume a lot of gas, it would be preferrable to use the new EIP-1559 format.

Does not run on "mvn compile"

I have added plugin to generate wrapper for smart contract:

          <plugin>
                <groupId>org.web3j</groupId>
                <artifactId>web3j-maven-plugin</artifactId>
                <version>0.1.5-SNAPSHOT</version>
                <configuration>
                    <packageName>name.antonsmirnov.apptogether.ethereum</packageName>
                    <sourceDestination>target/generated-sources/java</sourceDestination>
                    <nativeJavaType>true</nativeJavaType>
                    <soliditySourceFiles>
                        <directory>src/main/resources</directory>
                        <includes>
                            <include>**/*.sol</include>
                        </includes>
                    </soliditySourceFiles>
                </configuration>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>generate-sources</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

I'm running mvn generate-sources in parent maven module using the plugin.
However i can't see any generating output:

------------------------------------------------------------------------
[INFO] Building ethereum 1.0
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ ethereum ---
[INFO] Deleting /Users/asmirnov/Documents/dev/src/AppTogether/ethereum/target
[INFO] 
[INFO] --- build-helper-maven-plugin:3.0.0:add-source (default) @ ethereum ---
[INFO] Source directory: /Users/asmirnov/Documents/dev/src/AppTogether/ethereum/target/generated-sources/java added.
[INFO] 
[INFO] --- web3j-maven-plugin:0.1.5-SNAPSHOT:generate-sources (default) @ ethereum ---
[INFO] 
[INFO] ------------------------------------------------------------------------

I can see output directory is not even created:

$ls /Users/asmirnov/Documents/dev/src/AppTogether/ethereum/target/generated-sources/java
ls: /Users/asmirnov/Documents/dev/src/AppTogether/ethereum/target/generated-sources/java: No such file or directory

I've tried to call $mvn web3j:generate-sources in parent project too:

$mvn web3j:generate-sources
...
[ERROR] No plugin found for prefix 'web3j' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/asmirnov/.m2/repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]

Of coarse i have .sol file(s):

$ls ethereum/src/main/resources/
.                       ..                      AppetissimoContract.sol

Cannot specify the location of a solidity compiler exe

I have solc on my path and want to be specific about the version. For some reason the plugin now hands of to Sokt which then tries to download a versions of solc as needed. Is there a way to override this behaviour?

Error when run task :generateContactWrapper

When i install web3j plugin and run task generateContactWrapper, i got a error message:
:compileSolidity
In plugin 'org.web3j.solidity.gradle.plugin.SolidityPlugin' type 'org.web3j.solidity.gradle.plugin.SolidityCompile' field 'pathRemappings' without corresponding getter has been annotated with @Input, @Optional

Generated code do not compile

Dear web3j-maven-plugin,

thanks for the work done and i wish an happy new year.

I have extracted here a small smartcontract that do not compile anymore with your java generator

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project blockchainergy-smartcontracts: Compilation failure
[ERROR] /volatile/home/fl218080/gitBlockChain/blockchainergy-poc/blockchainergy-smartcontracts/target/main/java/com/cea/licia/blockchainenergy/Predictor.java:[43,78] <identifier> expected
[ERROR] -> [Help 1]
[ERROR] 
pragma solidity ^0.4.18;

/**
 * 
 * version 0.3 
 */
contract Predictor {

    /* this runs when the contract is executed */
    function Predictor() public {
        // initialize the variables
    }
    
    // returns an int array by adding to all its elements a scalar value "a"
    function subtractScalar(int[] self, int a) public pure returns (int[] s) {
        s = new int[](self.length);
        for (uint i = 0; i < self.length; i++)
            s[i] = self[i] - a;
    }
    
} // contract Predictor

the generated code snipped is:

    public RemoteCall<List<BigInteger>> subtractScalar(List<BigInteger> self, BigInteger a) {
        Function function = new Function("subtractScalar", 
                Arrays.<Type>asList(new org.web3j.abi.datatypes.DynamicArray<org.web3j.abi.datatypes.generated.Int256>(
                        org.web3j.abi.Utils.typeMap(self, org.web3j.abi.datatypes.generated.Int256.class)), 
                new org.web3j.abi.datatypes.generated.Int256(a)), 
                Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Int256>>() {}));
        return executeRemoteCallSingleValueReturn(function, List<BigInteger>.class);
    }

Do you have any idea why it is not working anymore?

I would appreciate your help.
Thanks
Francois from France

Definition of the function returns a value but is not defined as a view function.

Hello

I have this very simple Smart Contract:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.7.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}

When I compite with java maven

org.web3j
web3j-maven-plugin
4.5.11

I get this warnings:
[WARNING] Definition of the function get returns a value but is not defined as a view function. Please ensure it contains the view modifier if you want to read the return value
[INFO] Built Class for contract 'SimpleStorage'

Why this happens, it is clearly defined as public view

Can anybody help?

Thank you

Will

Can not use plugin with openzeppelin contract imports

I am not able to generate the Java Wrapper of my solidity token contract because of importing openzeppelin contracts into my contract.

<plugin>
    <groupId>org.web3j</groupId>
    <artifactId>web3j-maven-plugin</artifactId>
    <version>4.5.11</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate-sources</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <packageName>com.token.model</packageName>
        <sourceDestination>src/java/com/token/generated</sourceDestination>
        <nativeJavaType>true</nativeJavaType>
        <outputFormat>java</outputFormat>
        <soliditySourceFiles>
            <directory>src/main/resources/contracts</directory>
            <includes>
                <include>**/*.sol</include>
            </includes>
        </soliditySourceFiles>
        <outputDirectory>
            <java>src/java/com/token/generated</java>
        </outputDirectory>
    </configuration>
</plugin>

The installation and version of openzeppelin I use:
npm install [email protected]

The openzeppelin import in my contract file:
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

The error I get when executing the plugin:

C:/<path>/token/contracts/Token.sol:5:1: Error: Source "C:/<path>/token/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol" not found: File outside of allowed directories.
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

Lists of BigInteger as return Value

Hi,
just using your very helpful generator. I realized that changing to version 0.1.14 you simplified the generated wrappers by using Lists instead of DynamicArrays and BigInteger instead of Uint256.

However, when my solidity code returns an array of uint, you are generating a wrapper this returns a List. However, your cast doesn't seem to work properly because debugging shows that my Tuple4<BigInteger, List, List, List> is filled with Tuple4<BigInteger, List, List, List> instead like you can see below.

image

Java is of course raising compile errors when trying to use Uint256 instead of BigInteger, but not using it means having a ClassCastException. To solve I need to manually adjust to return Uint256 in all lists I use.

It would be much easier for me, when you can fix this issue on your side and having a working cast.

Thanks!

Generated code cannot deploy EIP-1559 compliant contract

After using the plugin to generate Java wrapper from DocumentRegistry.sol file, I try to deploy contract like this:

        public static void main(final String[] args) throws Exception {
            final String url = "https://rpc.goerli.mudit.blog/";
            final Web3j web3 = Web3j.build(new HttpService(url));

            final Credentials creds = Credentials.create("private-key");

            final String fromAddress = creds.getAddress();
            System.out.println("fromAddress = " + fromAddress);

            // Error processing transaction request: only replay-protected (EIP-155) transactions allowed over RPC
            final DocumentRegistry registryContract = DocumentRegistry.deploy(web3, creds, new org.web3j.tx.gas.DefaultGasProvider()).send();

            final String contractAddress = registryContract.getContractAddress();
            System.out.println("contractAddress = " + contractAddress);
        }

However, I get this exception:

Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException: Error processing transaction request: only replay-protected (EIP-155) transactions allowed over RPC
	at org.web3j.tx.Contract.deploy(Contract.java:460)
	at org.web3j.tx.Contract.lambda$deployRemoteCall$7(Contract.java:608)
	at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:42)
	at io.kauri.tutorials.java_ethereum.DeployContract$DocumentRegistryContract.main(DeployContract.java:25)
Caused by: java.lang.RuntimeException: Error processing transaction request: only replay-protected (EIP-155) transactions allowed over RPC
	at org.web3j.tx.TransactionManager.processResponse(TransactionManager.java:176)
	at org.web3j.tx.TransactionManager.executeTransaction(TransactionManager.java:81)
	at org.web3j.tx.ManagedTransaction.send(ManagedTransaction.java:128)
	at org.web3j.tx.Contract.executeTransaction(Contract.java:367)
	at org.web3j.tx.Contract.create(Contract.java:422)
	at org.web3j.tx.Contract.deploy(Contract.java:456)

Plugin configuration is below.

            <plugin>
                <groupId>org.web3j</groupId>
                <artifactId>web3j-maven-plugin</artifactId>
                <version>4.8.2</version>
                <executions>
                    <execution>
                        <id>generate-sources-web3j</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>generate-sources</goal>
                        </goals>
                        <configuration>
                            <packageName>me.gjeanmart.tutorials.javaethereum.contracts.generated</packageName>
                            <sourceDestination>${basedir}/target/generated-sources/contracts</sourceDestination>
                            <soliditySourceFiles>
                                <directory>${basedir}/src/main/resources</directory>
                                <includes>
                                    <include>**/*.sol</include>
                                </includes>
                            </soliditySourceFiles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Source DocumentRegistry.sol is attached: DocumentRegistry.sol

Generate the ABI elements

Will it be possible to generate also the ABI files in the generated folder?
It will be usefull to provide a tooling able to parse the transaction.input parameter directly?
Any idea on how to do it?

Several projects in javascritp are doint it 1

Upgrade to web3j 3.5.0

Haven't tried it, but as eg. the default CLI for macos is 3.5.0 and the maven generation still points to 3.4.0, I assume that this might cause errors. At least it was the case with <3.4.0 and CLI 3.4.0.
Anyways, if a CLI version is provided (which is good), it might make sense to also upgrade the other tools using the same class creation and generation functionality.

Bintray Repository Shutdown

I am unable to use the plugin, since it cannot access the Bintray repository (mentioned in https://github.com/web3j/web3j-maven-plugin/blob/master/pom.xml). I am receiving the following error in maven:

Error:  Failed to execute goal org.web3j:web3j-maven-plugin:4.2.0:generate-sources (generate-sources) on project 
org.eclipse.winery.accountability: Execution generate-sources of goal org.web3j:web3j-maven-plugin:4.2.0:generate-sources 
failed: Plugin org.web3j:web3j-maven-plugin:4.2.0 or one of its dependencies could not be resolved: Failed to collect 
dependencies at org.web3j:web3j-maven-plugin:jar:4.2.0 -> org.ethereum:solcJ-all:jar:0.4.25: Failed to read artifact descriptor for 
org.ethereum:solcJ-all:jar:0.4.25: Could not transfer artifact org.ethereum:solcJ-all:pom:0.4.25 from/to ethereum 
(https://dl.bintray.com/ethereum/maven/): authorization failed for
 https://dl.bintray.com/ethereum/maven/org/ethereum/solcJ-all/0.4.25/solcJ-all-0.4.25.pom, status: 403 Forbidden -> [Help 1]

(I know the plugin version I have is old, but I don't think the error relates to that)
I found this notification that the Bintray is shutting down in May 2021 altogether:
https://lists.boost.org/Archives/boost/2021/02/250813.php

CANNOT BUILD

when I build the project followed by the instruction, it shows error:

mvn web3j:generate-sources
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] Malformed POM /Users/jialiang/Desktop/devp/onlinevm/web3j-maven-plugin/pom.xml: Unrecognised tag: 'plugin' (position: START_TAG seen ...\n ... @7:13) @ /Users/jialiang/Desktop/devp/onlinevm/web3j-maven-plugin/pom.xml, line 7, column 13
@
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project org.web3j:web3j-maven-plugin:0.3.8-SNAPSHOT (/Users/jialiang/Desktop/devp/onlinevm/web3j-maven-plugin/pom.xml) has 1 error
[ERROR] Malformed POM /Users/jialiang/Desktop/devp/onlinevm/web3j-maven-plugin/pom.xml: Unrecognised tag: 'plugin' (position: START_TAG seen ...\n ... @7:13) @ /Users/jialiang/Desktop/devp/onlinevm/web3j-maven-plugin/pom.xml, line 7, column 13 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/ModelParseException

Testing

Extend the test cases on unit and integration test level

CI Build

  • Integrate a ci service to build and test the plugin after each commit.
  • start the ci build, after each build of web3j library

Plugin now require Java 11 instead of Java 8

Were there any serious reasons to change Java version from 8 to 11, when Web3j 4 originally supports Java 8?
Now if I want to use your plugin, I have to move from Java 8 to 11, which can potentially cause a lot of issues.
Maybe you can revert it back to 8?

Plugin is not compatible with web3j 4

I updated Web3J library to 4.0.3, then tried to recompile contracts with this plugin, but still getting wrappers for web3j 3.6.0 instead of 4. The problem that those wrappers are incompatible with the latest version of web3j, so I can't update the Web3j library to 4.
Please update this plugin.

trying to use your generator : problem of solidity compiler version

Dear web3j-maven-plugin developer,
I have tried to use your maven plugin. I am encountering one error:

[ERROR] Failed to execute goal org.web3j:web3j-maven-plugin:0.1.2:generate-sources (default) on project cf-smartcontracts: Could not compile solidity files
[ERROR] :1:1: Error: Source file requires different compiler version (current compiler is 0.4.8+commit.60cc1668.Linux.g++ - note that nightly builds are considered to be strictly less than the released version
[ERROR] pragma solidity ^0.4.17;
[ERROR] ^----------------------^
[ERROR] :109:9: Error: Undeclared identifier.
[ERROR] require(stakeholderList[supplierID].isRegistered == true);
<<<

I am under Linux centOS 7
I have adapted my PATH to go to the solc-static-linux file

solc --version
solc, the solidity compiler commandline interface
Version: 0.4.18+commit.9cf6e910.Linux.g++

How your plugin is finding the solc compiler ?
Thanks for your help.
Francois

Unsupported type encountered: tuple

When generating sources for a contract which has return or input values which are arrays of a struct, the following error is thrown.

Execution default-cli of goal org.web3j:web3j-maven-plugin:4.6.5:generate-sources failed: Unsupported type encountered: tuple

Below is a sample contract which causes the error above.

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

interface MyContract {
    struct MyData {
        address account;
        uint256 balance;
    }

    function myFunction(address account) external view returns (MyData[] memory data);
}

Can't process function that returns boolean

contract:

pragma solidity ^0.4.0;
contract SomeContract {
  ...
  mapping (string => bool) keys;
  ...
  function hasFeature(string featureKey) public constant returns (bool) {
      return keys[featureKey];
  }

while trying to generate wrapper getting the following exception:

[ERROR] Failed to execute goal org.web3j:web3j-maven-plugin:0.1.3:generate-sources (default-cli) on project ethereum: Execution default-cli of goal org.web3j:web3j-maven-plugin:0.1.3:generate-sources failed: invalid type parameter: boolean -> [Help 1]

I'm having installed solidity compiler 0.4.18 on mac and plugin found it:

[INFO] ------------------------------------------------------------------------
[INFO] Building ethereum 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- web3j-maven-plugin:0.1.3:generate-sources (default-cli) @ ethereum ---
[INFO] process 'SomeContract.sol'
[INFO] Solidity Compiler found
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.993 s
[INFO] Finished at: 2017-11-04T12:42:32+05:00
[INFO] Final Memory: 16M/306M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.web3j:web3j-maven-plugin:0.1.3:generate-sources (default-cli) on project ethereum: Execution default-cli of goal org.web3j:web3j-maven-plugin:0.1.3:generate-sources failed: invalid type parameter: boolean -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

The code can be compiled and function called in Remix. Also if i change return type to uint8 and change the function to return uint8 (1 or 0) everything is okay.

Multiple different pragma versions are not considered and file is randomly taken (probably iterator.next())

I had a problem when I pulled a project which had different versions of solidity files.

Example:
File1.sol:
pragma solidity >0.5.0 <=0.6.0

File2.sol
pragma solidity >0.5.0 <=0.7.0

Sometimes it will take solidity version from File2.sol, sometimes it will take solidity version from File1.sol.
What is problem?
If it randomly takes files and it takes pragma of File2.sol it will take solc 0.6.12 which will not be able to compile File1.

Here is a test which proves this:
Solidity:
File1.sol:

pragma solidity >=0.5.0 <0.6.0;

contract File1 {

}

File2.sol:

pragma solidity >=0.5.0 <0.7.0;

contract File2 {

}

Java:

@Test
    public void differentPragmas() {
        //delete /home/$user/.web3j folder to download evrerytime (fresh install) new solc version
        String currentUsersHomeDir = System.getProperty("user.home");
        try {
            FileUtils.deleteDirectory(Paths.get(currentUsersHomeDir + "/.web3j").toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> source = new LinkedList<>();
        //it will download 0.6.12 version
        source.add("File2.sol");
        source.add("File1.sol");
        CompilerResult result = solidityCompiler.compileSrc("src/test/resources/issue-70", source, new String[0], SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN);
        Assert.assertTrue(result.errors.isEmpty());
    }

First commit in the PR #71 has the test which does not work and commit after contains a simple approach to the solution.

Problem with running from gradle directly

task compileSolidity(type: JavaExec) {
    def solidityGenerator = new JavaClassGeneratorMojo()
    def methods = solidityGenerator.class.declaredFields
    def path = new org.apache.maven.shared.model.fileset.FileSet()
    path.setDirectory("src/main/resources")
    path.setIncludes(["AccountContract.sol"])
    methods.each { it.setAccessible(true) }
    solidityGenerator.packageName = "com.bitclave.node.solidity.generated"
    solidityGenerator.soliditySourceFiles = path
    solidityGenerator.execute()
}
compileJava.doFirst {
    tasks.compileSolidity.execute()
}

=>

* Where:
Build file '/Users/k06a/Projects/base-node/build.gradle' line: 48

* What went wrong:
A problem occurred evaluating root project 'base-node'.
> java.lang.NullPointerException (no error message)

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'base-node'.
  at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
  at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:176)
  at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
  at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:181)
  at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
  at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
  at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
  at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
  at org.gradle.configuration.project.LifecycleProjectEvaluator.access$000(LifecycleProjectEvaluator.java:33)
  at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:53)
  at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:50)
  at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
  at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
  at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
  at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
  at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:648)
  at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:126)
  at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
  at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
  at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
  at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuildAction.execute(DefaultGradleLauncher.java:207)
  at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuildAction.execute(DefaultGradleLauncher.java:204)
  at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
  at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
  at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
  at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:146)
  at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:112)
  at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:95)
  at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:66)
  at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
  at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
  at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
  at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
  at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
  at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
  at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:49)
  at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:31)
  at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
  at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
  at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
  at org.gradle.util.Swapper.swap(Swapper.java:38)
  at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
  at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
  at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
  at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
  at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
  at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
  at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
  at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
Caused by: java.lang.NullPointerException
  at org.web3j.codegen.Generator.write(Generator.java:19)
  at org.web3j.codegen.SolidityFunctionWrapper.generateJavaFiles(SolidityFunctionWrapper.java:99)
  at org.web3j.mavenplugin.JavaClassGeneratorMojo.generatedJavaClass(JavaClassGeneratorMojo.java:130)
  at org.web3j.mavenplugin.JavaClassGeneratorMojo.processContractFile(JavaClassGeneratorMojo.java:87)
  at org.web3j.mavenplugin.JavaClassGeneratorMojo.execute(JavaClassGeneratorMojo.java:66)
  at org.apache.maven.plugin.Mojo$execute.call(Unknown Source)
  at build_4w73mius0dyfnmprttudk9a4$_run_closure4.doCall(/Users/k06a/Projects/base-node/build.gradle:48)
  at org.gradle.api.internal.ClosureBackedAction.execute(ClosureBackedAction.java:71)
  at org.gradle.util.ConfigureUtil.configureTarget(ConfigureUtil.java:160)
  at org.gradle.util.ConfigureUtil.configureSelf(ConfigureUtil.java:136)
  at org.gradle.api.internal.AbstractTask.configure(AbstractTask.java:584)
  at org.gradle.api.internal.project.DefaultProject.task(DefaultProject.java:1158)
  at org.gradle.internal.metaobject.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:464)
  at org.gradle.internal.metaobject.BeanDynamicObject.invokeMethod(BeanDynamicObject.java:176)
  at org.gradle.internal.metaobject.CompositeDynamicObject.invokeMethod(CompositeDynamicObject.java:96)
  at org.gradle.internal.metaobject.MixInClosurePropertiesAsMethodsDynamicObject.invokeMethod(MixInClosurePropertiesAsMethodsDynamicObject.java:30)
  at org.gradle.groovy.scripts.BasicScript.invokeMethod(BasicScript.java:107)
  at org.gradle.groovy.scripts.BasicScript.methodMissing(BasicScript.java:116)
  at build_4w73mius0dyfnmprttudk9a4.run(/Users/k06a/Projects/base-node/build.gradle:38)
  at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
  ... 62 more

Import file not found

Have several solidity sources in src/main/resources:

StorageContract.sol
AccountContract.sol

Second one tries to import first one:

import './StorageContract.sol';
[ERROR] Failed to execute goal org.web3j:web3j-maven-plugin:0.1.4:generate-sources (default-cli) on project base-node: Could not compile solidity files
[ERROR] <stdin>:3:1: Error: Source "StorageContract.sol" not found: File not found.
[ERROR] import './StorageContract.sol';
[ERROR] ^-----------------------------^
[ERROR] -> [Help 1]

Generate methods allowing sending ethers

When mapping a Solidity contract funtion to a Java method, the plugin only creates a method parameter for each function parameter. IMO, it would be good to also generate an additional method allowing sending ethers in the transaction and possibly also allowing tuning gas price and limit for the operation, which would override those previously set for the contract.
So, a function like "function vote(uint8 proposal)" would result in two methods being created, the first one being the currently created "public Future<TransactionReceipt> vote(Uint8 proposal)", the second one being something like "public Future<TransactionReceipt> vote(Uint8 proposal, BigInteger weiValue, BigInteger gasPrice, BigInteger gasLimit)". Note, Contract and ManagedTransaction classes already have methods for dealing with this scenario.

Enhance web3j-maven-plugin to be compatible with Truffle since web3j is compatible with Truffle

In web3j documentation we could find

web3j also supports the generation of Java smart contract function wrappers directly from Truffle’s Contract Schema via the Command Line Tools utility.

$ web3j truffle generate [--javaTypes|--solidityTypes] /path/to/.json -o /path/to/src/main/java -p com.your.organisation.name
And this also can be invoked by calling the Java class:

org.web3j.codegen.TruffleJsonFunctionWrapperGenerator /path/to/.json -o /path/to/src/main/java -p com.your.organisation.name
A wrapper generated this way ia “enhanced” to expose the per-network deployed address of the contract. These addresses are from the truffle deployment at the time the wrapper is generared.

What do we need to do if we want to generate a java wrapper for Truffle?
Is there any way to combine pre existing work?

webj maven plugin not found

Hi ,

when i am running mvn web3j:generate-resources getting below error

below is my pom.xml configuration , please note i have tried different versions

 <dependency>
           <groupId>org.web3j</groupId>
           <artifactId>core</artifactId>
           <version>4.8.4</version>
       </dependency>

       <dependency>
           <groupId>org.web3j</groupId>
           <artifactId>quorum</artifactId>
           <version>4.0.6</version>
       </dependency>

   	<dependency>
   			<groupId>com.squareup.okhttp3</groupId>
   			<artifactId>okhttp</artifactId>
   			<version>4.9.0</version>
   		</dependency>
   		<!-- https://mvnrepository.com/artifact/org.ethereum/solcJ-all -->
<!-- https://mvnrepository.com/artifact/org.web3j/web3j-maven-plugin -->
<dependency>
   <groupId>org.web3j</groupId>
   <artifactId>web3j-maven-plugin</artifactId>
   <version>4.8.2</version>
</dependency>
<plugin>
   	<groupId>org.web3j</groupId>
   	<artifactId>web3j-maven-plugin</artifactId>
   	<version>4.8.1</version>
   	<configuration>
   		<packageName>com.test.quorum.contracts</packageName>
   		<sourceDestination>src/main/java</sourceDestination>
   		<nativeJavaType>true</nativeJavaType>
   		<soliditySourceFiles>
   			<directory>src/main/resources/solidity/contracts</directory>
   			<includes>
   				<include>**/*.sol</include>
   			</includes>
   		</soliditySourceFiles>
   		<abiSourceFiles>
   			<directory>src/main/resources</directory>
   			<includes>
   				<include>**/*.json</include>
   			</includes>
   		</abiSourceFiles>
   		<outputDirectory>
   			<java>src/main/java/generated</java>
   			<bin>src/main/bin/generated</bin>
   			<abi>src/main/abi/generated</abi>
   		</outputDirectory>
   	</configuration>


   </plugin>

The POM for org.web3j:web3j-maven-plugin:jar:4.8.1 is missing, no dependency information available
[WARNING] Failed to retrieve plugin descriptor for org.web3j:web3j-maven-plugin:4.8.1: Plugin org.web3j:web3j-maven-plugin:4.8.1 or one of its dependencies could not be resolved: org.web3j:web3j-maven-plugin:jar:4.8.1 was not found in https://repo.maven.apache.org/maven2 during a previous attempt. This failure was cached in the local repository and resolution is not reattempted until the update interval of central has elapsed or updates are forced
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml (20 kB at 52 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml (14 kB at 35 kB/s)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[ERROR] No plugin found for prefix 'web3j' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo]

No plugin found for prefix 'web3j' in the current project

[INFO] Scanning for projects...
[WARNING] The POM for org.web3j:web3j-maven-plugin:jar:0.3.5-SNAPSHOT is missing, no dependency information available
[WARNING] Failed to retrieve plugin descriptor for org.web3j:web3j-maven-plugin:0.3.5-SNAPSHOT: Plugin org.web3j:web3j-maven-plugin:0.3.5-SNAPSHOT or one of its dependencies could not be resolved: Could not find artifact org.web3j:web3j-maven-plugin:jar:0.3.5-SNAPSHOT
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml (14 KB at 6.9 KB/sec)
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml (20 KB at 9.9 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.712 s
[INFO] Finished at: 2018-10-07T15:43:01+06:00
[INFO] Final Memory: 9M/155M
[INFO] ------------------------------------------------------------------------
[ERROR] No plugin found for prefix 'web3j' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\lict.m2\repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]
[ERROR]

Upgrade the generator to reflect changes in web3j

I have issed an error in web3j 1
Initially I was thinking the error comes from FastRawTransactionManager, in fact after a deeper analysis it is due to the fact the generated code from web3j-Maven-plugin is not compliant with latest changes in web3j plugin.

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

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

default constructor are deprecated super

By adding manually the following one, I was able to solve the error

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

So I would like to propose a PR where the generator is upgraded with a new constructor

Incorrect Return Type

I am using Solc v0.6.9 and we I generate the Java code I am getting the incorrect return type for a few of my ERC20 smart contract functions (e.g., balanceOf).

ERC20 balanceOf function (Solidity code):

function balanceOf(address who) external view returns (uint256);

Java generated method (returns TransactionReceipt):

public RemoteFunctionCall<TransactionReceipt> ERC20BalanceOf(String _erc20Address, String _who) { final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( FUNC_ERC20BALANCEOF, Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(160, _erc20Address), new org.web3j.abi.datatypes.Address(160, _who)), Collections.<TypeReference<?>>emptyList()); return executeRemoteCallTransaction(function); }

Expected Java generated function (returns BigInteger):

public RemoteFunctionCall<BigInteger> ERC20BalanceOf(String _erc20Address, String _who) { final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( FUNC_ERC20BALANCEOF, Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(160, _erc20Address), new org.web3j.abi.datatypes.Address(160, _who)), Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {})); return executeRemoteCallSingleValueReturn(function, BigInteger.class); }

https://ethereum.stackexchange.com/questions/40730/why-is-web3j-java-not-generating-correct-return-types-for-my-contract

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.