API Reference
DocumentationLog In

This guide demonstrates how to integrate your Coinbase Cloud Node project with Web3j.

Prerequisites

In order to complete this guide, you need a Java project setup with Gradle or Maven.

Setup dependencies

Once you have a working Java project, add Web3j as a dependency to your project.

Gradle

Add Web3j as a dependency to build.gradle:

dependencies {
    implementation 'org.web3j:core:4.8.7'
}

Maven

Add Web3j as a dependency to pom.xml:

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.8.7</version>
</dependency>

Authorization

Users that create a Coinbase Node project, are provided with the following credentials:

  • An API endpoint
  • A username
  • A password

These credentials allow you to make authorized requests for reading and writing to the blockchain.

Store these credentials in environment variables:

  • Add the following environment variables, replacing the values with your project’s credentials:
export NODE_ENDPOINT=<YOUR_ENDPOINT>
export NODE_USERNAME<YOUR_USERNAME>
export NODE_PASSWORD<YOUR_PASSWORD>

To read these environment variables within your Java project, add the following lines of code to your Java class file:

```java
private static final String ENDPOINT = System.getenv(“NODE_ENDPOINT”);
private static final String USERNAME = System.getenv(“NODE_USERNAME”);
private static final String PASSWORD = System.getenv(“NODE_PASSWORD”);

📘

Note: For more information on how to create a Coinbase Node project, see Using Ethereum Clients.

Connecting to a node

In order to access data from the blockchain, you need to connect to the Ethereum node provided by your Coinbase Node project.

To connect to a node using Web3j, you can use the HttpService class.

HttpService accepts an endpoint URL, an HTTP client configured to authenticate requests using a username, and a password.

Copy the following code to create an HttpService node provider using your Coinbase Node project’s credentials:

package com.coinbase.cloud.web3j.demo;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.exceptions.ClientConnectionException;
import org.web3j.protocol.http.HttpService;
 
import java.io.IOException;
 
public class NodeClientDemo {
 
   // Username and Password stored in Env Variables
   private static final String USERNAME = System.getenv(“USERNAME”);
   private static final String PASSWORD = System.getenv(“PASSWORD”);
   private static final String ENDPOINT = System.getenv(“NODE_ENDPOINT”);
   private static final ObjectMapper mapper = new ObjectMapper();
 
   public static void main(String[] args) {
       try {
 
           OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
           clientBuilder.authenticator((route, response) -> {
               String credential = Credentials.basic(USERNAME, PASSWORD);
               return response.request().newBuilder().header("Authorization", credential).build();
           });
 
           HttpService service = new HttpService(ENDPOINT, clientBuilder.build());
           Web3j web3 = Web3j.build(service); 
       } catch (IOException | ClientConnectionException ex) {
           System.out.println(ex.getMessage());
       }
   }
}

Accessing blockchain data

Now that you have a Web3j instance, you can access data from the blockchain.
To demonstrate reading data from the blockchain using Web3j, copy the following code:

          EthBlock.Block latestBlock = web3
                   .ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false)
                   .send()
                   .getBlock();
 
           System.out.println("Latest Block: " + latestBlock.getNumber());
 
           EthBlock.Block specificBlock = web3
                   .ethGetBlockByNumber(new DefaultBlockParameterNumber(14933373), true)
                   .send()
                   .getBlock();
 
           System.out.println("Block 14933373 transaction information: \n"
                   + mapper.writeValueAsString(specificBlock.getTransactions()));
 
           Transaction transaction = (Transaction) specificBlock.getTransactions().get(0).get();
 
           EthTransaction ethTransaction = web3
                   .ethGetTransactionByHash(transaction.getHash())
                   .send();
 
           if (ethTransaction.getTransaction().isPresent()) {
               System.out.println("Transaction: " + ethTransaction.getTransaction().get().getBlockNumber());
           }

The code above performs the following:

  1. Gets the latest Ethereum block number
  2. Gets a information for a block using it’s block number
  3. Gets information about a transaction within a block

To run the code above, run the following commands in the root of your project:

gradle build

./gradlew run

A complete code example can be found below:

package com.coinbase.cloud.web3j.demo;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.exceptions.ClientConnectionException;
import org.web3j.protocol.http.HttpService;
 
import java.io.IOException;
 
public class NodeClientDemo {
 
   // Username and Password stored in Env Variables
   private static final String USERNAME = System.getenv(“USERNAME”);
   private static final String PASSWORD = System.getenv(“PASSWORD”);
   private static final String ENDPOINT = System.getenv(“NODE_ENDPOINT”);
   private static final ObjectMapper mapper = new ObjectMapper();
 
   public static void main(String[] args) {
       try {
 
           OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
           clientBuilder.authenticator((route, response) -> {
               String credential = Credentials.basic(USERNAME, PASSWORD);
               return response.request().newBuilder().header("Authorization", credential).build();
           });
 
           HttpService service = new HttpService(ENDPOINT, clientBuilder.build());
           Web3j web3 = Web3j.build(service);
 
           EthBlock.Block latestBlock = web3
                   .ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false)
                   .send()
                   .getBlock();
 
           System.out.println("Latest Block: " + latestBlock.getNumber());
 
           EthBlock.Block specificBlock = web3
                   .ethGetBlockByNumber(new DefaultBlockParameterNumber(14933373), true)
                   .send()
                   .getBlock();
 
           System.out.println("Block 14933373 transaction information: \n"
                   + mapper.writeValueAsString(specificBlock.getTransactions()));
 
           Transaction transaction = (Transaction) specificBlock.getTransactions().get(0).get();
 
           EthTransaction ethTransaction = web3
                   .ethGetTransactionByHash(transaction.getHash())
                   .send();
 
           if (ethTransaction.getTransaction().isPresent()) {
               System.out.println("Transaction: " + ethTransaction.getTransaction().get().getBlockNumber());
           }
 
       } catch (IOException | ClientConnectionException ex) {
           System.out.println(ex.getMessage());
       }
   }
}