> ## Documentation Index
> Fetch the complete documentation index at: https://www.helius.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何使用 getLatestBlockhash

> 了解 getLatestBlockhash 的使用案例、代码示例、请求参数、响应结构和提示。

[RPC 方法](https://www.helius.dev/docs/api-reference/rpc/http/getlatestblockhash) 对于在 Solana 网络上准备和发送交易至关重要。它检索节点处理的最新 blockhash，以及该 blockhash 保持有效的最后区块高度。有关如何有效使用 blockhash 并确保你的[交易着陆](https://www.helius.dev/blog/how-to-land-transactions-on-solana)的更多详细信息，请参考我们的综合指南。

在 Solana 上的每笔交易都必须引用一个最近的 blockhash。此机制有助于防止某些类型的攻击，例如在分叉链上的交易重放。

\*\*版本说明：\*\*此方法在 `solana-core` v1.9 或更新版本中可用。对于运行 `solana-core` v1.8 或更早版本的节点，请改用 `getRecentBlockhash` 方法。

## 常见用例

* **交易构建：** 在签名并发送新交易之前，获取最近的 blockhash 以包含在其中。
* **交易生命周期管理：** 使用 `lastValidBlockHeight` 来了解引用获取的 blockhash 的交易预计能保留多长时间。
* **预检：** 尽管 `simulateTransaction` 可以隐式执行此操作，应用程序可能会获取 blockhash 以手动准备模拟交易。

## 请求参数

此方法可以选择性地接受一个包含以下参数的配置对象：

* **`commitment`** (字符串，可选)：指定查询的[承诺级别](https://www.helius.dev/blog/solana-commitment-levels)。如果省略，则使用节点的默认承诺。对于交易，通常使用 `confirmed` 或 `finalized` 以确保 blockhash 来自链的相对稳定部分。
* **`minContextSlot`** (整数，可选)：请求可在其上评估的最小槽位。这确保查询针对至少处理到该槽位的账本状态进行。

## 响应结构

JSON-RPC 响应的 `result` 字段将是一个 `RpcResponse` 对象。该对象内的 `value` 字段包含：

* **`blockhash`** (string)：一个经过 base-58 编码的字符串，代表最新的区块哈希。
* **`lastValidBlockHeight`** (u64)：该区块哈希将过期的区块高度。在网络达到此区块高度之前，引用此区块哈希的交易是有效的。

响应还包括一个带有信息检索时的 `context` 对象。

## 示例

### 1. 使用默认承诺获取最新区块哈希

此示例使用节点的默认承诺获取最新的区块哈希。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getLatestBlockhash"
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  // Replace <api-key> with your Helius API key
  const { Connection } = require('@solana/web3.js');

  async function fetchLatestBlockhash() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
      console.log('Latest Blockhash Info:');
      console.log(`  Blockhash: ${blockhash}`);
      console.log(`  Last Valid Block Height: ${lastValidBlockHeight}`);
      // This blockhash can now be used in a transaction
    } catch (error) {
      console.error('Error fetching latest blockhash:', error);
    }
  }

  fetchLatestBlockhash();
  ```
</CodeGroup>

### 2. 使用 'confirmed' 承诺获取最新区块哈希

此示例明确请求具有 `confirmed` 承诺的最新区块哈希。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getLatestBlockhash",
      "params": [{ "commitment": "confirmed" }]
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  // Replace <api-key> with your Helius API key
  const { Connection } = require('@solana/web3.js');

  async function fetchConfirmedBlockhash() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
      console.log('Confirmed Blockhash Info:');
      console.log(`  Blockhash: ${blockhash}`);
      console.log(`  Last Valid Block Height: ${lastValidBlockHeight}`);
    } catch (error) {
      console.error('Error fetching confirmed blockhash:', error);
    }
  }

  fetchConfirmedBlockhash();
  ```
</CodeGroup>

## 开发者提示

* **区块哈希有效性：** 区块哈希在有限的时间内有效，约为 2 分钟（但这可能有所不同）。交易必须在其区块高度过期之前由网络确认。如果自上次获取区块哈希以来已经过了相当长的时间，始终获取新的区块哈希。
* **选择承诺：** 对于关键交易，使用 `finalized` 承诺提供了最强的保证，确保区块哈希来自主链分叉，但可能会稍微旧一些。`confirmed` 提供了良好的平衡。了解更多关于[承诺级别](https://www.helius.dev/blog/solana-commitment-levels)的详细信息。
* **交易费用：** 请记住同时计算并包含适当的交易费用。区块哈希本身并不决定费用。
* **重试逻辑：** 如果交易因过了其区块高度而过期，则必须使用新的、更近的区块哈希重新签名并重新提交。

本指南提供了有效使用 `getLatestBlockhash` 的步骤，这是通过交易与 Solana 网络互动的基石。

## 相关方法

<CardGroup cols={2}>
  <Card title="simulateTransaction" href="/docs/zh/api-reference/rpc/http/simulatetransaction">
    在发送前模拟交易
  </Card>

  <Card title="isBlockhashValid" href="/docs/zh/api-reference/rpc/http/isblockhashvalid">
    检查区块哈希是否仍然有效
  </Card>
</CardGroup>
