web3.js 是一个基于 JavaScript/Node.js 的完整库集合,用于通过 HTTP、IPC 或 WebSocket 高效连接并操作 以太坊节点。不论你想部署智能合约、监听新区块,还是管理用户钱包,web3.js 几乎覆盖了 Ethereum 开发 的全部调用场景。本指南帮助你十分钟迅速搭建基础环境,并奉上随手可查的 API 总览,让 去中心化应用(DApp) 的开发效率立刻翻倍。
文档总览与学习路径
User Documentation(用户使用手册)
- 快速安装、配置环境
- 回调、Promise、事件三种异步模式详解
- 最易混淆的 json-interface 专用术语表
- API Reference(核心接口参考)
覆盖五大模块:web3.eth、web3.eth.Contract、web3.eth.accounts、web3.utils、web3.eth.personal,以及进阶功能 ENS、BZZ、SHH。
环境准备与安装
1. 快速安装 web3.js
npm install [email protected]如需国内加速,可使用淘宝源:
npm --registry https://registry.npmmirror.com install [email protected]2. 引入并连接节点
const Web3 = require('web3');
// 本地 Geth/Parity 节点示例
const web3 = new Web3('http://localhost:8545');
// 也可接入 WS 或 IPC
// new Web3('ws://localhost:8546');
// new Web3('/Users/me/Library/Ethereum/geth.ipc');3. 验证连接
web3.eth.net.isListening()
.then(() => console.log('✅ 已经连接'))
.catch(e => console.error('❌ 连接失败', e));核心模块速记卡
2.1 web3.eth —— 与以太坊主链对话
| 高频方法 | 典型使用场景 |
|---|---|
getBalance(address) | 读取余额 |
sendTransaction(tx) | 转账、调用合约 |
getBlockNumber() | 获取最新区块高度 |
estimateGas(tx) | 估算 Gas 费用 |
getPastLogs(filter) | 抓取合约事件日志 |
使用示例:
web3.eth.getBalance('0x...').then(console.log);2.2 web3.eth.Contract —— 一键操控智能合约
初始化:
const abi = [...]; // ABI 数组
const address = '0x...'; // 已部署合约地址
const contract = new web3.eth.Contract(abi, address);调用只读方法:
contract.methods.totalSupply().call().then(console.log);发送写交易:
contract.methods.transfer(to, amount).send({ from: accounts[0] });
账户管理和签名
3.1 web3.eth.accounts —— 本地安全钱包
生成、导入、加密、解密,全部本地完成:
const account = web3.eth.accounts.create(); // 创建私钥
const keystore = web3.eth.accounts.encrypt(account.privateKey, 'password123');
const decrypted = web3.eth.accounts.decrypt(keystore, 'password123');3.2 web3.eth.personal —— 解锁节点托管账号
当私钥保存在节点内部,可直接解锁并使用:
web3.eth.personal.unlockAccount('0x...', 'mypassword', 600); // 解锁 10 分钟监听实时事件
通过订阅机制实时查看链上动态:
新区块头:
web3.eth.subscribe('newBlockHeaders').on('data', block => { console.log('⛏️ 新块高度', block.number); });待定交易池:
web3.eth.subscribe('pendingTransactions').on('data', tx => { console.log('💸 检测到待确认交易', tx); });
工具箱 web3.utils
- 单位换算
web3.utils.toWei('1', 'ether')→1000000000000000000 - 地址校验与转换
isAddress('0x...')、toChecksumAddress('0x...') - ABI 编码
encodeFunctionCall轻松生成交易输入数据。
最常被问到的六个问题 FAQ
Q1 web3.js 与 ethers.js 有什么区别?
A:web3.js 功能全面、API 名称与 Ethereum JSON-RPC 一一对应;ethers.js 轻量、对 TypeScript 支持更好。初学者从 web3.js 起步,对 DApp 开发 兼容性极佳。
Q2 如何在浏览器中直接使用?
A:可引入 CDN:
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>再通过 window.Web3 全局变量即可直接调用。
Q3 连接 Infura / Alchemy 等公共节点需要写代理吗?
A:不需要。只需替换 RPC 地址即可:
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_PROJECT_ID');注意加入 密钥 保护,并设置合理的 速率限制。
Q4 web3.eth.accounts.signTransaction 报错“invalid sender”?
A:通常是 chainId 未匹配。主网为 1,Goerli 为 5。写交易前:
web3.eth.getChainId().then(chainId => console.log(chainId));Q5 部署合约时报错“out of gas”?
A:先用 estimateGas 预估上限,再乘 1.2 倍安全系数:
const gas = await contract.methods.constructor(param).estimateGas();
await contract.deploy({ data, arguments }).send({ gas: Math.floor(gas * 1.2) });Q6 如何监听 DeFi 代币的 Transfer 事件?
A:使用 getPastEvents 与订阅双管齐下:
const TOKEN = new web3.eth.Contract(ERC20_ABI, TOKEN_ADDRESS);
// 历史 10000 区块扫描
TOKEN.getPastEvents('Transfer', { fromBlock: latest - 10000, toBlock: 'latest' })
.then(console.log);
// 实时扫描
TOKEN.events.Transfer({ fromBlock: 'latest' })
.on('data', event => console.log(event.returnValues));结语与下一步
web3.js 1.0.0 版本拥有完备的 TypeScript 声明文件、更清晰的 Promise/Subscribe 混合风格,以及全新的 JSON Schema Validator,几乎覆盖了所有现代 Ethereum 开发 需求。把本文保存为书签,遇到问题直接搜索文中模块与方法,可节省超 50% 调试时间。
开始构建你的第一款 去中心化应用 吧!
- 安装环境
- 部署合约并在前端调用
- 加入事件监听与钱包交互
祝编码愉快,链上相见!