Web3.js Tutorial

Master Web3.js for Ethereum development. Build dApps with wallet connections, smart contracts, and transactions.

What is Web3.js?

Web3.js is a JavaScript library for interacting with Ethereum blockchain. It allows websites to connect to wallets, read blockchain data, and send transactions.

Installation

npm install web3

Or use via CDN:

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>

Connect to Ethereum

Connect to RPC

import Web3 from 'web3';

const rpcURL = "https://mainnet.infura.io/v3/YOUR_INFURA_KEY";
const web3 = new Web3(rpcURL);

console.log(web3.eth);

Connect Wallet (MetaMask)

Request Account Access

async function connectWallet() {
  if (window.ethereum) {
    try {
      const accounts = await window.ethereum.request({
        method: "eth_requestAccounts"
      });
      console.log("Connected:", accounts[0]);
      return accounts[0];
    } catch (error) {
      console.error("Error connecting:", error);
    }
  } else {
    alert("Please install MetaMask!");
  }
}

Check Wallet Balance

async function getBalance(address) {
  const balance = await web3.eth.getBalance(address);
  const ethBalance = web3.utils.fromWei(balance, 'ether');
  console.log("Balance:", ethBalance, "ETH");
}

Send Transaction

Transfer ETH

async function sendEth(toAddress, amount) {
  const accounts = await web3.eth.getAccounts();
  const from = accounts[0];
  
  const tx = {
    from: from,
    to: toAddress,
    value: web3.utils.toWei(amount, 'ether'),
    gas: 21000,
    gasPrice: await web3.eth.getGasPrice()
  };
  
  const receipt = await web3.eth.sendTransaction(tx);
  console.log("Transaction hash:", receipt.transactionHash);
}

Interact with Smart Contract

Call Contract Methods

const contractAddress = "0x123...";
const abi = [...]; // Contract ABI

const contract = new web3.eth.Contract(abi, contractAddress);

// Read data (view function)
const balance = await contract.methods.balanceOf(walletAddress).call();

// Write data (state-changing function)
await contract.methods.transfer(toAddress, amount).send({
  from: walletAddress
});

Listen to Events

// Listen for Transfer events
contract.events.Transfer({
  filter: { from: walletAddress },
  fromBlock: 'latest'
})
.on('data', (event) => {
  console.log("Transfer event:", event.returnValues);
})
.on('error', console.error);

Web3.js vs Ethers.js

  • Web3.js: Older, larger community, more tutorials
  • Ethers.js: Lighter, more modern API, better TypeScript support

Both are excellent choices. Ethers.js is recommended for new projects.

Next Steps

  • Learn Ethers.js for a more modern API
  • Explore Wagmi for React applications
  • Build a complete NFT marketplace
  • Integrate with IPFS for decentralized storage