API Reference
DocumentationLog In

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

Prerequisites

In order to complete this guide, you need a Node.js project.

To create a new project, run:

npm init -y

Install

Once you have a working Node.js project, add web3.js as a dependency.

To install web3.js, run the following command from the root directory of your project:

npm install web3

Setup

Import

Before you can start using web3.js in your project’s code, you need to import it.

Add the following line of code to the top of your file to import web3.js:

const Web3 = require('web3');

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.

To add these credentials to your project:

  1. Create a file named .env to store environment variables
  2. Add the following environment variables to the .env file, replacing the values with your project’s credentials.
NODE_ENDPOINT=<YOUR_ENDPOINT>
NODE_USERNAME<YOUR_USERNAME>
NODE_PASSWORD<YOUR_PASSWORD>

To access these environment variables within your project, add the following lines of code to your JavaScript file:

const url = process.env.NODE_ENDPOINT;
const username = process.env.NODE_USERNAME;
const password = process.env.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 web3.js, you can use the HttpProvider method.

HttpProvider accepts an endpoint URL and a list of options as arguments.

Copy the following code to create a node provider using web3.js and your Coinbase Node project’s credentials:

// Import environment variables
const url = process.env.NODE_ENDPOINT;
const username = process.env.NODE_USERNAME;
const password = process.env.NODE_PASSWORD;

// Create base64 string of project credentials
const string = `${username}:${password}`;
const base64String = Buffer.from(string).toString("base64");

// Options
const options = {
   keepAlive: true,
   withCredentials: true,
   timeout: 20000, // ms
   headers: [
       {
           name: 'Authorization',
           value: `Basic ${base64String}`
       },
   ]
};

// Create web3 node provider using project credentials
const web3Provider = new Web3.providers.HttpProvider(url, options);
const web3 = new Web3(web3Provider);

Accessing blockchain data

Now that you have a web3 node provider, you can access data from the blockchain.

To demonstrate reading data from the blockchain using web3.js, copy the following code:

// Function to read information from the blockchain
async function getBlockchainInfo () {

   let latestBlock = await web3.eth.getBlockNumber().then((result) => {
       console.log("Latest Ethereum Block is ", result);
       return result;
     });

   let getTransaction = await web3.eth.getBlock(latestBlock).then(result =>{
       console.log("Information about block", result)
        if (result.transactions.length !== null) {
           return result.transactions[0];
       }
       else {
           console.log(`No transactions found for ${latestBlock}`)
           return null;
       }
   });

   if (getTransaction != null ){
       let getTransactionInfo = web3.eth.getTransaction(getTransaction).then(result => {
           console.log("Information about transaction", result)
           return;
       });
   }
};

// Execute function
getBlockchainInfo()

The code above performs the following:

  • Gets the latest Ethereum block number
  • Gets a information for a block using it’s block number
  • Gets information about a transaction within a block

To run the code above, run the following command:

node app.js

Running the code results in an output similar to the following:

Latest Ethereum Block is  14981397
Information about block {
  hash: '0x5926a2cdaf844797e32eb4e2b0b54985199bc61c8bbc463f7e2d264e8aa61286',
  parentHash: '0xa6a92ecf2ae3b66a41756b1a63304e1b82fb2339534d170240d5cbfd91f66298',
  number: 14981397,
  timestamp: 1655501356,
  nonce: '0xc5ad61f221fef0af',
  difficulty: null,
  gasLimit: BigNumber { _hex: '0x01c95111', _isBigNumber: true },
  gasUsed: BigNumber { _hex: '0x0b568d', _isBigNumber: true },
  miner: '0xab3B229eB4BcFF881275E7EA2F0FD24eeaC8C83a',
  extraData: '0x706f6f6c696e2e636f6d246a93ca206f28c475',
  transactions: [
    '0x564f35a035806aef2acd5875c41e728c58aa0ea62ff013ce5b77f503a4d1deb2',
    … 
 ],
  baseFeePerGas: BigNumber { _hex: '0x0596ead5a2', _isBigNumber: true },
  _difficulty: BigNumber { _hex: '0x3270bb6dc08e8a', _isBigNumber: true }
}
Information about transaction {
  hash: '0x564f35a035806aef2acd5875c41e728c58aa0ea62ff013ce5b77f503a4d1deb2',
  type: 2,
  accessList: [],
  blockHash: '0x5926a2cdaf844797e32eb4e2b0b54985199bc61c8bbc463f7e2d264e8aa61286',
  blockNumber: 14981397,
  transactionIndex: 0,
  confirmations: 1,
  from: '0xFDF2E512A7545C68EB14Bae985e3db1D9c0CD2E1',
  gasPrice: BigNumber { _hex: '0x068555fda2', _isBigNumber: true },
  maxPriorityFeePerGas: BigNumber { _hex: '0xee6b2800', _isBigNumber: true },
  maxFeePerGas: BigNumber { _hex: '0x2e90edd000', _isBigNumber: true },
  gasLimit: BigNumber { _hex: '0xce7c', _isBigNumber: true },
  to: '0x0Cfb5d82BE2b949e8fa73A656dF91821E2aD99FD',
  value: BigNumber { _hex: '0x00', _isBigNumber: true },
  nonce: 41,
  data: '0x23b872dd000000000000000000000000fdf2e512a7545c68eb14bae985e3db1d9c0cd2e10000000000000000000000002504407012559909eb9ea18273d2617d0c6582430000000000000000000000000000000000000000000000000002000c00000b98',
  r: '0x1918d7aaad914811a7260b05a025452b9fb5b0140fe2038bd941794d086241b7',
  s: '0x40c1a1f6bc3fe33a5e8ff8c0956af6a93c05951297192b8de37757de068e7f30',
  v: 0,
  creates: null,
  chainId: 1,
  wait: [Function (anonymous)]
}