Web3.js 入门:如何连接以太坊公网进行交互**
以太坊作为全球领先的区块链平台,其庞大的生态系统和去中心化应用(DApps)的开发离不开与区块链网络的交互,而 Web3.js 作为最流行、最成熟的 JavaScript 库之一,为前端开发者提供了一套强大的工具,使得通过网页与以太坊网络(包括公网)进行通信成为可能,本文将详细介绍如何使用 Web3.js 连接到以太坊公网,并展示一些基本的交互操作。
连接以太坊公网意味着你的 DApp 将与真实的、去中心化的以太坊主网进行交互,处理真实的资产和合约。
在开始之前,你需要确保你的项目环境中已经安装了 Web3.js,如果你使用 Node.js 和 npm/yarn,可以通过以下命令安装:
npm install web3yarn add web3
如果你在 HTML 文件中直接使用,可以通过 CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
连接以太坊公网,本质上需要连接到一个运行在公网上的以太坊节点,这个节点可以通过多种方式获取,最常见的是使用第三方 Infura 或 Alchemy 提供的服务,或者运行自己的全节点(对硬件和带宽要求较高)。
Infura 是一个广泛使用的以太坊节点服务提供商,它为开发者提供稳定可靠的 RPC 接口。
https://mainnet.infura.io/v3/ 开头的 URL,后面跟着你的项目 ID,这个 URL 就是连接以太坊公网的入口。示例 URL: https://mainnet.infura.io/v3/YOUR_PROJECT_ID
注意: 请妥善保管你的项目 ID,不要泄露给他人。
有了节点 URL 后,我们就可以在代码中初始化 Web3.js 实例,并尝试连接到以太坊公网。
const Web3 = require('web3'); // 如果是 Node.js 环境
// 或者,如果是浏览器环境,Web3 已经挂载在 window 对象上
// const Web3 = window.Web3;
// 1. 替换为你的 Infura (或其他服务提供商) 的 URL
const infuraUrl = 'https://mainnet.infura.io/v3/YOUR_PROJECT_ID';
// 2. 创建 Web3 实例
const web3 = new Web3(infuraUrl);
// 3. 验证连接是否成功 (可选)
web3.eth.getBlockNumber()
.then(blockNumber => {
console.log('当前以太坊公网最新区块号:', blockNumber);
console.log('成功连接到以太坊公网!');
})
.catch(error => {
console.error('连接以太坊公网失败:', error);
});
代码解释:
web3 对象现在成为了与以太坊网络交互的入口。web3.eth.getBlockNumber() 方法,我们可以尝试获取当前网络的最新区块号,如果成功打印出区块号,则说明连接已经建立。除了 Infura,还有其他选择:

// 检查 MetaMask 是否安装
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask 已安装!');
// 请求用户授权
await window.ethereum.request({ method: 'eth_requestAccounts' });
// 使用 MetaMask 提供的 provider
const web3 = new Web3(window.ethereum);
// 后续操作...
} else {
console.log('请安装 MetaMask!');
}
一旦成功连接到以太坊公网,你就可以执行各种操作了。
const address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e'; // 替换为你想查询的以太坊地址
web3.eth.getBalance(address)
.then(balance => {
// 余额是 Wei,转换为 ETH
const ethBalance = web3.utils.fromWei(balance, 'ether');
console.log(`地址 ${address} 的余额是: ${ethBalance} ETH`);
})
.catch(error => {
console.error('查询余额失败:', error);
});
发送交易是一个更复杂的过程,需要发送者的私钥签名(通常使用 web3.eth.accounts.signTransaction),并且需要支付 gas 费。
// 注意:在实际应用中,私钥应该安全存储,不要硬编码在代码中!
const senderPrivateKey = 'YOUR_PRIVATE_KEY'; // 发送者的私钥
const senderAddress = '0xYourSenderAddress';
const receiverAddress = '0xReceiverAddress';
const amountInEther = '0.01';
// 构建交易对象
const transaction = {
from: senderAddress,
to: receiverAddress,
value: web3.utils.toWei(amountInEther, 'ether'),
gas: 21000, // 转账交易的 gas 限制通常是 21000
gasPrice: await web3.eth.getGasPrice(), // 获取当前建议的 gas 价格
nonce: await web3.eth.getTransactionCount(senderAddress, 'latest') // 获取发送者的当前 nonce
};
// 签名交易
web3.eth.accounts.signTransaction(transaction, senderPrivateKey)
.then(signedTx => {
// 发送签名后的交易
return web3.eth.sendSignedTransaction(signedTx.rawTransaction);
})
.then(receipt => {
console.log('交易成功!');
console.log('交易收据:', receipt);
})
.catch(error => {
console.error('交易失败:', error);
});
通过 Web3.js 连接到以太坊公网是开发去中心化应用的关键一步,本文介绍了使用 Web3.js 结合 Infura 等节点服务提供商
返回栏目