Lightweight Ethereum Clients Using Web3j

https://www.baeldung.com/web3j

1. Introduction

This tutorial introduces Web3j, a Java implementation of the popular Web3 abstraction library.

Web3j is used to interact with the Ethereum network by connecting to Ethereum nodes using JSON-RPC or familiar standards like HTTP, WebSockets, IPC.

Ethereum is a whole topic unto itself so let’s first take a quick look at what it is!

2. Ethereum

Ethereum is a (1) cryptocurrency (token symbol ETH), (2) distributed supercomputer, (3) blockchain, and (4) smart contract network written in Solidity.

In other words, Ethereum (the network) is run by a bunch of connected servers called nodes that communicate in a kind of mesh topology (technically, this is not exactly true but close enough to get a more solid understanding of how it all works).

Web3j, and its parent library called Web3allows web applications to connect to one of those nodes and thereby submit Ethereum transactions,which are, for all intents and purposes, compiled Solidity smart contract functionsthat have been previously deployed to the Ethereum network. For more information on smart contracts see our article on creating and deploying them with Solidity here.

Each Node broadcasts its changes to every other node so that consensus and verification can be achieved. Thus, each node contains the entire history of the Ethereum blockchain simultaneously thereby creating a redundant backup of all the data, in a tamper-proof way, and via consensus and verification by all the other nodein the network.\

For more detailed information on Ethereum, check out the official page.

3. Set Up

To use the full suite of features provided by Web3j, we have to do a little bit more to get set up than usual. First, Web3j is supplied in several, free-standing, modules each of which can be optionally added to the corepom.xmldependency:

1

2

3

4

5

<dependency>

    <groupId>org.web3j</groupId>

    <artifactId>core</artifactId>

    <version>3.3.1</version>

</dependency>

Please note that the team at Web3j provides a pre-built Spring Boot Starter with some configuration and limited functionality built right in!

We’ll restrict our focus to the core functionalities in this article (including how to add Web3j to a Spring MVC application, so compatibility with a wider-range of Spring webapps is obtained).

A full list of these modules can be found on Maven Central.

3.1. Compiling Contracts: Truffle or Solc

There are two primary ways to compile and deploy Ethereum smart contracts (.solc files):

The official Solidity compiler.

Truffle(an abstraction suite for testing, deploying, and managing smart contracts).

We’ll stick with Truffle in this article. Truffle simplifies and abstracts the process of compiling smart contracts, migrating them, and deploying them to a network. It also wraps the Solc compiler letting us gain some experience with both.

To set up Truffle:

$ npm install truffle -g

$ truffle version

Four key commands we’ll use to initialize our project respectively, compile our app, deploy our app to the Blockchain, and test it respectively:

1

2

3

4

$ truffle init

$ truffle compile

$ truffle migrate

$ truffle test

Now, let’s go over a simple example:

1

2

3

4

5

6

7

pragma solidity ^0.4.17;


contract Example {

  function Example() {

    // constructor

  }

}

Which should yield the following ABI JSON when compiled:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

{

  "contractName": "Example",

  "abi": [

    {

      "inputs": [],

      "payable": false,

      "stateMutability": "nonpayable",

      "type": "constructor"

    }

  ],

  "bytecode": "0x60606040523415600e57600080fd5b603580601b6...,

  "deployedBytecode": "0x6060604052600080fd00a165627a7a72305...,

  //...

}

We can then use the supplied bytecode and ABI within our application to interact with the deployed contracts!

3.2. Testing Contracts: Ganache

One of the easiest ways to work with an Ethereum testnet is to launch own Ganache server. We’ll use the pre-built, out-of-the-box, solution since it’s the easiest to set up and configure. It also provides an interface and server shell for Ganache CLI which drives Ganache under-the-hood.

We can connect to our Ganache server on the default supplied URL address: http://localhost:8545 or http://localhost:7545.

There are a couple of other popular approaches to setting up a test network including using Meta-MaskInfura, orGo-Lang and Geth.

We’ll stick with Ganache in this article since setting up your own GoLang instance (and configuring it as a custom testnet) can be pretty tricky and since the status of Meta-Mask on Chrome is presently uncertain.

We can use Ganache for manual testing scenarios (when debugging or completing our integration testing) or use them for automated testing scenarios (which we have to build our tests around since, in such circumstances, we might not have the available endpoints).

4. Web3 and RPC

Web3 provides a facade and interface for interacting easily with the Ethereum blockchain and Ethereum server nodes. In other words, Web3 facilitates intercommunication between clients and the Ethereum Blockchain by way of JSON-RPC. Web3J is the official Java port of Web3.

We can initialize Web3j for use within our application by passing in a provider (e.g. – the endpoint of a third-party or local Ethereum node):

1

2

3

4

Web3j web3a = Web3j.build(newHttpService());

Web3j web3b = Web3j.build(newHttpService("YOUR_PROVIDER_HERE"));

Web3j myEtherWallet = Web3j.build(

  newHttpService("https://api.myetherapi.com/eth"));

The third option shows how to add in a third-party provider (thereby connecting with their Ethereum node). But we also have the option to leave our provider option empty. In that case, the default port will be used (8545) on localhost instead.

5. Essential Web3 Methods

Now that we know how to initialize our app to communicate with the Ethereum blockchain, let’s look at a few, core, ways to interact with the Ethereum blockchain.

It’s a good policy to wrap your Web3 methods with a CompleteableFuture to handle the asynchronous nature of JSON-RPC requests made to your configured Ethereum node.

5.1. Current Block Number

We can, for example, return the current block number:

1

2

3

4

5

6

7

publicCompletableFuture<EthBlockNumber> getBlockNumber() {

    EthBlockNumber result = newEthBlockNumber();

    result = this.web3j.ethBlockNumber()

      .sendAsync()

      .get();

    returnCompletableFuture.completedFuture(result);

}

5.2. Account

To get the account of a specified address:

1

2

3

4

5

6

7

publicCompletableFuture<EthAccounts> getEthAccounts() {

    EthAccounts result = newEthAccounts();

    result = this.web3j.ethAccounts()

        .sendAsync()

        .get();

    returnCompletableFuture.completedFuture(result);

}

5.3. Number of Account Transactions

To get the number of transactions of a given address:

1

2

3

4

5

6

7

8

publicCompletableFuture<EthGetTransactionCount> getTransactionCount() {

    EthGetTransactionCount result = newEthGetTransactionCount();

    result = this.web3j.ethGetTransactionCount(DEFAULT_ADDRESS,

      DefaultBlockParameter.valueOf("latest"))

        .sendAsync()

        .get();

    returnCompletableFuture.completedFuture(result);

}

5.4. Account Balance

And finally, to get the current balance of an address or wallet:

1

2

3

4

5

6

7

8

publicCompletableFuture<EthGetBalance> getEthBalance() {

    EthGetBalance result = newEthGetBalance();

    this.web3j.ethGetBalance(DEFAULT_ADDRESS,

      DefaultBlockParameter.valueOf("latest"))

        .sendAsync()

        .get();

    returnCompletableFuture.completedFuture(result);

}

6. Working with Contracts in Web3j

Once we’ve compiled our Solidity contract using Truffle, we can work with our compiled Application Binary Interfaces(ABI) using the standalone Web3j command line tool available here or as a free-standing zip here.

6.1. CLI Magic

We can then automatically generate our Java Smart Contract Wrappers (essentially a POJO exposing the smart contract ABI) using the following command:

1

2

3

$ web3j truffle generate [--javaTypes|--solidityTypes]

  /path/to/<truffle-smart-contract-output>.json

  -o /path/to/src/main/java-p com.your.organisation.name

Running the following command in the root of the project:

1

2

web3j truffle generate dev_truffle/build/contracts/Example.json

  -o src/main/java/com/baeldung/web3/contract-p com.baeldung

generated our Example class:

1

2

3

4

publicclassExample extendsContract {

    privatestaticfinalString BINARY = "0x60606040523415600e576...";

    //...

}

6.2. Java POJO’s

Now that we have our Smart Contract Wrapper, we can create a wallet programmatically and then deploy our contract to that address:

1WalletUtils.generateNewWalletFile("PASSWORD", newFile("/path/to/destination"), true);

1Credentials credentials = WalletUtils.loadCredentials("PASSWORD", "/path/to/walletfile");

6.3. Deploy A Contract

We can deploy our contract like so:

1

2

3

4

Example contract = Example.deploy(this.web3j,

  credentials,

  ManagedTransaction.GAS_PRICE,

  Contract.GAS_LIMIT).send();

And then get the address:

1contractAddress = contract.getContractAddress();

6.4. Sending Transactions

To send aTransaction using the Functions of our Contract we  can initialize a Web3j Function with a List of input values and a List of output parameters:

1

2

3

4

List inputParams = newArrayList();

List outputParams = newArrayList();

Function function = newFunction("fuctionName", inputParams, outputParams);

String encodedFunction = FunctionEncoder.encode(function);

We can then initialize our Transaction with necessary gas (used to execute of the Transaction) and nonce parameters:

1

2

3

4

5

6

7

8

9

10

BigInteger nonce = BigInteger.valueOf(100);

BigInteger gasprice = BigInteger.valueOf(100);

BigInteger gaslimit = BigInteger.valueOf(100);


Transaction transaction = Transaction

  .createFunctionCallTransaction("FROM_ADDRESS",

    nonce, gasprice, gaslimit, "TO_ADDRESS", encodedFunction);


EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();

transactionHash = transactionResponse.getTransactionHash();

For a full list of smart contract functionalities see theofficial docs.

7. Conclusion

That’s it! We’ve set up a Java Spring MVC app with Web3j – it’s Blockchain time!

As always, the code examples used in this article are available over on GitHub.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,279评论 0 10
  • 一次搭公车去吃饭,天色向晚,年旧的路灯光把树影投到了车内在人们的脸上斑斓,又好似记忆,若影若现。 搭车的人不识时务...
    韦十八阅读 242评论 0 0
  • (一) 忽然很想到文山湖走走,一种强烈的感觉。 但在那浪漫的地方一个人散步,显得很突兀,于是我思忖着要叫上谁,与我...
    芳晨阅读 711评论 0 20
  • KK是我工作过程中认识的姑娘,当时好像是老板让我找培训机构做公司内训,于是在寻找过程中就认识了KK。 KK属于我当...
    QIU_C阅读 3,888评论 0 2
  • 到了这个年纪谈感情 很多时候适当就好 和年少不同 好的时候腻腻歪歪 差的时候一言不发 问句你怎么了 常常便是没事放...
    就静静听你说阅读 335评论 0 0