Blockchain technology continues to revolutionize how we interact with digital systems, and at the heart of Ethereum development lies web3.js — a powerful JavaScript library that enables seamless communication with the Ethereum blockchain. In this comprehensive guide, we’ll explore the web3-eth package in web3.js version 4, focusing on its core functionalities, practical implementation using TypeScript, and best practices for building decentralized applications (dApps). Whether you're deploying smart contracts, sending transactions, or interacting with on-chain data, this tutorial will equip you with the foundational skills needed to succeed.
Setting Up Your Development Environment
Before diving into coding, it's essential to configure a local development environment that mimics real-world blockchain interactions. This allows for safe testing without risking actual funds.
To get started, ensure the following tools are installed:
- Ganache: A personal Ethereum blockchain for development and testing.
- Node.js: A JavaScript runtime environment required to run web3.js.
- npm or Yarn: Package managers for installing dependencies.
Once these prerequisites are in place, create a new project directory and initialize it:
mkdir smart-contract-tutorial
cd smart-contract-tutorial
npm init -y
npm install typescript @types/nodeThis sets up a TypeScript-ready environment where you can begin integrating web3.js.
👉 Discover how to connect your wallet securely and start building dApps today.
Installing and Connecting Web3.js to Ganache
The next step is installing the web3.js library and establishing a connection to your local blockchain via Ganache.
Install the latest version of web3.js:
npm install web3Create a file named index.ts and initialize a connection to Ganache:
import { Web3 } from 'web3';
// Connect to Ganache running on localhost
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
async function logBlockNumber() {
const blockNumber = await web3.eth.getBlockNumber();
console.log('Latest block number:', blockNumber);
}
logBlockNumber().catch(console.error);Run the script using npx ts-node index.ts. If successful, you'll see the current block number printed in the console. If you encounter an ECONNREFUSED error, verify that Ganache is active and listening on port 7545.
Note: While Ganache is ideal for local testing, you can also connect to public testnets or mainnets using services like Infura or Alchemy by simply changing the provider URL.
Deploying Smart Contracts and Managing Transactions
One of the primary uses of the web3-eth package is deploying and interacting with smart contracts. Let’s walk through key operations including fund transfers, gas estimation, and signed transactions.
Sending Ether Between Accounts
Ganache automatically generates test accounts with pre-funded Ether. You can transfer funds between them easily:
import { Web3 } from 'web3';
const web3 = new Web3('http://localhost:7545');
async function sendTransaction() {
const accounts = await web3.eth.getAccounts();
const tx = {
from: accounts[0],
to: accounts[1],
value: web3.utils.toWei('1', 'ether'),
};
const receipt = await web3.eth.sendTransaction(tx);
console.log('Transaction hash:', receipt.transactionHash);
}This example demonstrates basic transaction handling — retrieving accounts, converting Ether values using toWei, and sending a transaction.
Estimating Gas Usage
Efficient gas management is critical in Ethereum development. Use estimateGas to predict the cost before execution:
const deployment = contract.deploy({ data: bytecode, arguments: [1] });
const gasEstimate = await deployment.estimateGas({ from: accounts[0] });
console.log(`Estimated gas: ${gasEstimate}`);You can format output as either BigInt (default) or hexadecimal by passing ETH_DATA_FORMAT.
Signing Transactions Off-Chain
For enhanced security, sign transactions locally before broadcasting:
const privateKey = '0x...'; // From Ganache
const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);This pattern is commonly used in wallets to prevent private key exposure.
👉 Learn how to optimize gas fees and improve transaction success rates.
Direct Import of web3-eth for Lightweight Builds
While importing the full web3 library works well, you can reduce bundle size by importing only the web3-eth module when needed:
import { Web3Eth } from 'web3-eth';
const eth = new Web3Eth('http://localhost:7545');
async function checkBalance() {
const accounts = await eth.getAccounts();
const balance = await eth.getBalance(accounts[0]);
console.log('Balance in wei:', balance);
}This approach is ideal for frontend applications where performance and load time matter.
You can also configure default settings such as transaction type:
eth.setConfig({ defaultTransactionType: '0x1' });Working with Different Transaction Types
Ethereum supports multiple transaction formats, each designed for specific use cases and network conditions.
Legacy Transactions (Type 0)
These are traditional transactions where users manually set gasPrice. They’re still supported but less efficient during network congestion.
const tx = {
from: account.address,
to: recipient,
value: '0x1',
gas: 21000,
gasPrice: await web3.eth.getGasPrice(),
type: 0,
};EIP-2930 Access List Transactions (Type 1)
Introduced in the Berlin hard fork, these transactions include an access list that specifies addresses and storage keys to be accessed, reducing gas costs for complex contract calls.
Example:
const { accessList } = await web3.eth.createAccessList({
to: contractAddress,
data: contractMethodData,
}, 'latest');Useful for interacting with state-heavy contracts efficiently.
EIP-1559 Dynamic Fee Transactions (Type 2)
The most modern and user-friendly format, EIP-1559 replaces volatile gas pricing with a base fee (burned) and an optional priority fee (to miners).
const tx = {
from: account.address,
to: recipient,
value: '0x1',
gasLimit: 21000,
type: 2,
// maxFeePerGas & maxPriorityFeePerGas auto-filled by web3.js
};This model improves predictability and reduces overpayment — now the standard for most dApps.
👉 Explore advanced transaction strategies and boost your dApp’s efficiency.
Best Practices for Ethereum Development
As you build more complex applications, follow these guidelines to ensure security, efficiency, and maintainability:
- Always test contracts on local or test networks before deploying to mainnet.
- Keep dependencies updated to benefit from security patches.
- Never expose private keys in source code; use environment variables or secure vaults.
- Use
estimateGasto avoid out-of-gas failures. - Leverage events for real-time updates in frontend interfaces.
- Employ linting tools like Solhint for cleaner Solidity code.
Frequently Asked Questions (FAQ)
Q: What is the difference between web3.js and ethers.js?
A: Both are Ethereum libraries, but web3.js is more feature-rich and widely adopted in legacy projects, while ethers.js is lightweight and developer-friendly. Web3.js v4 now supports TypeScript natively, closing the gap in usability.
Q: Can I use web3-eth without installing the full web3 package?
A: Yes! You can install and import web3-eth directly to minimize bundle size, especially useful in frontend applications.
Q: How do I handle errors when sending transactions?
A: Wrap transaction calls in try-catch blocks and check rejection reasons. Common issues include insufficient funds, incorrect nonce, or contract reverts.
Q: Is it safe to use Ganache private keys in code?
A: Only in development. Ganache keys are public by design, so never use them in production environments.
Q: What does EIP stand for?
A: Ethereum Improvement Proposal. It's a formal design document suggesting changes or upgrades to the Ethereum protocol.
Q: How can I monitor transaction status after sending?
A: Use web3.eth.getTransactionReceipt(hash) to poll for confirmation or listen to events via WebSocket providers.
Conclusion
The web3-eth package is a cornerstone of Ethereum development, offering robust tools for interacting with the blockchain — from sending transactions to deploying smart contracts. With support for legacy and modern transaction types, gas optimization features, and modular architecture, web3.js v4 empowers developers to build scalable and efficient dApps using TypeScript.
By mastering these fundamentals — setting up a local node, managing accounts, estimating gas, and signing transactions — you're well-equipped to explore more advanced topics like token creation, DeFi integrations, and Layer 2 solutions.
Continue experimenting, stay updated with Ethereum’s evolving standards, and keep building innovative decentralized experiences. The future of web3 is in your hands.
Core Keywords: web3.js, Ethereum development, smart contracts, web3-eth package, TypeScript blockchain, EIP-1559 transactions, gas estimation