一、核心概述:Web3.js是什么?
Web3.js 是以太坊官方推荐的 库,用于与以太坊区块链节点进行交互。通过 Web3.js,开发者可以在网页、Node.js 等 环境中,实现查询账户余额、发送交易、部署和调用智能合约等核心功能。本文提供从环境搭建到实际调用的完整操作路径,所有代码均基于 Web3.js 1.x 稳定版本,确保生产环境可用。
二、环境准备与安装
2.1 前提条件
Node.js 环境(建议 v14 及以上)
一个可访问的以太坊节点(可自建节点或使用第三方服务,如 、)
2.2 安装 Web3.js
在项目目录中执行:
npm web3
若使用 Yarn:
yarn add web3
安装完成后,在代码中引入:
const Web3 = ('web3');
// 或 ES6 模块
Web3 from 'web3';
三、连接以太坊节点
3.1 通过 HTTP 连接(推荐使用 等节点服务)
// 使用 节点(需注册获取 )
const web3 = new Web3(';);
// 或使用本地节点(如 测试网)
const web3 = new Web3(':8545');
3.2 通过 连接(支持事件订阅)
const web3 = new Web3('wss://..io/ws/v3/YOUR--ID');
3.3 验证连接
.()
.then(() => .log('节点连接成功'))
.catch(err => .error('连接失败', err));
四、基础账户操作
4.1 查询账户余额
const = '6c';
web3.eth.()
.then( => {
// 余额单位是 wei,转换为 ether
const ether = web3.utils.(, 'ether');
.log(${} 余额: ${ether} ETH);
});
4.2 获取当前区块号
web3.eth.()
.then( => .log('最新区块:', ));
4.3 查看交易详情
const = '0x...';
web3.eth.()
.then(tx => .log(tx));
五、发送交易(ETH 转账)
5.1 创建交易对象
const tx = {
from: '0x...', // 发送方地址
to: '0x...', // 接收方地址
value: web3.utils.toWei('0.01', 'ether'), // 转账金额
gas: 21000, // 基础转账 gas 限制
: await web3.eth.(), // 当前 gas 价格
nonce: await web3.eth.('0x...', '') // 交易序号
};
5.2 签名并发送(需提供私钥)
const = '0x...'; // 发送方私钥
const = await web3.eth..(tx, );
const = await web3.eth.n(.);
.log('交易哈希:', .);
六、智能合约交互
6.1 准备合约 ABI 和地址
const = [...]; // 从编译产物获取
const = '0x...';
const = new web3.eth.(, );
6.2 调用只读方法(call)
// 示例:调用一个返回 的 方法
const = await ..('0x...').call();
.log('余额:', );
6.3 发送改变状态的方法(send)
// 需要签名发送,示例:调用 方法
const = '0x...';
const = '0x...';
const data = ..('0x...', 100).();
const tx = {
from: ,
to: ,
gas: ,
: await web3.eth.(),
data: data,
nonce: await web3.eth.(, '')
};
const = await web3.eth..(tx, );
const = await web3.eth.n(.);
.log('交易哈希:', .);
6.4 监听合约事件
..({ : '' })
.on('data', event => .log(event))
.on('error', .error);
七、常用工具函数
7.1 单位转换
// wei 转 ether
web3.utils.('', 'ether'); // '1'
// ether 转 wei
web3.utils.toWei('0.5', 'ether'); // ''
7.2 地址校验
web3.utils.('0x...'); // true/false
7.3 生成新账户
const = web3.eth..();
.log('地址:', .);
.log('私钥:', .);
八、常见问题与最佳实践
8.1 Gas 费用估算
使用 web3.eth. 预计算交易 gas:
const = await web3.eth.(tx);
8.2 交易确认等待
建议使用 web3.eth.t 轮询或配合事件确认交易上链:
const = await web3.eth.t();
if ( && .) {
.log('交易成功');
}
8.3 安全性提示
私钥绝对不要在前端暴露,应使用后端签名或钱包插件(如 )。
生产环境使用 HTTPS/WSS 连接节点,避免中间人攻击。
对用户输入进行严格校验,防止合约漏洞利用。
8.4 测试网络选择
开发测试推荐使用 或 测试网,可通过水龙头获取测试 ETH。

