Web3.js is a JavaScript library that allows developers to interact with the Ethereum blockchain. It provides an interface to connect web applications (frontends) with smart contracts deployed on the blockchain. Web3.js communicates with Ethereum nodes using the JSON-RPC protocol, enabling both read and write operations to the blockchain, such as querying balances, sending transactions, calling smart contract methods, and more.
Web3.js is essential for developing Decentralized Applications (DApps), especially those that run in the browser and connect to user wallets like MetaMask.
Why Web3.js?
Before blockchain interaction libraries like Web3.js, connecting a web interface with the blockchain was complex and required low-level networking and JSON-RPC calls. Web3.js simplifies this interaction by providing easy-to-use methods and abstractions for developers.
Key Features of Web3.js
- Blockchain Interaction
- Query blockchain data (e.g., balances, transaction details, blocks).
- Send Ether between accounts.
- Monitor and subscribe to events.
- Smart Contract Communication
- Deploy contracts.
- Call contract methods (read and write).
- Listen to contract events.
- Wallet Integration
- Connect to MetaMask or other Ethereum-compatible wallets.
- Sign transactions.
- Provider Configuration
- Connects to Ethereum networks through local nodes (e.g., Ganache) or remote providers (e.g., Infura).
Installation
To use Web3.js in your JavaScript or React project, install it using npm:
npm install web3
Or using a CDN for HTML files:
<script src="https://cdn.jsdelivr.net/npm/web3@1.10.0/dist/web3.min.js"></script>
Initializing Web3
You can initialize Web3.js using MetaMask (browser wallet):
import Web3 from 'web3';
let web3;
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
await window.ethereum.request({ method: 'eth_requestAccounts' }); // Request user accounts
} catch (error) {
console.error("User denied account access");
}
} else {
console.error("Non-Ethereum browser detected. Install MetaMask!");
}
This code connects your DApp to the user’s MetaMask wallet and requests permission to access their accounts.
Interacting with Ethereum
1. Get Accounts
const accounts = await web3.eth.getAccounts();
console.log(accounts);
2. Check Balance
const balance = await web3.eth.getBalance(accounts[0]);
console.log(web3.utils.fromWei(balance, 'ether')); // Convert from Wei to Ether
3. Send Ether
await web3.eth.sendTransaction({
from: accounts[0],
to: '0xRecipientAddress',
value: web3.utils.toWei('0.01', 'ether')
});
Working with Smart Contracts
To interact with a deployed contract, you need:
- ABI (Application Binary Interface)
- Contract Address
const contractABI = [ /* ABI from compiled contract */ ];
const contractAddress = '0xYourContractAddress';
const contract = new web3.eth.Contract(contractABI, contractAddress);
Call a Read-Only Function
const value = await contract.methods.get().call();
console.log(value);
Call a State-Changing Function
await contract.methods.set(42).send({ from: accounts[0] });
Web3.js Utilities
Web3.js includes various utility functions:
- Convert between units:
web3.utils.toWei('1', 'ether'); web3.utils.fromWei('1000000000000000000', 'ether');
- Hashing:
web3.utils.sha3('Hello');
Event Listening
Smart contracts can emit events. Web3.js can listen to those:
contract.events.ValueChanged({}, (error, event) => {
if (!error) {
console.log(event.returnValues);
}
});
Common Use Cases
- Build DApps with real-time updates based on blockchain events.
- Create dashboards that display wallet balances or token holdings.
- Develop NFT platforms and DeFi applications.