How to Send Ethereum (ETH) Transactions Using Web3.js in Node.js

ยท

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:


Step 1: Install Web3.js

Install the Web3.js library via npm:

npm install web3

Step 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

  1. Gas Fees: Transactions require gas. Use web3.eth.estimateGas() for dynamic gas calculation.
  2. Security: Store private keys securely (e.g., using .env files or hardware wallets).
  3. 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

For more Ethereum development guides, explore ๐Ÿ‘‰ OKX's developer resources.