-
Notifications
You must be signed in to change notification settings - Fork 1
Tutorial Web3j
Tutorial : Deploy a Smart Contract from Java code with Web3j
For the demo the following components are assumed to be correctly installed :
- Java 8 to compile the Web3j lib,
- Maven 3.x to compile the project,
- Docker 1.x to virtualize Geth.
First, download the folder SXP/DemoWeb3j
.
A Dockerfile is provided to build an image that can be executed locally and in offline mode.
This is very useful for development and testing of blockchain applications locally and without any external dependencies like a working Wifi connection.
$ cd DemoWeb3j
$ sudo docker build -t ethereum_geth docker_geth
The above command will create a Docker image named ethereum_geth
.
The resulting Docker image can then be used to start a local Geth client.
$ cd DemoWeb3j
$ sudo docker run -it -p 8545:8545 -d ethereum_geth
Using the default parameters provided in the Dockerfile the Geth client starts mining and building a fresh private and local blockchain. Based on the Dockerfile The Geth client has been set up to contain two initial accounts with the first account being unlocked and ready to send Ethers around as soon as the Geth client has accumulated Ethers from its mining process.
A running Geth container may also be used to work with Geth JavaScript console. To open a console in the running Geth container use the following Docker command.
$ cd DemoWeb3j
$ sudo docker exec -it <container-id> bash
Once in the console of the Geth container, access the running Geth node using /geth attach
as shown below.
root@<container-id>:/# /geth attach
Welcome to the Geth JavaScript console!
instance: Geth/v1.5.9-stable-a07539fb/linux/go1.7.5
coinbase: 0x1002d4b236bf23eef87ff3d0b3beae7931753f79
at block: 2521 (Fri, 03 Mar 2017 15:51:07 UTC)
datadir: /root/.ethereum
modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
> eth.getBalance(eth.coinbase)
1.3259508e+22
> exit
root@<container-id>:/# exit
exit
After cloning this repository build the command line tool using Maven.
mvn clean package
The result of the Maven build is an executable JAR file.
Use the following command to run the web3j Hello World.
java -jar target/DemoWeb3j-1.0-SNAPSHOT.jar
The above command runs class HelloWorld
with default parameters (Port=8545 and IP=localhost).
Connecting to the Geth container the expected output of the command looks like this.
When changing the greeter smart contract (file src/main/resources/greeter.sol
) it will be necessary to re-generate the Java contract wrapper class Greeter
. This can be done by running CompileDemo
as shown in the screenshot below.
In the first step CompileDemo
reads in greeter.sol
and compiles it into byte code (file greeter.bin
) and contract API (file greeter.bin
). In the second step, the web3j wrapper generator is used to create the output (file Greeter.java
).