> ## 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.

# 如何使用 getBlock

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

[`getBlock`](https://www.helius.dev/docs/api-reference/rpc/http/getblock) RPC 方法允许您检索 Solana 分账中已确认区块的详细信息。这对于区块浏览器、交易历史分析以及理解特定时间点的链状态至关重要。

<Warning>
  **避免批处理以提高性能**

  批处理归档方法会显著增加延迟。不允许超过10个请求的批处理。
</Warning>

## 常见用例

* **检查区块内容：** 查看特定[区块](https://www.helius.dev/blog/solana-slots-blocks-and-epochs)中包含的所有交易。
* **检索区块哈希：** 获取给定插槽的区块哈希，其父区块哈希及其父插槽。
* **检查区块高度和时间：** 找出区块的高度（其序列号）及其估计的生产时间。
* **分析交易详情：** 使用适当的参数，您可以获取完整的交易数据，包括费用、状态、前/后余额和内部指令等元数据。
* **获取奖励：** 可选择性地包括区块的奖励信息。

## 参数

1. `slot`（数字，必需）：要查询的区块的插槽号（u64）。

2. `config`（对象，可选）：具有以下字段的配置对象：

* `commitment`（字符串，可选）：指定要使用的[承诺级别](https://www.helius.dev/blog/solana-commitment-levels)。不支持 `processed`。默认为 `finalized`。
* `encoding`（字符串，可选）：交易数据的编码。如果 `transactionDetails`是`full`或`accounts`，则默认为 `json`，否则为`base64`。
* `json`：以 JSON 格式返回交易和账户数据（建议使用 `jsonParsed`替代）。
* `jsonParsed`：以解析后的 JSON 返回交易和账户数据。推荐使用此选项，因为它包含所有交易账户密钥（包括来自地址查找表的密钥）。
* `base58`（慢）
* `base64`
* `base64+zstd`
* `transactionDetails`（字符串，可选）：指定返回交易详细程度。默认为 `full`。
* `full`：返回完整的交易详情，包括交易元数据。
* `accounts`：返回每笔交易所涉及的账户列表，但不包括完整的交易数据或元数据。
* `signatures`：仅返回交易签名。
* `none`：不返回交易详情。
* `rewards`（布尔，可选）：是否在响应中包含奖励数组。默认为 `false`。
* `maxSupportedTransactionVersion`（数字，可选）：要返回的最大交易版本。如果区块包含版本更高的交易，则返回错误。如果省略，则仅返回旧版交易，并且如果区块包含任何版本的交易将导致错误。设置为 `0` 以包含使用地址查找表的版本化交易。

## 响应

如果指定的区块已确认且找到，`result` 字段将是一个包含区块信息的对象。如果未找到或未确认区块，`result` 将为 `null`。

区块对象中的关键字段包括：

* `blockhash` （字符串）：此区块的 base-58 编码区块哈希。
* `previousBlockhash` （字符串）：前一区块的 base-58 编码区块哈希。如果父区块不可用（由于账本清理），则可能是系统程序 ID。
* `parentSlot` （数字）：父区块的插槽号。
* `transactions` （数组）：包含在区块中的交易对象数组。这些对象的结构取决于 `encoding` 和 `transactionDetails` 参数。
  * 每个交易对象通常包含 `meta`（如费用、状态、日志、前/后余额）和 `transaction`（实际交易数据，包括消息和签名）。
* `rewards` （数组，可选）：奖励对象数组，如果指定了 `rewards: true` 则存在。每个对象详细描述 `pubkey`, `lamports`, `postBalance`, `rewardType`, 以及可能的 `commission`。
* `blockTime` （数字 | null）：区块的估计生成时间，以 Unix 时间戳表示（自纪元起的秒数），如果不可用则为 `null`。
* `blockHeight` （数字 | null）：此区块的高度（从插槽 0 起源的链中的区块数），如果不可用则为 `null`。

请参阅官方 Solana RPC 文档以获取响应中交易和元对象的完整详细结构。

## 示例：获取区块信息

让我们尝试在 Devnet 上获取一个说明性插槽号的信息。
**重要:** 插槽号处理速度很快。下面使用的插槽号（`250000000`）是一个占位符。运行示例时，应将其替换为在目标网络（例如 Devnet 或 Mainnet）上存在的最新确认插槽。可以使用 Solana 区块浏览器找到最新的插槽号。

\*\*注意：\*\*在下面的示例中，将`YOUR_API_KEY`替换为您实际的Helius API密钥。

<CodeGroup>
  ```bash curl theme={"system"}
  # Replace 250000000 with a valid, recent slot number on Devnet/Mainnet
  curl https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY -X POST -H "Content-Type: application/json" -d \
  '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getBlock",
    "params": [
      250000000, 
      {
        "encoding": "jsonParsed",
        "transactionDetails": "full",
        "rewards": true,
        "maxSupportedTransactionVersion": 0
      }
    ]
  }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  const { Connection } = require('@solana/web3.js');

  async function getBlockDetails() {
    const rpcUrl = 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY'; // Replace YOUR_API_KEY
    const connection = new Connection(rpcUrl, 'confirmed');
    
    // Replace with a valid, recent slot number on your target network
    const slotToQuery = 250000000; 

    try {
      const block = await connection.getBlock(slotToQuery, {
        encoding: "jsonParsed",
        transactionDetails: "full",
        rewards: true,
        maxSupportedTransactionVersion: 0 
      });

      if (block) {
        console.log('Block Details:');
        console.log(`   Slot: ${slotToQuery}`);
        console.log(`   Blockhash: ${block.blockhash}`);
        console.log(`   Previous Blockhash: ${block.previousBlockhash}`);
        console.log(`   Parent Slot: ${block.parentSlot}`);
        console.log(`   Block Height: ${block.blockHeight !== null ? block.blockHeight : 'N/A'}`);
        console.log(`   Block Time: ${block.blockTime ? new Date(block.blockTime * 1000).toISOString() : 'N/A'}`);
        console.log(`   Transactions Count: ${block.transactions.length}`);
        // console.log('   Transactions:', JSON.stringify(block.transactions, null, 2)); // Full transaction details
        // console.log('   Rewards:', JSON.stringify(block.rewards, null, 2)); // Reward details
      } else {
        console.log(`Block at slot ${slotToQuery} not found or not confirmed.`);
      }
    } catch (error) {
      console.error(`Error fetching block ${slotToQuery}:`, error);
    }
  }

  getBlockDetails();
  ```

  ```typescript Kit theme={"system"}
  import { createSolanaRpc } from "@solana/kit";

  const rpc_url = "https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY";
  const rpc = createSolanaRpc(rpc_url);

  const slot_number = BigInt(377261141);

  let block = await rpc
    .getBlock(
      slot_number,
      {
        commitment: "finalized",
        encoding: "json",
        transactionDetails: "full",
        maxSupportedTransactionVersion: 0,
        rewards: false,
      },
    )
    .send();

  console.log("block:", block);
  ```

  ```rust Rust theme={"system"}
  use anyhow::Result;
  use solana_client::nonblocking::rpc_client::RpcClient;
  use solana_sdk::commitment_config::CommitmentConfig;
  use solana_transaction_status_client_types::{TransactionDetails, UiTransactionEncoding};

  #[tokio::main]
  async fn main() -> Result<()> {
      let client = RpcClient::new_with_commitment(
          String::from("https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY"),
          CommitmentConfig::confirmed(),
      );

      let slot_number = 377261141;

      let config = solana_client::rpc_config::RpcBlockConfig {
          encoding: UiTransactionEncoding::Base58.into(),
          transaction_details: TransactionDetails::Full.into(),
          rewards: None,
          commitment: CommitmentConfig::finalized().into(),
          max_supported_transaction_version: Some(0),
      };
      let block = client.get_block_with_config(slot_number, config).await?;

      println!("Block: {:#?}", block);

      Ok(())
  }
  ```
</CodeGroup>

## 开发者提示

* \*\*插槽与区块高度：\*\*请记住，`getBlock`接受一个`slot`数字作为输入，不一定是区块高度。虽然插槽是连续的，但有些可能会被领导者跳过。响应中的`blockHeight`字段表示在此之前的实际区块数量。
* **`maxSupportedTransactionVersion`至关重要：**要查看具有版本化交易的区块（现在是标准并使用地址查找表），您**必须**设置`maxSupportedTransactionVersion: 0`（或是如果出现新标准则为更高版本）。忘记此步骤会导致大多数现代区块出现错误。
* **选择`transactionDetails`:**
  * `full`需要用于大多数详细分析，但返回的数据最多。
  * `signatures`在您只需要列出区块中的交易时很有用。
  * `accounts`可作为中间选择，如果您需要查看涉及哪些账户而不获取所有指令数据。
  * `none`很少使用，但如果您只关心区块级别的元数据，如`blockhash`或`rewards`，则可使用。
* \*\*推荐使用`jsonParsed`进行编码：\*\*请求交易详情时，`jsonParsed`提供最适合开发者的输出，并会正确解析地址查找表中的账户，而`json`（已弃用）则不会。
* \*\*区块不可用：\*\*如果结果为`null`，这意味着在该插槽处未找到区块。这可能是因为插槽被跳过、区块未确认到您指定的`commitment`等级，或者RPC节点从其账本中修剪了该历史区块（这在旧插槽中很常见）。
* \*\*奖励信息：\*\*设置`rewards: true`是查看分配给验证者的区块奖励（以及潜在的股权持有人，具体取决于奖励类型）分配所必需的。这会增加响应的大小。
* \*\*理解区块结构：\*\*要更深入理解区块在Solana架构中的适应方式，请参阅[理解Solana中的插槽、区块和纪元](https://www.helius.dev/blog/solana-slots-blocks-and-epochs)。
