Skip to content
All essays
WebMarch 20, 202415 min

Web3.js Development Guide

Master Web3.js for building decentralized applications

Ü
Ümit Uz
Mobile & Full Stack Developer

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

bash
npm install web3
# or
yarn add web3

Getting Started

Connecting to Ethereum

javascript
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:

javascript
// 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

javascript
// 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

javascript
// 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

javascript
// 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

javascript
// 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

javascript
const tx = await web3.eth.getTransaction('0x...');
console.log(tx);
console.log(tx.value);
console.log(tx.from);
console.log(tx.to);

Get Block

javascript
// 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

javascript
// Get nonce (transaction count)
const nonce = await web3.eth.getTransactionCount('0x...');

Sending Transactions

Send transactions to the Ethereum network.

Send Ether

javascript
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

javascript
const gasPrice = await web3.eth.getGasPrice();

const tx = await web3.eth.sendTransaction({
    from: '0x...',
    to: '0x...',
    value: '1000000000000000000',
    gas: 21000,
    gasPrice: gasPrice
});

Estimate Gas

javascript
const gasEstimate = await web3.eth.estimateGas({
    from: '0x...',
    to: '0x...',
    value: '1000000000000000000'
});

Smart Contract Interaction

Deploy and interact with smart contracts.

Deploy Contract

javascript
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

javascript
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

javascript
// 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.

javascript
// 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.

javascript
// 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

javascript
// 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

javascript
// 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

javascript
// 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

javascript
const networkId = await web3.eth.net.getId();
console.log(networkId); // 1 for Mainnet, 5 for Goerli

Get Network Type

javascript
const networkType = await web3.eth.net.getNetworkType();
console.log(networkType); // 'main', 'goerli', etc.

Get Block Number

javascript
const blockNumber = await web3.eth.getBlockNumber();

Get Gas Price

javascript
const gasPrice = await web3.eth.getGasPrice();

Batch Requests

Send multiple requests at once.

javascript
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

javascript
const subscription = await web3.eth.subscribe('newBlockHeaders');

subscription.on('data', (blockHeader) => {
    console.log(blockHeader);
});

subscription.on('error', console.error);

New Pending Transactions

javascript
const subscription = await web3.eth.subscribe('pendingTransactions');

subscription.on('data', (txHash) => {
    console.log(txHash);
});

Contract Events

javascript
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

javascript
try {
    const tx = await web3.eth.sendTransaction({
        from: '0x...',
        to: '0x...',
        value: '1000000000000000000'
    });
} catch (error) {
    console.error(error);
    // Handle error
}

Contract Revert

javascript
try {
    const result = await contract.methods.failingMethod().send({
        from: '0x...'
    });
} catch (error) {
    console.error('Transaction reverted:', error.message);
}

Best Practices

  1. 1Always handle errors properly
  2. 2Use event listeners for transaction confirmation
  3. 3Estimate gas before sending transactions
  4. 4Use appropriate gas price strategies
  5. 5Validate addresses before transactions
  6. 6Use checksum addresses
  7. 7Keep private keys secure
  8. 8Use HD wallets for production

Common Patterns

Transaction with Confirmation

javascript
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

javascript
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.

Enjoyed this essay? Share it.

Related essays

Next essay
Agile Methodology: A Complete Guide for Development Teams