Using Web3.js with a Local Ethereum Node

Web3.js is a JavaScript library that allows you to interact with the Ethereum blockchain. To use Web3.js with a local Ethereum node, follow these steps:

1. Set Up Your Local Ethereum Node

You can set up a local Ethereum node using Geth or OpenEthereum (formerly known as Parity). Below, we will use Geth as an example.

Install Geth

First, download and install Geth from the official Ethereum website. Follow the installation instructions for your operating system.

Run Geth

Open your terminal and run the following command to start your local Ethereum node:

geth --http --http.port 8545 --http.api personal,eth,net,web3 --allow-insecure-unlock

This command starts Geth with the HTTP server enabled, allowing Web3.js to connect to it. The APIs specified are the ones you will be using.

2. Set Up Your Web3.js Environment

Ensure you have Node.js and npm installed. Create a new project directory and initialize it:

mkdir myproject
cd myproject
npm init -y

3. Install Web3.js

Install the Web3.js library using npm:

npm install web3

4. Connect Web3.js to Your Local Node

Create a JavaScript file (e.g., app.js) and connect to your local Ethereum node:

const Web3 = require('web3');

// Connect to the local Ethereum node
const web3 = new Web3('http://localhost:8545');

// Check the connection
web3.eth.net.isListening()
.then(() => console.log('Connected to local Ethereum node'))
.catch(e => console.log('Error connecting to local Ethereum node:', e));

5. Interact with the Ethereum Blockchain

You can now interact with the Ethereum blockchain. Below are examples of how to get the current block number and send a transaction.

Get Current Block Number

async function getBlockNumber() {
const blockNumber = await web3.eth.getBlockNumber();
console.log('Current Block Number:', blockNumber);
}

getBlockNumber();

Send a Transaction

To send a transaction, you need to unlock an account and then send Ether. First, create an account using Geth:

geth account new

Then unlock the account using:

geth attach
personal.unlockAccount('YOUR_ACCOUNT_ADDRESS', 'YOUR_PASSWORD')

Now you can send a transaction:

async function sendTransaction() {
const accounts = await web3.eth.getAccounts();

const tx = {
from: accounts[0],
to: 'RECIPIENT_ADDRESS', // Replace with the recipient's address
value: web3.utils.toWei('0.1', 'ether'), // Amount to send in Ether
gas: 2000000,
};

const receipt = await web3.eth.sendTransaction(tx);
console.log('Transaction Receipt:', receipt);
}

sendTransaction();

6. Run Your Code

Execute your JavaScript file using Node.js:

node app.js

Conclusion

By following these steps, you can successfully use Web3.js with a local Ethereum node to interact with the Ethereum blockchain. This setup is essential for developing and testing decentralized applications (dApps) in a controlled environment.