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?Web3,?allows?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-Mask,?Infura, 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.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末艺栈,一起剝皮案震驚了整個(gè)濱河市垢乙,隨后出現(xiàn)的幾起案子她肯,更是在濱河造成了極大的恐慌导绷,老刑警劉巖且预,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異怒详,居然都是意外死亡疗绣,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門器躏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來俐载,“玉大人,你說我怎么就攤上這事登失《粲叮” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵揽浙,是天一觀的道長状婶。 經(jīng)常有香客問我,道長馅巷,這世上最難降的妖魔是什么太抓? 我笑而不...
    開封第一講書人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮令杈,結(jié)果婚禮上走敌,老公的妹妹穿的比我還像新娘。我一直安慰自己逗噩,他們只是感情好掉丽,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開白布跌榔。 她就那樣靜靜地躺著,像睡著了一般捶障。 火紅的嫁衣襯著肌膚如雪僧须。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評(píng)論 1 297
  • 那天项炼,我揣著相機(jī)與錄音担平,去河邊找鬼。 笑死锭部,一個(gè)胖子當(dāng)著我的面吹牛暂论,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播拌禾,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼取胎,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了湃窍?” 一聲冷哼從身側(cè)響起闻蛀,我...
    開封第一講書人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎您市,沒想到半個(gè)月后觉痛,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡茵休,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年秧饮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片泽篮。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡盗尸,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出帽撑,到底是詐尸還是另有隱情泼各,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布亏拉,位于F島的核電站扣蜻,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏及塘。R本人自食惡果不足惜莽使,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望笙僚。 院中可真熱鬧芳肌,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至净薛,卻和暖如春汪榔,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背肃拜。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來泰國打工痴腌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人燃领。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓士聪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親柿菩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,322評(píng)論 0 10
  • 一次搭公車去吃飯雨涛,天色向晚枢舶,年舊的路燈光把樹影投到了車內(nèi)在人們的臉上斑斕,又好似記憶替久,若影若現(xiàn)凉泄。 搭車的人不識(shí)時(shí)務(wù)...
    韋十八閱讀 246評(píng)論 0 0
  • (一) 忽然很想到文山湖走走颅拦,一種強(qiáng)烈的感覺蒂誉。 但在那浪漫的地方一個(gè)人散步,顯得很突兀距帅,于是我思忖著要叫上誰右锨,與我...
    芳晨閱讀 747評(píng)論 0 23
  • KK是我工作過程中認(rèn)識(shí)的姑娘,當(dāng)時(shí)好像是老板讓我找培訓(xùn)機(jī)構(gòu)做公司內(nèi)訓(xùn)碌秸,于是在尋找過程中就認(rèn)識(shí)了KK绍移。 KK屬于我當(dāng)...
    QIU_C閱讀 3,893評(píng)論 0 2
  • 到了這個(gè)年紀(jì)談感情 很多時(shí)候適當(dāng)就好 和年少不同 好的時(shí)候膩膩歪歪 差的時(shí)候一言不發(fā) 問句你怎么了 常常便是沒事放...
    就靜靜聽你說閱讀 342評(píng)論 0 0