在 Node.js 中使用 Web3.js 完成以太坊 ETH 转账全指南

·

关键词: Web3.js、Node.js、以太坊转账、ETH 交易、gas 费估算、钱包安全、测试网

1. 为什么用 Web3.js?

Web3.js 是以太坊官方 SDK,可在 Node.js 环境中无痛操作区块链:查询余额、签名交易、发送 ETH,甚至构建 DeFi 程序。它抽象掉了底层 RPC 的繁琐细节,让开发者专注于业务逻辑。


2. 环境与依赖的快速搭建

  1. 确认 Node.js ≥ v18,并确保已安装 npmpnpm
  2. 安装核心依赖:

    npm install web3 dotenv   # dotenv 用于安全读取私钥
  3. 准备以太坊节点

    • 本地起 Ganache → http://localhost:8545
    • 生产环境 → 使用 Goerli / Sepolia 测试网 RPC,或直接开启 Infura / Alchemy 接口。

3. 三步送出第一笔 ETH

3.1 创建 Ethereum 客户端实例

const Web3 = require('web3');
const web3 = new Web3('https://sepolia.infura.io/v3/YOUR_PROJECT_ID');

3.2 安全地加载地址与私钥

在项目根目录新建 .env

SENDER_ADDRESS=0x...YOUR_ADDRESS
PRIVATE_KEY=0x...YOUR_PRIVATE_KEY

在代码中读取:

require('dotenv').config();
const sender = process.env.SENDER_ADDRESS;
const privateKey = process.env.PRIVATE_KEY;

3.3 计算 gas 与发起转账

const recipient = '0xReceiverAddress';
const valueWei = web3.utils.toWei('0.05', 'ether');

(async () => {
  const nonce = await web3.eth.getTransactionCount(sender, 'latest');
  const gasPrice = await web3.eth.getGasPrice();
  const gasLimit = 21000;             // 普通 ETH 转账固定 21000

  const tx = {
    from: sender,
    to: recipient,
    value: valueWei,
    gas: gasLimit,
    gasPrice,
    nonce,
    chainId: 11155111    // Sepolia 测试网 ChainId
  };

  const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);
  const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
  console.log('交易哈希:', receipt.transactionHash);
})();

4. 新手避坑清单


5. 常见 FAQ

Q1: Sepolia 和 Goerli 哪个更适合测试新手?
A: 推荐 Sepolia,出块更稳定,水龙头限制更小;Goerli 水龙头逐渐枯竭。

Q2: 能一次转大额主网 ETH 吗?
A: 可发送任意数量,但务必先以小额度测试链和钱包签名逻辑,确认无误后再主网大额操作。

Q3: 如何判断转账是否成功?
A: 监听 receipt.status == 1,若 0 表示失败;还可通过 receipt.gasUsed 观察实际消耗。

Q4: 转账预防重放攻击的方法?
A: noncechainId 双重校验确保交易只在目标链生效。

Q5: 需要额外安装 MetaMask 吗?
A: 不需,Node.js 环境用不上浏览器钱包;但你可以用 MetaMask 给测试地址快速领水。

Q6: Web3.js 与 Ethers.js 该选谁?
A: Web3.js 生态最全;Ethers.js 体积更小、类型系统友好。新手先用 Web3.js 还是👉 最快上手示例教程 查看对比。


6. 进阶:动态计算 gas 费用

const eip1559Tip = web3.utils.toWei('1.5', 'gwei');
const block = await web3.eth.getBlock('latest');
const baseFee = block.baseFeePerGas;
const maxFeePerGas = baseFee * 2n + BigInt(eip1559Tip);

const tx = {
  type: 0x2,
  maxFeePerGas,
  maxPriorityFeePerGas: eip1559Tip,
  ...其余字段
};

7. 将转账逻辑封装成服务

// services/ethTransfer.js
class EthTransferService {
  constructor(web3, privateKey) {
    this.web3 = web3;
    this.account = this.web3.eth.accounts.privateKeyToAccount(privateKey);
    this.web3.eth.accounts.wallet.add(this.account);
  }

  async send(to, amountEth) {
    const tx = {
      from: this.account.address,
      to,
      value: web3.utils.toWei(amountEth, 'ether'),
      gas: 21000
    };
    return this.web3.eth.sendTransaction(tx);
  }
}
module.exports = EthTransferService;

8. 安全审计与最佳实践

  1. 私钥分级
    部署服务器使用 密钥托管服务(KMS),本地开发用 .env 但不提交 Git。
  2. 定时轮询余额
    设置阈值预警,避免因矿工费升高导致账户不够用。
  3. 测试覆盖率
    在 CI 中跑单元测试,模拟转账与 gas 估算,Webhook 通知失败记录。

9. 实机演练 5 分钟速通

  1. 打开 VS Code 新建目录:node-eth-transfer-demo
  2. 依步骤 2 安装依赖。
  3. 复制粘贴 3.1 至 3.3 的代码,替换成自己的地址与水龙头领到的测试 ETH。
  4. node index.js 即刻生成交易哈希,浏览器查询 Sepolia 区块浏览器确定 status=1。

恭喜你,已完成 Node.js + Web3.js 以太坊 ETH 转账 全流程!继续尝试批量转账、监听事件或接入 ERC-20 Token,把区块链的威力发挥到极致。