Web3 Development

Web3j Gradle plugin: Solidity compilation & creation of Java bindings

Written by Conor Svensson | Oct 16, 2018 9:46:00 AM
Here at blk.io we’re happy to announce the general availability of the web3j Gradle plugin. Ever since support was added to web3j forsmart contract bindings we’ve wanted to have a Gradle plugin. We were fortunate that Heinz Marti developed (and continues to maintain) a Maven plugin, but as a long time Gradle user it really felt that this was a key tool missing for Java, Android and Kotlin developers.
The plugin takes care of your Solidity compilation and creation of Java bindings automatically, so you can do everything in your IDE (or just two terminal windows if you prefer vim/emacs).

Getting started

To get started, simply add the web3j plugin to your gradle.build file using plugin DSL syntax (recommended):
plugins {
id 'org.web3j' version '0.1.4'
}

Or if you’re using the older style plugin convention:

 

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
           classpath 'org.web3j:web3j-gradle-plugin:0.1.4'
    }
}

apply plugin: 'web3j'

 

Now, all our project requires is for our Solidity code to be placed in a solidity directory in our project.
Now simply run gradlew build to let the plugin do its thing! 
 
When the plugin runs as part of the build phase, you can then see the Solidity binary and ABI files generated by the Solidity compiler, plus the web3j smart contract bindings in the project build directory. 
 
Our automatically generated Solidity ABI and binary files, plus Java contract bindings

Sample project

In this example, we’ve used the web3j sample project which we’ve updated to use the plugin too!

Behind the scenes

The plugin adds a number of tasks to the Gradle build phases which can be viewed by running gradlew tasks --all.
compileSolidity - Compiles Solidity contracts for main source set.
compileTestJava - Compiles test Java source.
compileTestSolidity - Compiles Solidity contracts for test source set.
generateContractWrappers - Generates web3j contract wrappers for main source set.
generateTestContractWrappers - Generates web3j contract wrappers for test source set.
The tasks are self-explanatory, however, the plugin itself is modular, in that the Solidity compilation phase is performed by an additional web3j Solidity Gradle plugin. This means that if you just want to perform Solidity compilation in your project you can by using the dedicated plugin. 
 
There are numerous properties you can configure too should your project not use the default standard configuration. If you have any suggestions for further improvements, please let us know! 
 
Finally thanks to Xavier for doing all of the heavy lifting!