1 분 소요


Web3j

Web3j 이란 무엇인가

Wrapper 기능

Web3j Java에 설정하고 Test 해보기

dependency 설정

  • Gradle

    • java
    implementation ('org.web3j:core:4.8.7')
    
    • android
    implementation ('org.web3j:core:4.8.7-android')
    
  • maven

    • java 8
    <dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.8.7</version>
    </dependency>
    
    • android
    <dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.8.7-android</version>
    </dependency>
    

Test 코드 작성

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EthServiceTest {

    @Test
    public void getEthClientVersionSync() throws Exception
    {
        HttpService httpService = new HttpService();

        // default port인 8545를 바꿔야 한다면 new HttpService("url입력") 하면 된다.
        Web3j web3j = Web3j.build(new HttpService());
        Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
        System.out.println(web3ClientVersion.getWeb3ClientVersion());
    }


    @Test
    public void getEthClientVersionASync() throws Exception
    {
        Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
        Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();
        System.out.println(web3ClientVersion.getWeb3ClientVersion());
    }

    @Test
    public void getEthClientVersionRx() throws Exception
    {
        Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
        web3.web3ClientVersion().flowable().subscribe(x -> {
            System.out.println(x.getWeb3ClientVersion());
        });

        Thread.sleep(5000);
    }
}
  • ganache-cli를 켜고 테스트를 한다.
# 8545 port로 실행
ganache-cli -d -m -p 8545 -a 5
  • 정상동작 확인