Sending Ethereum (ETH) transactions with Web3.js in Node.js is a straightforward process. This guide will walk you through the steps to connect to an Ethereum node, create transactions, and handle gas fees securely.
Prerequisites
Before starting, ensure you have:
- Node.js installed (v14+ recommended)
- npm (comes with Node.js)
- Access to an Ethereum node (e.g., Ganache, Infura, or a local/client node)
Step 1: Install Web3.js
Install the Web3.js library via npm:
npm install web3Step 2: Connect to an Ethereum Node
Use the following code to connect to your Ethereum provider (e.g., Ganache):
const Web3 = require('web3');
// Replace with your provider URL (e.g., Infura or local node)
const provider = new Web3.providers.HttpProvider('http://localhost:8545');
const web3 = new Web3(provider);Step 3: Set Up Account and Private Key
Important: Never hardcode private keys in production. Use environment variables or secure keystores.
const accountAddress = '0xYourAccountAddress'; // Replace
const privateKey = '0xYourPrivateKey'; // Replace
const account = new web3.eth.Account(privateKey);Step 4: Check Account Balance
Verify your ETH balance before sending transactions:
const balance = await web3.eth.getBalance(accountAddress);
console.log(`Balance: ${web3.utils.fromWei(balance, 'ether')} ETH`);Step 5: Send a Transaction
Send ETH to a recipient address:
const recipientAddress = '0xRecipientAddress'; // Replace
const amount = web3.utils.toWei('1', 'ether'); // 1 ETH in wei
const tx = {
from: accountAddress,
to: recipientAddress,
value: amount,
gas: 21000, // Standard gas limit for ETH transfers
};
// Sign and send the transaction
const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log('Transaction receipt:', receipt);Key Considerations
- Gas Fees: Transactions require gas. Use
web3.eth.estimateGas()for dynamic gas calculation. - Security: Store private keys securely (e.g., using
.envfiles or hardware wallets). - Network: Test transactions on a testnet (e.g., Goerli) before mainnet.
FAQ
Q1: How do I get test ETH for development?
A: Use a faucet (e.g., Goerli Faucet) to request test ETH for free.
Q2: Why is my transaction pending?
A: Check gas prices (Etherscan Gas Tracker) and resend with higher gas if needed.
Q3: Can I send ERC-20 tokens with this method?
A: No. ERC-20 transfers require interacting with smart contracts. ๐ Learn more about ERC-20 transfers.
Advanced Tips
- Batch Transactions: Use
web3.eth.sendSignedTransactionfor multiple TXs. - Event Listening: Track transactions with
web3.eth.subscribe('pendingTransactions').
For more Ethereum development guides, explore ๐ OKX's developer resources.