⚡ TECH BLOG
Home
Blog
Tags
About
⚡

Powered by Next.js 15 & Modern Web Tech ⚡

Back to Home

Web3.js Introduction: Connecting Frontend to Blockchain

November 15, 2022
web3blockchainethereumjavascript
Web3.js Introduction: Connecting Frontend to Blockchain

Web3.js Introduction: Connecting Frontend to Blockchain

Web3.js is the most popular library for connecting JavaScript applications to Ethereum. Let's learn how to use it.

Installation

npm install web3

Basic Setup

import Web3 from 'web3';

// Connect to Ethereum node
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_PROJECT_ID');

// Or connect to MetaMask
if (window.ethereum) {
  const web3 = new Web3(window.ethereum);
  await window.ethereum.enable();
}

Getting Account Information

// Get connected accounts
const accounts = await web3.eth.getAccounts();
console.log(accounts[0]); // First account

// Get balance
const balance = await web3.eth.getBalance(accounts[0]);
const ethBalance = web3.utils.fromWei(balance, 'ether');
console.log(`Balance: ${ethBalance} ETH`);

// Get block information
const blockNumber = await web3.eth.getBlockNumber();
const block = await web3.eth.getBlock(blockNumber);

Smart Contract Interaction

// Contract ABI and address
const contractABI = [
  {
    "inputs": [],
    "name": "getValue",
    "outputs": [{"name": "", "type": "uint256"}],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [{"name": "_value", "type": "uint256"}],
    "name": "setValue",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
];

const contractAddress = '0x...';

// Create contract instance
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Read from contract
const value = await contract.methods.getValue().call();
console.log('Current value:', value);

// Write to contract
await contract.methods.setValue(42).send({
  from: accounts[0],
  gas: 100000
});

Sending Transactions

// Send ETH
const tx = await web3.eth.sendTransaction({
  from: accounts[0],
  to: '0x...',
  value: web3.utils.toWei('0.1', 'ether'),
  gas: 21000
});

console.log('Transaction hash:', tx.transactionHash);

// Sign and send transaction
const signedTx = await web3.eth.accounts.signTransaction({
  to: '0x...',
  value: web3.utils.toWei('0.1', 'ether'),
  gas: 21000
}, privateKey);

const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

Event Listening

// Listen for events
contract.events.ValueChanged({
  fromBlock: 0
}, (error, event) => {
  if (error) {
    console.error(error);
    return;
  }
  console.log('Event:', event);
});

// Get past events
const events = await contract.getPastEvents('ValueChanged', {
  fromBlock: 0,
  toBlock: 'latest'
});

Utility Functions

// Convert between units
const wei = web3.utils.toWei('1', 'ether');  // '1000000000000000000'
const eth = web3.utils.fromWei('1000000000000000000', 'ether'); // '1'

// Generate random bytes
const randomHex = web3.utils.randomHex(32);

// Hash functions
const hash = web3.utils.sha3('hello world');
const keccak256 = web3.utils.keccak256('hello world');

MetaMask Integration

async function connectWallet() {
  if (typeof window.ethereum !== 'undefined') {
    try {
      const accounts = await window.ethereum.request({
        method: 'eth_requestAccounts'
      });
      console.log('Connected:', accounts[0]);
    } catch (error) {
      console.error('User rejected connection');
    }
  } else {
    console.log('Please install MetaMask');
  }
}

// Listen for account changes
window.ethereum.on('accountsChanged', (accounts) => {
  console.log('Account changed:', accounts[0]);
});

// Listen for chain changes
window.ethereum.on('chainChanged', (chainId) => {
  window.location.reload();
});

React Hook for Web3

import { useState, useEffect } from 'react';
import Web3 from 'web3';

function useWeb3() {
  const [web3, setWeb3] = useState(null);
  const [account, setAccount] = useState(null);
  const [balance, setBalance] = useState(null);

  useEffect(() => {
    if (window.ethereum) {
      const web3Instance = new Web3(window.ethereum);
      setWeb3(web3Instance);
    }
  }, []);

  const connect = async () => {
    if (!window.ethereum) return;
    
    const accounts = await window.ethereum.request({
      method: 'eth_requestAccounts'
    });
    setAccount(accounts[0]);
    
    const balance = await web3.eth.getBalance(accounts[0]);
    setBalance(web3.utils.fromWei(balance, 'ether'));
  };

  return { web3, account, balance, connect };
}

Best Practices

  1. Always check for wallet availability
  2. Handle errors gracefully
  3. Use proper gas estimation
  4. Implement proper security measures
  5. Cache contract instances

Conclusion

Web3.js provides a powerful interface for connecting frontend applications to Ethereum. With proper integration, you can build feature-rich decentralized applications.

Share:

💬 Comments