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

# 如何使用 getSignaturesForAddress

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

[`getSignaturesForAddress`](https://www.helius.dev/docs/api-reference/rpc/http/getsignaturesforaddress) RPC 方法允许您检索涉及特定账户地址的已确认交易签名列表。这对于获取账户的交易历史非常有用。签名按时间倒序返回（最新的在前）。

<Tip>
  对于高级过滤、排序和代币账户历史，请使用 [`getTransactionsForAddress`](/docs/zh/rpc/gettransactionsforaddress)。请注意，`getSignaturesForAddress` 不包含涉及关联代币账户的交易。
</Tip>

## 常见用例

* **账户交易历史：** 显示用户钱包的过去交易。对于更高级的交易历史解析，考虑使用 Helius 的 [增强交易 API](https://www.helius.dev/docs/enhanced-transactions)。
* **活动审计：** 审查与特定智能合约或账户相关的所有交易。
* **特定交易查找：** 如果只知道相关地址，通过遍历账户历史查找特定交易。
* **数据索引：** 构建本地化的交易索引以加快查询和分析。

## 请求参数

1. **`address`** (`string`): （必需）要检索交易签名的账户的 base-58 编码公钥。
2. **`options`** (`object`, 可选): 包含以下字段的可选配置对象：
   * **`limit`** (`number`, 可选): 要返回的最大签名数。默认值为 1000，最大允许值为 1000。
   * **`before`** (`string`, 可选): 一个 base-58 编码的交易签名。如果提供，查询将从此签名之前的交易开始。
   * **`until`** (`string`, 可选): 一个 base-58 编码的交易签名。如果提供，查询将在该签名达到之前搜索交易（不包括该签名）。
   * **`commitment`** (`string`, 可选): 指定查询使用的[承诺级别](https://www.helius.dev/blog/solana-commitment-levels)。支持的值为 `finalized` 或 `confirmed`。不支持 `processed` 承诺。如果省略，则使用 RPC 节点的默认承诺（通常为 `finalized`）。
   * **`minContextSlot`** (`number`, 可选): 请求可以被评估的最小 slot。这不是对历史交易的过滤，而是为节点的上下文设置最小 slot。

<Warning>
  **不支持批处理**

  此归档方法不支持批处理。仅进行单独请求。
</Warning>

## 响应结构

JSON-RPC 响应中的 `result` 字段是一个签名信息对象数组。每个对象的结构如下：

* **`signature`** (`string`): base-58 编码的交易签名。
* **`slot`** (`u64`): 处理交易的槽位。
* **`err`** (`object` | `null`): 如果交易失败则为错误对象，成功则为 `null`。
* **`memo`** (`string` | `null`): 交易相关的备忘录（如果有）。
* **`blockTime`** (`i64` | `null`): 包含交易的块的估计生成时间，Unix 时间戳格式（自纪元以来的秒数）。如果不可用则为 `null`。
* **`confirmationStatus`** (`string` | `null`): 交易的确认状态（例如，`processed`, `confirmed`, `finalized`）。如果不可用（例如，对于旧的 Helius 响应）则为 `null`。

## 示例

### 1. 获取地址的最新签名

此示例获取给定地址的最近（最多 1000 个）交易签名。

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

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

  async function getLatestSignatures() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    // Replace with the public key you want to query
    const address = new PublicKey('11111111111111111111111111111111'); 

    try {
      const signatures = await connection.getSignaturesForAddress(address);
      if (signatures && signatures.length > 0) {
        console.log(`Found ${signatures.length} signatures:`);
        signatures.forEach((sigInfo, index) => {
          console.log(`--- Signature ${index + 1} ---`);
          console.log(`  Signature: ${sigInfo.signature}`);
          console.log(`  Slot: ${sigInfo.slot}`);
          console.log(`  Block Time: ${sigInfo.blockTime ? new Date(sigInfo.blockTime * 1000).toLocaleString() : 'N/A'}`);
          console.log(`  Error: ${JSON.stringify(sigInfo.err)}`);
          console.log(`  Memo: ${sigInfo.memo || 'N/A'}`);
          console.log(`  Confirmation Status: ${sigInfo.confirmationStatus || 'N/A'}`);
        });
      } else {
        console.log('No signatures found for this address.');
      }
    } catch (error) {
      console.error('Error fetching signatures:', error);
    }
  }

  getLatestSignatures();
  ```
</CodeGroup>

### 2. 获取有限制的签名

此示例获取指定数量的地址的最近交易签名。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  # Replace TARGET_ACCOUNT_ADDRESS with the address you want to query
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getSignaturesForAddress",
      "params": [
        "TARGET_ACCOUNT_ADDRESS",
        {
          "limit": 5 
        }
      ]
    }'
  ```

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

  async function getLimitedSignatures() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    // Replace with the public key you want to query
    const address = new PublicKey('Vote111111111111111111111111111111111111111'); 
    const limit = 5;

    try {
      const signatures = await connection.getSignaturesForAddress(address, { limit });
      console.log(`Fetched up to ${limit} signatures:`);
      signatures.forEach((sigInfo, index) => {
        console.log(`${index + 1}. Signature: ${sigInfo.signature}, Slot: ${sigInfo.slot}`);
      });
    } catch (error) {
      console.error(`Error fetching limited signatures for ${address.toBase58()}:`, error);
    }
  }

  getLimitedSignatures();
  ```
</CodeGroup>

### 3. 分页获取交易历史

此示例演示如何使用 `before` 参数批量获取交易历史。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Initial request (get the latest 2)
  # Replace <api-key> with your Helius API key
  # Replace TARGET_ACCOUNT_ADDRESS with the address you want to query
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getSignaturesForAddress",
      "params": [
        "TARGET_ACCOUNT_ADDRESS",
        { "limit": 2 }
      ]
    }'

  # Suppose the last signature from the above response was LAST_SIGNATURE_FROM_PREVIOUS_BATCH
  # Fetch the next 2 transactions before that one
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getSignaturesForAddress",
      "params": [
        "TARGET_ACCOUNT_ADDRESS",
        { 
          "limit": 2,
          "before": "LAST_SIGNATURE_FROM_PREVIOUS_BATCH" 
        }
      ]
    }'
  ```

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

  async function paginateSignatures() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    // Replace with the public key you want to query - e.g. a known active address
    const address = new PublicKey('Vote111111111111111111111111111111111111111'); 
    const batchSize = 2;
    let lastSignature = null;
    let allSignatures = [];
    const maxPages = 3; // Limit how many pages we fetch for this example

    try {
      for (let i = 0; i < maxPages; i++) {
        console.log(`Fetching page ${i + 1}...`);
        const options = { limit: batchSize };
        if (lastSignature) {
          options.before = lastSignature;
        }

        const signatures = await connection.getSignaturesForAddress(address, options);
        
        if (signatures.length === 0) {
          console.log('No more signatures found.');
          break;
        }

        signatures.forEach(sigInfo => {
          allSignatures.push(sigInfo.signature);
          console.log(`  Found: ${sigInfo.signature} in slot ${sigInfo.slot}`);
        });
        
        lastSignature = signatures[signatures.length - 1]?.signature;

        if (signatures.length < batchSize || !lastSignature) {
           console.log('Fetched all available signatures or reached end of page.');
           break;
        }
        // Optional: Add a small delay if making many sequential requests
        // await new Promise(resolve => setTimeout(resolve, 200)); 
      }
      console.log(`
  Total signatures fetched (${allSignatures.length}):`);
      allSignatures.forEach((sig, idx) => console.log(`${idx + 1}. ${sig}`));

    } catch (error) {
      console.error('Error paginating signatures:', error);
    }
  }

  paginateSignatures();
  ```
</CodeGroup>

## 开发者提示

* **分页:** 要获取活跃账户的完整交易历史，您可能需要进行多次请求，使用上一个批次中收到的最后签名和一个 `limit`。
* **速率限制:** 在获取大量交易历史时，请注意 RPC 节点的速率限制。
* **顺序:** 签名总是从最新返回到最旧。
* **`limit` 参数：** `limit` 参数可以在 1 到 1000 之间。如果未指定，默认值为 1000。
* **`until` 参数：** 此参数可用于在达到已知较旧的签名时停止获取签名，如果您只需要获取到某个时间点的交易，这非常有用。
* **`minContextSlot`:** 此参数不过滤历史交易。它指定 RPC 节点在评估请求时应该使用的最小槽位上下文。如果节点的状态早于此槽位，可能返回错误。
* **交易详情:** 此方法只返回签名和基本信息。要获取完整的交易详情，您需要使用每个签名调用 `getTransaction` 方法。
* **代币账户限制:** 此方法仅返回直接引用提供地址的交易。不包括地址拥有的代币账户相关交易。要获取完整的代币历史，包括关联的代币账户，请使用 [`getTransactionsForAddress`](/docs/zh/rpc/gettransactionsforaddress) 结合 `tokenAccounts` 过滤器。

通过使用 `getSignaturesForAddress` 及其分页选项，您可以有效地检索和管理任何 Solana 地址的交易历史。

## 相关方法

<CardGroup cols={2}>
  <Card title="getTransactionsForAddress" href="/docs/zh/rpc/gettransactionsforaddress">
    高级过滤、排序和代币账户历史
  </Card>

  <Card title="getTransaction" href="/docs/zh/api-reference/rpc/http/gettransaction">
    从签名获取完整的交易详情
  </Card>
</CardGroup>
