在区块链技术飞速发展的今天,以太坊作为全球最大的智能合约平台,承载了无数去中心化应用(Dapps)的梦想,而要将这些复杂的区块链逻辑呈现在用户面前,友好的前端交互至关重要,以太坊 JS API 正是连接 Web 前端与以太坊区块链的桥梁,它为开发者提供了一套强大且易用的工具集,使得在浏览器或 Node.js 环境中与以太坊网络进行交互变得轻而易举,本文将深入探讨以太坊 JS API 的核心概念、常用库以及如何利用它们开启 Web3 前端开发之旅。

以太坊 JS API 并非指某一个单一的库,而是泛指一系列用 JavaScript 编写的库和工具,它们封装了与以太坊节点交互的底层细节(如 JSON-RPC 协议),为开发者提供了高层次的接口,通过这些 API,开发者可以轻松实现以下功能:
在以太坊 JS 生态中,有几个核心库几乎成为了开发者的标配:
Ethers.js
Web3.js

Web3.py (Python)是 JS API,但值得一提的还有 Web3.py,它是 Python 版本的以太坊交互库,对于 Python 开发者来说是类似的存在,本文主要聚焦 JS 生态。
为了更直观地理解以太坊 JS API 的威力,我们以 Ethers.js 为例,展示几个常见操作:
安装 Ethers.js
npm install ethers
连接到以太坊网络

import { ethers } from "ethers";
// 使用 Infura 的公共节点(需要替换为你的 Infura 项目 ID)
const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");
// 或者连接到本地运行的节点(如 Geth, Nethermind)
// const provider = new ethers.providers.JsonRpcProvider("http://localhost:8545");
async function getBalance() {
const address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // 以太坊创始人 Vitalik Buterin 的地址
const balance = await provider.getBalance(address);
console.log(`Balance of ${address}: ${ethers.utils.formatEther(balance)} ETH`);
}
getBalance();
发送交易
import { ethers } from "ethers";
// 创建提供者
const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");
// 创建签名者(需要私钥,实际应用中务必安全存储,不要硬编码)
const privateKey = "YOUR_PRIVATE_KEY";
const wallet = new ethers.Wallet(privateKey, provider);
const recipientAddress = "0xRecipientAddressHere";
const amount = ethers.utils.parseEther("0.01"); // 0.01 ETH
async function sendTransaction() {
console.log("Sending transaction...");
const tx = await wallet.sendTransaction({
to: recipientAddress,
value: amount,
gasLimit: 21000, // 转账 ETH 的典型 gas 限制
});
console.log("Transaction hash:", tx.hash);
await tx.wait(); // 等待交易被打包
console.log("Transaction confirmed!");
}
sendTransaction();
与智能合约交互
假设我们有一个简单的 ERC20 代币合约,其 ABI(应用二进制接口)和地址已知:
import { ethers } from "ethers";
const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");
const privateKey = "YOUR_PRIVATE_KEY";
const wallet = new ethers.Wallet(privateKey, provider);
// 代币 ABI(简化版)
const tokenAbi = [
"function balanceOf(address owner) view returns (uint256)",
"function transfer(address to, uint256 amount) returns (bool)"
];
const tokenAddress = "0xTokenContractAddressHere";
// 创建合约实例
const tokenContract = new ethers.Contract(tokenAddress, tokenAbi, wallet);
async function checkTokenBalanceAndTransfer() {
const userAddress = "0xYourAddressHere";
const balance = await tokenContract.balanceOf(userAddress);
console.log(`Token balance of ${userAddress}: ${ethers.utils.formatUnits(balance, 18)}`);
// 转代币
const transferAmount = ethers.utils.parseUnits("100", 18);
const tx = await tokenContract.transfer("0xRecipientAddressHere", transferAmount);
console.log("Transfer transaction hash:", tx.hash);
await tx.wait();
console.log("Transfer confirmed!");
}
checkTokenBalanceAndTransfer();
以太坊 JS API 几乎是所有前端 DApps 的基石:
免责声明:本文为转载,非本网原创内容,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
如有疑问请发送邮件至:bangqikeconnect@gmail.com