> ## 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 + getTransaction 迁移到 getTransactionsForAddress

> 将 getSignaturesForAddress + getTransaction 循环替换为单个 getTransactionsForAddress 调用。包括参数映射、前后代码、分页更改，以及一个自动化迁移的复制粘贴 AI 代理提示。

## 为什么迁移？

在 Solana 上获取地址的交易历史的标准方法需要两个步骤：调用 `getSignaturesForAddress` 列出签名，然后每个签名调用 `getTransaction` 获取详细信息。对于 1,000 笔交易，需要 1,001 个 HTTP 请求。

[`getTransactionsForAddress`](/docs/zh/rpc/gettransactionsforaddress) 是 Helius 专属的 RPC 方法，将这两步合并为一个调用。每次请求最多返回 1,000 笔完整交易，具有标准方法不具备的过滤、双向排序和代币账户支持。

|                | `getSignaturesForAddress` + `getTransaction` | `getTransactionsForAddress`   |
| -------------- | -------------------------------------------- | ----------------------------- |
| 1,000 笔交易的请求次数 | 1,001                                        | 1                             |
| 1,000 笔完整交易的信用 | \~1,001 （每次调用 1 个信用）                         | 100 （每 100 笔交易 10 个信用）        |
| 关联代币账户（ATA）历史  | 不包括                                          | 通过 `filters.tokenAccounts` 包括 |
| 时间和槽范围过滤器      | 没有                                           | 有                             |
| 状态过滤（成功/失败）    | 没有                                           | 有                             |
| 排序顺序           | 仅最新优先                                        | 最新或最旧优先                       |
| 分页             | `before`/`until` 签名                          | `paginationToken`             |

结果：大约减少 10 倍的信用，减少 1,000 倍的往返次数，并且对于 `getTransaction` 的分散没有客户端批处理、速率限制处理或重试逻辑。

## 前后对比

以下是在两种模式下执行相同的任务 —— 获取地址的最后 1,000 笔交易的完整详细信息：

<CodeGroup>
  ```javascript Before (two methods) theme={"system"}
  const rpcUrl = 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY';

  // Step 1: Get signatures (1 request)
  const sigResponse = await fetch(rpcUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'getSignaturesForAddress',
      params: ['YOUR_ADDRESS_HERE', { limit: 1000 }]
    })
  });
  const { result: signatures } = await sigResponse.json();

  // Step 2: Get transaction details (1,000 additional requests)
  const transactions = await Promise.all(
    signatures.map(async (sig) => {
      const txResponse = await fetch(rpcUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: 1,
          method: 'getTransaction',
          params: [sig.signature, { maxSupportedTransactionVersion: 0 }]
        })
      });
      const { result } = await txResponse.json();
      return result;
    })
  );
  ```

  ```javascript After (one method) theme={"system"}
  const response = await fetch('https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'getTransactionsForAddress',
      params: [
        'YOUR_ADDRESS_HERE',
        {
          transactionDetails: 'full',
          maxSupportedTransactionVersion: 0,
          limit: 1000
        }
      ]
    })
  });

  const { result } = await response.json();
  const transactions = result.data; // Full transactions, same shape as getTransaction
  ```
</CodeGroup>

`getTransactionsForAddress` 不属于标准 Solana RPC，因此 `@solana/web3.js` 没有 `Connection` 的辅助工具。按上述示例通过原始 JSON-RPC 请求调用它 —— 它在与您其他 RPC 流量相同的 Helius 端点上运行。

## 参数映射

旧的两步流程中的每个选项都有直接对应的等效项。大多数名称保持不变 —— 只有分页方式不同。

### 来源自 getSignaturesForAddress

| 旧选项              | 新等效项                                                       |
| ---------------- | ---------------------------------------------------------- |
| `limit`          | `limit` — 相同的最大值为 1,000                                    |
| `before`         | `paginationToken` 来自上一个响应                                  |
| `until`          | `filters.signature.gt`                                     |
| `commitment`     | `commitment` — 仅 `confirmed` 或 `finalized`；不支持 `processed` |
| `minContextSlot` | `minContextSlot` — 不变                                      |

### 来源自 getTransaction

| 旧选项                              | 新等效项                                               |
| -------------------------------- | -------------------------------------------------- |
| `encoding`                       | `encoding` — 当 `transactionDetails` 是 `"full"` 时适用 |
| `maxSupportedTransactionVersion` | `maxSupportedTransactionVersion` — 不变              |
| `commitment`                     | `commitment` — 同上规则                                |

两个功能完全没有旧等效项：

* `filters` — 用 `blockTime`、`slot`、`status`、`tokenTransfer` 或 `tokenAccounts` 服务器端细分结果，而不是在代码中获取所有内容并过滤。
* `sortOrder: "asc"` — 按时间顺序（最旧的优先）的结果，标准方法无法在不获取整个历史记录并反转的情况下返回。

## 迁移步骤

<Steps>
  <Step title="确认您在 Helius 端点上">
    `getTransactionsForAddress` 是 Helius 专属。它可以在 `https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY`（和 devnet）上工作 —— 如果您是 Helius 客户，现有调用的端点已使用。所以不需要更改 API 密钥或计划。
  </Step>

  <Step title="将两步获取替换为一次调用">
    删除 `getSignaturesForAddress` 调用和 `getTransaction` 循环。使用 `transactionDetails: "full"` 进行单个 `getTransactionsForAddress` 请求，同时继承您的 `encoding`、`maxSupportedTransactionVersion` 和 `commitment` 值，如 [参数映射](#参数映射) 中所示。

    如果您只需要签名（例如，用于现有管道），请改用 `transactionDetails: "signatures"` —— 每次调用费用为 10 个信用。
  </Step>

  <Step title="更新响应处理">
    响应封套有三个变化：

    * 结果存在于 `result.data`（一个数组）中，而不是直接存在于 `result` 中。
    * 每个完整模式条目是 `{ slot, transactionIndex, blockTime, transaction, meta }`。`transaction` 和 `meta` 对象在形状上与 `getTransaction` 返回的结果相同，因此您的解析代码可以不变。
    * 签名模式条目匹配 `getSignaturesForAddress` 输出（`signature`，`slot`，`err`，`memo`，`blockTime`，`confirmationStatus`）加上一个新的 `transactionIndex` 字段。

    需要注意的行为差异：使用旧模式时，`getTransaction` 调用可能会为一个签名返回 `null`。使用 `getTransactionsForAddress` 时，每个 `result.data` 条目都是一个完整的交易 —— 请删除任何用于处理缺失详细信息的空值处理。
  </Step>

  <Step title="替换基于签名的分页">
    将 `before` 游标循环替换为 `paginationToken`：

    ```javascript theme={"system"}
    let paginationToken = null;
    const allTransactions = [];

    do {
      const response = await fetch('https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: 1,
          method: 'getTransactionsForAddress',
          params: [
            'YOUR_ADDRESS_HERE',
            {
              transactionDetails: 'full',
              maxSupportedTransactionVersion: 0,
              limit: 1000,
              ...(paginationToken && { paginationToken })
            }
          ]
        })
      });

      const { result } = await response.json();
      allTransactions.push(...result.data);
      paginationToken = result.paginationToken;
    } while (paginationToken);
    ```

    循环在 `paginationToken` 是 `null` 时结束 —— 不再需要比较签名列表或自行跟踪最后一个签名。

    如果您使用 `until` 停止在已知的签名处，则将其替换为 `filters.signature: { gt: "KNOWN_SIGNATURE" }`。如果您用于在某个时间点停止，`filters.blockTime` 或 `filters.slot` 通常更适合。
  </Step>

  <Step title="可选：启用完整的代币历史">
    除非您还调用 `getTokenAccountsByOwner` 并获取每个代币账户的签名，否则旧模式会错过关联代币账户（ATA）活动。要包括它，请添加一个过滤器：

    ```json theme={"system"}
    {
      "filters": {
        "tokenAccounts": "balanceChanged"
      }
    }
    ```

    `balanceChanged` 返回引用钱包或更改其拥有的任何代币账户余额的交易，过滤掉垃圾邮件。请参阅 [关联代币账户](/docs/zh/rpc/gettransactionsforaddress#关联代币账户) 以获取 `none`/`balanceChanged`/`all` 选项和 2022 年前的注意事项。
  </Step>

  <Step title="验证旧输出">
    对于示例地址，通过两种方式获取历史记录并比较签名集。在 `filters.tokenAccounts` 未设置（默认 `none`）的情况下，`getTransactionsForAddress` 返回与同一范围的 `getSignaturesForAddress` 相同的交易。然后部署并移除旧代码路径。
  </Step>
</Steps>

## 行为差异审查

大多数迁移是直接替换，但在发布前检查以下内容：

* **承诺。** 不支持 `processed`；使用 `confirmed` 或 `finalized`。如果您的旧代码轮询 `processed` 的最近历史，请切换到 `confirmed`。
* **计量。** 完整交易响应每 100 笔交易返回的费用为 10 个信用（最低 10 个信用）；仅签名的响应每次调用固定花费 10 个信用。旧模式每次调用费用为 1 个信用 —— 每次请求便宜，但每笔交易获取的费用大大增加。失败的响应是免费的。请参阅 [计量](/docs/zh/rpc/gettransactionsforaddress#计量)。
* **网络支持。** 主网具有无限保留。Devnet 支持两周的保留。Testnet 不支持。
* **保留地址。** 一小部分系统地址（投票程序、系统程序、sysvars）路由到备份归档路径或返回为空。如果您索引这些，请审查 [限制和边界情况](/docs/zh/rpc/gettransactionsforaddress#限制和边缘情况)。
* **多个地址。** 像旧流程一样，一次请求涵盖一个地址。并行查询地址并合并；请参阅 [多个地址](/docs/zh/rpc/gettransactionsforaddress#多个地址)。

## 常见问题

### getTransactionsForAddress 是标准的 Solana RPC 方法吗？

不是。它是 Helius 专属方法，仅在 Helius RPC 端点上提供。标准 Solana RPC 和其他提供者只提供 `getSignaturesForAddress` 和 `getTransaction`。您的其他 RPC 调用不受影响 —— 此方法与完整的标准 RPC 界面一起存在于同一端点上。

### 迁移后我还需要 getTransaction 吗？

仅用于您已经拥有签名且没有地址上下文的一次性查找，例如验证用户粘贴的特定交易。对于任何基于地址的历史记录 —— 回填、索引、钱包活动提要 —— `getTransactionsForAddress` 替代这两种方法。

### 它能与 @solana/web3.js 一起使用吗？

该方法不在 `Connection` 类中，但可以通过任何 HTTP 客户端对您的 Helius RPC URL 进行调用。使用 `fetch`（或您语言的等效工具）按上述示例使用标准 JSON-RPC 主体。您可以继续将 `Connection` 用于其他操作。

### 它会返回与 getSignaturesForAddress 相同的交易吗？

是的。使用默认设置（`filters.tokenAccounts: "none"`），它返回引用查询地址的交易 —— 与 `getSignaturesForAddress` 返回的集合相同。将 `tokenAccounts` 设置为 `balanceChanged` 或 `all` 返回更多：它添加了钱包的关联代币账户的活动，这是标准方法无法看到的。

### 它的费用与旧模式相比如何？

使用 `getTransactionsForAddress` 获取 1,000 笔完整交易的费用为 100 个信用，而使用 `getSignaturesForAddress` + `getTransaction` 的费用约为 1,001 个信用（和 1,001 个请求）。仅签名的响应每次调用固定费用 10 个信用。请参阅 [Helius 费用](/docs/zh/billing/credits) 获取完整定价。

## 让 AI 代理执行迁移

如果您使用 Claude Code、Cursor 或其他编码代理，请将下面的提示粘贴到代码库的代理会话中。它会在您的代码库中找到旧模式并重写。

````markdown theme={"system"}
Migrate this codebase from the two-step Solana transaction history pattern
(getSignaturesForAddress followed by getTransaction) to the single Helius RPC
method getTransactionsForAddress.

## Background

getTransactionsForAddress is a Helius-exclusive JSON-RPC method served on
standard Helius RPC endpoints (https://mainnet.helius-rpc.com/?api-key=...).
It returns up to 1,000 full transactions per call, replacing one
getSignaturesForAddress call plus one getTransaction call per signature.
Docs: https://www.helius.dev/docs/rpc/gettransactionsforaddress.md

## Step 1: Find the old pattern

Search for:
- getSignaturesForAddress calls (via @solana/web3.js Connection, raw JSON-RPC,
  or another SDK) whose signatures are then passed to getTransaction /
  getParsedTransaction / getTransactions
- Pagination loops using `before` or `until` signature cursors
- getTokenAccountsByOwner calls used only to fetch per-token-account signature
  history

Leave standalone getTransaction calls (single-signature lookups with no
address context) unchanged.

## Step 2: Rewrite each call site

Replace the two-step flow with one raw JSON-RPC request (web3.js has no
Connection helper for this method):

```javascript
const response = await fetch(HELIUS_RPC_URL, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'getTransactionsForAddress',
    params: [
      address, // base-58 string
      {
        transactionDetails: 'full',       // or 'signatures' if only signatures were used
        maxSupportedTransactionVersion: 0, // carry over from the old getTransaction options
        encoding: 'json',                  // carry over ('json', 'jsonParsed', 'base64', 'base58')
        limit: 1000,                       // up to 1,000
        // paginationToken: '...',         // from the previous response, for page 2+
        // sortOrder: 'desc',              // 'desc' (default, newest first) or 'asc'
        // filters: { ... }                // optional, see mapping below
      }
    ]
  })
});
const { result } = await response.json();
// result.data      -> array of transactions
// result.paginationToken -> string cursor, or null when done
```

Parameter mapping:
- limit -> limit
- before: <sig> -> paginationToken (preferred) or filters: { signature: { lt: <sig> } }
- until: <sig>  -> filters: { signature: { gt: <sig> } }
- commitment -> commitment ('confirmed' or 'finalized' only; if the old code
  used 'processed', use 'confirmed')
- minContextSlot -> minContextSlot
- encoding / maxSupportedTransactionVersion (from getTransaction) -> same names,
  top level of the config object

Response shape:
- Full mode: each entry is { slot, transactionIndex, blockTime, transaction, meta }.
  transaction and meta are identical in shape to getTransaction results, so
  existing parsing code carries over. Entries are never null - remove
  null-handling that existed for missing getTransaction results.
- Signatures mode: entries match getSignaturesForAddress output
  ({ signature, slot, err, memo, blockTime, confirmationStatus }) plus
  transactionIndex.

Pagination: loop while result.paginationToken is non-null, passing it back as
paginationToken. Remove manual last-signature tracking.

If the old code fetched signatures for the wallet's token accounts too
(getTokenAccountsByOwner + per-account getSignaturesForAddress), replace all
of it with one call using filters: { tokenAccounts: 'balanceChanged' } and
delete the merge/dedupe logic.

## Step 3: Constraints and cleanup

- The endpoint must be a Helius RPC URL; other providers do not serve this
  method. Do not change endpoints for other RPC calls.
- Remove now-unused batching, throttling, and retry helpers that existed only
  for the getTransaction fan-out.
- One request covers one address; keep parallel queries for multi-address code.
- Preserve the surrounding code style and error handling conventions.

## Step 4: Verify

- Run the project's type checks and tests.
- Do NOT make any RPC calls yourself. Instead, write a standalone script (e.g.
  scripts/verify-gtfa-migration.mjs) that fetches history for one address both
  ways - the old getSignaturesForAddress + getTransaction flow and the new
  getTransactionsForAddress call with default filters - and prints whether the
  signature sets match, listing any differences. Read the RPC URL from an
  environment variable and the address from a CLI argument; never hardcode an
  API key.
- Tell the user how to run it, for example:
  HELIUS_RPC_URL="https://mainnet.helius-rpc.com/?api-key=..." \
    node scripts/verify-gtfa-migration.mjs <address>
- Summarize every call site changed and flag any you were unsure about.
````

该提示是自包含的 —— 代理不需要访问此页面。有关针对代理准备的文档、MCP 搜索和技能，请参阅 [Helius for AI agents](/docs/zh/agents/overview)。

## 后续步骤

<CardGroup cols={2}>
  <Card title="getTransactionsForAddress 指南" icon="clock-rotate-left" href="/docs/zh/rpc/gettransactionsforaddress">
    全面教程，涵盖过滤器、排序、分页和代币账户。
  </Card>

  <Card title="API 参考" icon="code" href="/docs/zh/api-reference/rpc/http/gettransactionsforaddress">
    完整的请求和响应模式。
  </Card>

  <Card title="索引指南" icon="layer-group" href="/docs/zh/rpc/how-to-index-solana-data">
    使用 getTransactionsForAddress 进行回填和同步 Solana 索引。
  </Card>

  <Card title="历史数据概览" icon="database" href="/docs/zh/rpc/historical-data">
    比较所有 Solana 历史数据方法。
  </Card>
</CardGroup>
