---
title: "JavaScript API 库"
description: "介绍允许你从应用程序与区块链交互的 JavaScript 客户端库。"
lang: zh
---

为了让 Web 应用程序与以太坊区块链交互（即读取区块链数据和/或向网络发送交易），它必须连接到一个以太坊节点。

为此，每个以太坊客户端都实现了 [JSON-RPC](/developers/docs/apis/json-rpc/) 规范，因此应用程序可以依赖一组统一的[方法](/developers/docs/apis/json-rpc/#json-rpc-methods)。

如果你想使用 JavaScript 连接以太坊节点，可以使用原生 JavaScript，但生态系统中存在几个便利的库，使这变得容易得多。借助这些库，开发者可以编写直观的单行方法来初始化（在底层）与以太坊交互的 JSON-RPC 请求。

请注意，自[合并](/roadmap/merge/)以来，运行一个节点需要两款相互连接的以太坊软件——执行客户端和共识客户端。请确保你的节点同时包含执行客户端和共识客户端。如果你的节点不在本地计算机上（例如，你的节点运行在 AWS 实例上），请相应地更新教程中的 IP 地址。有关更多信息，请参阅我们关于[运行节点](/developers/docs/nodes-and-clients/run-a-node/)的页面。

## 前提条件 {#prerequisites}

除了了解 JavaScript 之外，了解[以太坊技术栈](/developers/docs/ethereum-stack/)和[以太坊客户端](/developers/docs/nodes-and-clients/)也会有所帮助。

## 为什么要使用库？ {#why-use-a-library}

这些库抽象了直接与以太坊节点交互的许多复杂性。它们还提供实用函数（例如，将 ETH 转换为 Gwei），因此作为开发者，你可以花更少的时间处理以太坊客户端的复杂细节，而将更多时间集中在应用程序的独特功能上。

## 库的功能 {#library-features}

### 连接到以太坊节点 {#connect-to-ethereum-nodes}

使用提供者 (provider)，这些库允许你连接到以太坊并读取其数据，无论是通过 JSON-RPC、Infura、Etherscan、Alchemy 还是梅塔马斯克。

> **警告：** Web3.js 已于 2025 年 3 月 4 日归档。[阅读公告](https://blog.chainsafe.io/web3-js-sunset/)。对于新项目，请考虑使用 [Ethers.js](https://ethers.org) 或 [Viem](https://viem.sh) 等替代库。

**Ethers 示例**

```js
// BrowserProvider 包装了一个标准的 Web3 提供者，也就是
// 梅塔马斯克作为 window.ethereum 注入到每个页面的内容
const provider = new ethers.BrowserProvider(window.ethereum)

// 梅塔马斯克插件还允许对交易进行签名，以
// 发送以太币并支付费用以改变区块链内的状态。
// 为此，我们需要账户签名者...
const signer = provider.getSigner()
```

**Web3.js 示例**

```js
var web3 = new Web3("http://localhost:8545")
// 或者
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))

// 更改提供者
web3.setProvider("ws://localhost:8546")
// 或者
web3.setProvider(new Web3.providers.WebsocketProvider("ws://localhost:8546"))

// 在 node.js 中使用 IPC 提供者
var net = require("net")
var web3 = new Web3("/Users/myuser/Library/Ethereum/geth.ipc", net) // mac os 路径
// or
var web3 = new Web3(
  new Web3.providers.IpcProvider("/Users/myuser/Library/Ethereum/geth.ipc", net)
) // mac os 路径
// 在 windows 上路径是："\\\\.\\pipe\\geth.ipc"
// 在 linux 上路径是："/users/myuser/.ethereum/geth.ipc"
```

设置完成后，你将能够查询区块链的：

- 区块号
- Gas 估算
- 智能合约事件
- 网络 ID
- 以及更多……

### 钱包功能 {#wallet-functionality}

这些库为你提供了创建钱包、管理密钥和签署交易的功能。

以下是 Ethers 的一个示例

```js
// 从助记词创建一个钱包实例...
mnemonic =
  "announce room limb pattern dry unit scale effort smooth jazz weasel alcohol"
walletMnemonic = Wallet.fromPhrase(mnemonic)

// ...或者从私钥创建
walletPrivateKey = new Wallet(walletMnemonic.privateKey)

walletMnemonic.address === walletPrivateKey.address
// true

// 根据 Signer API，地址作为一个 Promise 返回
walletMnemonic.getAddress()
// { Promise: '0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1' }

// 钱包地址也可以同步获取
walletMnemonic.address
// '0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1'

// 内部密码学组件
walletMnemonic.privateKey
// '0x1da6847600b0ee25e9ad9a52abbd786dd2502fa4005dd5af9310b7cc7a3b25db'
walletMnemonic.publicKey
// '0x04b9e72dfd423bcf95b3801ac93f4392be5ff22143f9980eb78b3a860c4843bfd04829ae61cdba4b3b1978ac5fc64f5cc2f4350e35a108a9c9a92a81200a60cd64'

// 钱包助记词
walletMnemonic.mnemonic
// {
//   locale: 'en',
//   path: 'm/44\'/60\'/0\'/0/0',
//   phrase: 'announce room limb pattern dry unit scale effort smooth jazz weasel alcohol'
// }

// 注意：使用私钥创建的钱包没有
//       助记词（派生过程阻止了这一点）
walletPrivateKey.mnemonic
// null

// 签名消息
walletMnemonic.signMessage("Hello World")
// { Promise: '0x14280e5885a19f60e536de50097e96e3738c7acae4e9e62d67272d794b8127d31c03d9cd59781d4ee31fb4e1b893bd9b020ec67dfa65cfb51e2bdadbb1de26d91c' }

tx = {
  to: "0x8ba1f109551bD432803012645Ac136ddd64DBA72",
  value: utils.parseEther("1.0"),
}

// 签名交易
walletMnemonic.signTransaction(tx)
// { Promise: '0xf865808080948ba1f109551bd432803012645ac136ddd64dba72880de0b6b3a7640000801ca0918e294306d177ab7bd664f5e141436563854ebe0a3e523b9690b4922bbb52b8a01181612cec9c431c4257a79b8c9f0c980a2c49bb5a0e6ac52949163eeb565dfc' }

// connect 方法返回一个新的
// 连接到提供者的钱包实例
wallet = walletMnemonic.connect(provider)

// 查询网络
wallet.getBalance()
// { Promise: { BigNumber: "42" } }
wallet.getTransactionCount()
// { Promise: 0 }

// 发送以太币
wallet.sendTransaction(tx)
```

[阅读完整文档](https://docs.ethers.io/v5/api/signer/#Wallet)

设置完成后，你将能够：

- 创建账户
- 发送交易
- 签署交易
- 以及更多……

### 与智能合约函数交互 {#interact-with-smart-contract-functions}

JavaScript 客户端库允许你的应用程序通过读取已编译合约的应用程序二进制接口 (ABI) 来调用智能合约函数。

ABI 本质上以 JSON 格式解释了合约的函数，并允许你像使用普通的 JavaScript 对象一样使用它。

因此，以下 Solidity 合约：

```solidity
contract Test {
    uint a;
    address d = 0x12345678901234567890123456789012;

    constructor(uint testInt)  { a = testInt;}

    event Event(uint indexed b, bytes32 c);

    event Event2(uint indexed b, bytes32 c);

    function foo(uint b, bytes32 c) returns(address) {
        Event(b, c);
        return d;
    }
}
```

将产生以下 JSON：

```json
[{
    "type":"constructor",
    "payable":false,
    "stateMutability":"nonpayable"
    "inputs":[{"name":"testInt","type":"uint256"}],
  },{
    "type":"function",
    "name":"foo",
    "constant":false,
    "payable":false,
    "stateMutability":"nonpayable",
    "inputs":[{"name":"b","type":"uint256"}, {"name":"c","type":"bytes32"}],
    "outputs":[{"name":"","type":"address"}]
  },{
    "type":"event",
    "name":"Event",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"}, {"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
  },{
    "type":"event",
    "name":"Event2",
    "inputs":[{"indexed":true,"name":"b","type":"uint256"},{"indexed":false,"name":"c","type":"bytes32"}],
    "anonymous":false
}]
```

这意味着你可以：

- 向智能合约发送交易并执行其方法
- 调用以估算在 EVM 中执行方法所需的 Gas
- 部署合约
- 以及更多……

### 实用函数 {#utility-functions}

实用函数为你提供了便捷的快捷方式，使在以太坊上进行构建变得更加容易。

ETH 的值默认以 Wei 为单位。1 ETH = 1,000,000,000,000,000,000 WEI —— 这意味着你要处理很多数字！`web3.utils.toWei` 会为你将以太币转换为 Wei。

在 Ethers 中，它看起来像这样：

```js
// 获取账户余额（通过地址或 ENS 名称）
balance = await provider.getBalance("ethers.eth")
// { BigNumber: "2337132817842795605" }

// 通常你需要为用户格式化输出
// 他们更喜欢看到以太币的值（而不是 Wei）
ethers.utils.formatEther(balance)
// '2.337132817842795605'
```

- [Web3.js 实用函数](https://docs.web3js.org/api/web3-utils)
- [Ethers 实用函数](https://docs.ethers.org/v6/api/utils/)

## 可用库

**Web3.js -** **_以太坊 JavaScript API。_**

- [文档](https://docs.web3js.org)
- [GitHub](https://github.com/ethereum/web3.js)

**Ethers.js -** **_使用 JavaScript 和 TypeScript 编写的完整以太坊钱包实现和实用工具。_**

- [Ethers.js 首页](https://ethers.org/)
- [文档](https://docs.ethers.io)
- [GitHub](https://github.com/ethers-io/ethers.js)

**The Graph -** **_用于索引以太坊和 IPFS 数据并使用 GraphQL 进行查询的协议。_**

- [The Graph](https://thegraph.com)
- [Graph 浏览器](https://thegraph.com/explorer)
- [文档](https://thegraph.com/docs)
- [GitHub](https://github.com/graphprotocol)
- [Discord](https://thegraph.com/discord)

**Alchemy SDK -** **_具有增强 API 的 Ethers.js 包装器。_**

- [文档](https://www.alchemy.com/docs)
- [GitHub](https://github.com/alchemyplatform/alchemy-sdk-js)

**Viem -** **_以太坊的 TypeScript 接口。_**

- [文档](https://viem.sh)
- [GitHub](https://github.com/wagmi-dev/viem)

**Wagmi -** **_基于 Viem 构建的以太坊 React Hooks 库。_**

- [文档](https://wagmi.sh)
- [GitHub](https://github.com/wevm/wagmi)

**RainbowKit -** **_基于 Wagmi 和 Viem 构建的 React 库，用于为去中心化应用 (dapp) 添加钱包连接功能。_**

- [文档](https://www.rainbowkit.com)
- [GitHub](https://github.com/rainbow-me/rainbowkit)

**Codex -** **_跨数十条链的实时、丰富的区块链数据 API。_**

- [文档](https://docs.codex.io)
- [浏览器](https://docs.codex.io/explore)
- [GitHub](https://github.com/Codex-Data)
- [Discord](https://discord.com/invite/mFpUhT3vAq)

**Drift -** **_内置缓存、Hooks 和测试模拟的 TypeScript 元库。_**

- [文档](https://ryangoree.github.io/drift/)
- [GitHub](https://github.com/ryangoree/drift/)
## 延伸阅读 {#further-reading}

_知道对你有帮助的社区资源吗？编辑本页面并添加它！_

## 相关主题 {#related-topics}

- [节点和客户端](/developers/docs/nodes-and-clients/)
- [开发框架](/developers/docs/frameworks/)

## 相关教程 {#related-tutorials}

- [设置 Web3.js 以在 JavaScript 中使用以太坊区块链](/developers/tutorials/set-up-web3js-to-use-ethereum-in-javascript/) _——在项目中设置 Web3.js 的说明。_
- [从 JavaScript 调用智能合约](/developers/tutorials/calling-a-smart-contract-from-javascript/) _——使用 DAI 代币，了解如何使用 JavaScript 调用合约函数。_
- [使用 Web3 和 Alchemy 发送交易](/developers/tutorials/sending-transactions-using-web3-and-alchemy/) _——从后端发送交易的分步演练。_

## 教程：以太坊上的 JavaScript API 和 WebSocket {#tutorials}

- [使用 WebSocket](/developers/tutorials/using-websockets/) _——如何将 WebSocket 与 Alchemy 结合使用以订阅以太坊事件并发出实时 JSON-RPC 请求。_
