Web3.js is a JavaScript library that allows you to interact with the Ethereum blockchain. It's essential for building decentralized applications (dApps) that read and write data to Ethereum, making it a cornerstone of Web3 development.
What is Web3.js?
Web3.js is a collection of libraries that allow you to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket.
Core Features
- Connect to Ethereum networks
- Read blockchain data
- Send transactions
- Deploy and interact with smart contracts
- Handle wallets and accounts
- Encode and decode data
Installation
npm install web3
# or
yarn add web3Getting Started
Connecting to Ethereum
const Web3 = require('web3');
// Connect to local node
const web3 = new Web3('http://localhost:8545');
// Connect to Mainnet
const web3 = new Web3('https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY');
// Connect to WebSocket provider
const web3 = new Web3('ws://localhost:8545');Provider Options
Popular providers:
// Infura
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');
// Alchemy
const web3 = new Web3('https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY');
// Local Ganache
const web3 = new Web3('http://127.0.0.1:7545');Accounts and Wallets
Web3.js provides utilities for managing accounts.
Creating Accounts
// Create new account
const account = web3.eth.accounts.create();
console.log(account.address);
console.log(account.privateKey);
// Create wallet with multiple accounts
const wallet = web3.eth.accounts.wallet.create(2);
console.log(wallet.length);Importing Accounts
// From private key
const account = web3.eth.accounts.privateKeyToAccount('0x...');
// Add to wallet
web3.eth.accounts.wallet.add(account);
// From mnemonic
const account = web3.eth.accounts.create(mnemonic);Signing Data
// Sign message
const signature = web3.eth.accounts.sign(
'Hello World',
'private-key'
);
// Sign transaction
const signedTx = await web3.eth.accounts.signTransaction({
to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
value: '1000000000000000',
gas: 2000000
}, 'private-key');Reading Blockchain Data
Query the Ethereum blockchain for information.
Get Balance
// Get balance in Wei
const balance = await web3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb');
// Convert to Ether
const balanceInEth = web3.utils.fromWei(balance, 'ether');
console.log(balanceInEth);Get Transaction
const tx = await web3.eth.getTransaction('0x...');
console.log(tx);
console.log(tx.value);
console.log(tx.from);
console.log(tx.to);Get Block
// Get latest block
const block = await web3.eth.getBlock('latest');
// Get block by number
const block = await web3.eth.getBlock(12345678);
// Get block with full transactions
const block = await web3.eth.getBlock('latest', true);Get Transaction Count
// Get nonce (transaction count)
const nonce = await web3.eth.getTransactionCount('0x...');Sending Transactions
Send transactions to the Ethereum network.
Send Ether
const tx = await web3.eth.sendTransaction({
from: '0x...',
to: '0x...',
value: '1000000000000000000', // 1 ETH in Wei
gas: 21000
});
console.log(tx.transactionHash);Send with Gas Price
const gasPrice = await web3.eth.getGasPrice();
const tx = await web3.eth.sendTransaction({
from: '0x...',
to: '0x...',
value: '1000000000000000000',
gas: 21000,
gasPrice: gasPrice
});Estimate Gas
const gasEstimate = await web3.eth.estimateGas({
from: '0x...',
to: '0x...',
value: '1000000000000000000'
});Smart Contract Interaction
Deploy and interact with smart contracts.
Deploy Contract
const abi = [...];
const bytecode = '0x...';
const contract = new web3.eth.Contract(abi);
const deployTx = contract.deploy({
data: bytecode,
arguments: ['constructor', 'args']
});
const gasEstimate = await deployTx.estimateGas();
const contractInstance = await deployTx.send({
from: '0x...',
gas: gasEstimate
});
console.log(contractInstance.options.address);Interact with Contract
const abi = [...];
const address = '0x...';
const contract = new web3.eth.Contract(abi, address);
// Call view function (no gas)
const value = await contract.methods.getValue().call();
// Send transaction (requires gas)
const tx = await contract.methods.setValue(42).send({
from: '0x...',
gas: 100000
});Contract Events
// Get past events
const events = await contract.getPastEvents('Transfer', {
fromBlock: 0,
toBlock: 'latest'
});
// Subscribe to events
contract.events.Transfer()
.on('data', (event) => {
console.log(event);
})
.on('error', console.error);
// Filter events
contract.events.Transfer({
filter: { from: '0x...' },
fromBlock: 0
})
.on('data', (event) => {
console.log(event);
});Unit Conversion
Convert between Ethereum units.
// Wei to Ether
const eth = web3.utils.fromWei('1000000000000000000', 'ether');
// Ether to Wei
const wei = web3.utils.toWei('1', 'ether');
// Other units
const gwei = web3.utils.toWei('1', 'gwei');
const szabo = web3.utils.toWei('1', 'szabo');
const finney = web3.utils.toWei('1', 'finney');Encoding and Decoding
Handle data encoding and decoding.
// ABI encode parameters
const encoded = web3.eth.abi.encodeParameters(
['uint256', 'string'],
[123, 'hello']
);
// ABI decode
const decoded = web3.eth.abi.decodeParameters(
['uint256', 'string'],
encoded
);
// ABI encode function call
const callData = web3.eth.abi.encodeFunctionCall({
name: 'transfer',
type: 'function',
inputs: [{
type: 'address',
name: 'to'
}, {
type: 'uint256',
name: 'amount'
}]
}, ['0x...', '1000']);
// ABI encode parameters
const encodedParams = web3.eth.abi.encodeParameter('uint256', '123');
// Decode log
const decodedLog = web3.eth.abi.decodeLog(
[{
type: 'uint256',
name: 'value'
}],
log.data,
log.topics.slice(1)
);Utility Functions
Various helpful utilities.
Hash Functions
// SHA3
const hash = web3.utils.sha3('hello world');
// Keccak256
const hash = web3.utils.keccak256('hello world');
// Solidity keccak256
const hash = web3.utils.soliditySha3(
{ type: 'uint256', value: 123 },
{ type: 'string', value: 'hello' }
);Address Utilities
// Check if valid address
const isValid = web3.utils.isAddress('0x...');
// Convert to checksum address
const checksum = web3.utils.toChecksumAddress('0x...');
// Check if checksum address
const isChecksum = web3.utils.checkAddressChecksum('0x...');Hex Conversions
// String to hex
const hex = web3.utils.utf8ToHex('hello');
// Hex to string
const str = web3.utils.hexToUtf8('0x...');
// Number to hex
const hex = web3.utils.numberToHex(42);
// Hex to number
const num = web3.utils.hexToNumber('0x2a');Network Information
Get information about the network.
Get Network ID
const networkId = await web3.eth.net.getId();
console.log(networkId); // 1 for Mainnet, 5 for GoerliGet Network Type
const networkType = await web3.eth.net.getNetworkType();
console.log(networkType); // 'main', 'goerli', etc.Get Block Number
const blockNumber = await web3.eth.getBlockNumber();Get Gas Price
const gasPrice = await web3.eth.getGasPrice();Batch Requests
Send multiple requests at once.
const batch = new web3.BatchRequest();
batch.add(web3.eth.getBalance.request('0x...', 'latest', callback1));
batch.add(web3.eth.getTransactionCount.request('0x...', 'latest', callback2));
batch.execute();Subscriptions
Subscribe to blockchain events (WebSocket required).
New Blocks
const subscription = await web3.eth.subscribe('newBlockHeaders');
subscription.on('data', (blockHeader) => {
console.log(blockHeader);
});
subscription.on('error', console.error);New Pending Transactions
const subscription = await web3.eth.subscribe('pendingTransactions');
subscription.on('data', (txHash) => {
console.log(txHash);
});Contract Events
const subscription = await web3.eth.subscribe('logs', {
address: '0x...',
topics: ['0x...']
});
subscription.on('data', (log) => {
console.log(log);
});Error Handling
Handle errors properly.
Transaction Errors
try {
const tx = await web3.eth.sendTransaction({
from: '0x...',
to: '0x...',
value: '1000000000000000000'
});
} catch (error) {
console.error(error);
// Handle error
}Contract Revert
try {
const result = await contract.methods.failingMethod().send({
from: '0x...'
});
} catch (error) {
console.error('Transaction reverted:', error.message);
}Best Practices
- 1Always handle errors properly
- 2Use event listeners for transaction confirmation
- 3Estimate gas before sending transactions
- 4Use appropriate gas price strategies
- 5Validate addresses before transactions
- 6Use checksum addresses
- 7Keep private keys secure
- 8Use HD wallets for production
Common Patterns
Transaction with Confirmation
const tx = await web3.eth.sendTransaction({
from: '0x...',
to: '0x...',
value: '1000000000000000000'
})
.on('transactionHash', (hash) => {
console.log('Transaction hash:', hash);
})
.on('receipt', (receipt) => {
console.log('Transaction receipt:', receipt);
})
.on('error', console.error);Retry Logic
async function sendWithRetry(txObject, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await web3.eth.sendTransaction(txObject);
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}Conclusion
Web3.js is the foundation for interacting with Ethereum from JavaScript. Mastering it enables you to build powerful decentralized applications that read and write to the blockchain, deploy contracts, and handle complex transactions.
Practice with different Web3.js features, understand the Ethereum transaction lifecycle, and build real dApps. Web3.js is your bridge to the world of blockchain development.