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

# getProgramAccountsV2

> getProgramAccounts 的增强版本，支持基于游标的分页和 changedSinceSlot，用于高效查询由特定 Solana 程序拥有的大量账户，并进行增量更新。

## 概述

`getProgramAccountsV2` 是标准 `getProgramAccounts` 方法的增强版本，专为需要有效查询特定Solana程序拥有的大量账户集的应用程序而设计。此方法引入了基于光标的分页和增量更新功能。

<Info>
  **V2 中的新功能：**

  * **基于游标的分页**：配置请求上限为每次1到10,000个账户
  * **增量更新**：使用 `changedSinceSlot` 仅获取最近修改的账户
  * **更好的性能**：防止超时，并减少大数据集的内存使用
  * **向后兼容**：支持所有现有的 `getProgramAccounts` 参数
  * **可选的 `withContext`**：`true` 在 `result.context` 下添加 `slot` 和 `apiVersion`；省略或 `false` 则不包含
</Info>

## 主要优势

<CardGroup cols={2}>
  <Card title="可扩展查询" icon="chart-line">
    通过有效分页处理拥有数百万个账户的程序
  </Card>

  <Card title="实时同步" icon="arrows-rotate">
    使用 `changedSinceSlot` 进行增量更新和实时数据同步
  </Card>

  <Card title="防止超时" icon="clock">
    以前超时的大型查询现在通过分页可靠运行
  </Card>

  <Card title="内存高效" icon="microchip">
    分块处理数据而不是一次性加载所有内容到内存
  </Card>
</CardGroup>

## 分页最佳实践

<Warning>
  **重要的分页行为**：分页结束仅在**没有返回账户**时指示。由于过滤，API返回的账户可能少于限制 - 始终继续分页，直到 `paginationKey` 是 `null`。
</Warning>

### 基本分页模式

```typescript theme={"system"}
let allAccounts = [];
let paginationKey = null;

do {
  const response = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: '1',
      method: 'getProgramAccountsV2',
      params: [
        "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
        {
          encoding: 'base64',
          filters: [{ dataSize: 165 }],
          limit: 5000,
          ...(paginationKey && { paginationKey })
        }
      ]
    })
  });
  
  const data = await response.json();
  allAccounts.push(...data.result.accounts);
  paginationKey = data.result.paginationKey;
} while (paginationKey);
```

### 增量更新

```typescript theme={"system"}
// Get only accounts modified since slot 150000000
const incrementalUpdate = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: '1',
    method: 'getProgramAccountsV2',
    params: [
      programId,
      {
        encoding: 'jsonParsed',
        limit: 1000,
        changedSinceSlot: 150000000
      }
    ]
  })
});
```

## 性能提示

<Tip>
  **最佳限制大小**：对于大多数用例，每次请求 1,000-5,000 个账户的限制提供了性能和可靠性的最佳平衡。
</Tip>

* **从较小的限制开始**（1000），并根据网络性能增加
* **使用合适的编码**：便捷使用 `jsonParsed`，性能使用 `base64`
* **应用过滤器**在分页前减少数据集大小
* **存储 `paginationKey`** 以便查询中断时恢复
* **监控响应时间**并相应调整限制

## `withContext`（可选）

布尔值在程序配置对象（`params[1]`）上。只有 `result` 的形状发生变化，不改变过滤器、限制或分页。

```json theme={"system"}
// Omitted or false
{ "jsonrpc": "2.0", "id": "1", "result": { "accounts": [], "paginationKey": null } }

// true — snapshot metadata plus page under `result.value`
{ "jsonrpc": "2.0", "id": "1", "result": {
  "context": { "slot": 411895550, "apiVersion": "3.1.9" },
  "value": { "accounts": [], "paginationKey": null }
}}
```

## 从 getProgramAccounts 迁移

从原方法迁移非常简单 - 只需替换方法名称并添加分页参数：

```diff theme={"system"}
{
  "jsonrpc": "2.0",
  "id": "1",
- "method": "getProgramAccounts",
+ "method": "getProgramAccountsV2",
  "params": [
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
    {
      "encoding": "base64",
      "filters": [{ "dataSize": 165 }],
+     "limit": 5000
    }
  ]
}
```

## 相关方法

<CardGroup cols={2}>
  <Card title="getProgramAccounts" icon="code" href="/zh/api-reference/rpc/http/getprogramaccounts">
    无分页的原始方法
  </Card>

  <Card title="getTokenAccountsByOwnerV2" icon="wallet" href="/zh/api-reference/rpc/http/gettokenaccountsbyownerv2">
    用于令牌账户查询的 V2 方法
  </Card>
</CardGroup>

## 请求参数

<ParamField body="address" type="string" required>
  要查询账户的 Solana 程序公钥（地址），作为 base-58 编码字符串。
</ParamField>

<ParamField body="commitment" type="string">
  请求的承诺级别。

  * `confirmed`
  * `finalized`
  * `processed`
</ParamField>

<ParamField body="minContextSlot" type="number">
  请求可以评估的最小槽。
</ParamField>

<ParamField body="withContext" type="boolean">
  当 `true` 时，返回 `result.context`（快照元数据：`slot`, `apiVersion`）并在 `result.value` 下嵌套 `accounts` 和 `paginationKey`。当 `false` 或省略时，这些字段直接出现在 `result` 上（例如 `result.accounts`）。应用相同的过滤器和限制。
</ParamField>

<ParamField body="encoding" type="string">
  返回账户数据的编码格式。

  * `jsonParsed`
  * `base58`
  * `base64`
  * `base64+zstd`
</ParamField>

<ParamField body="dataSlice" type="object">
  请求账户数据的切片。
</ParamField>

<ParamField body="dataSlice.length" type="number">
  返回的字节数。
</ParamField>

<ParamField body="dataSlice.offset" type="number">
  开始读取的字节偏移量。
</ParamField>

<ParamField body="limit" type="number">
  每个请求返回的最大账户数量（1-10,000）。
</ParamField>

<ParamField body="paginationKey" type="string">
  Base-58编码的分页游标，用于获取后续页面。使用先前响应中的paginationKey。
</ParamField>

<ParamField body="changedSinceSlot" type="number">
  仅返回在此槽位编号处或之后修改的账户。对增量更新很有用。
</ParamField>

<ParamField body="filters" type="array">
  强大的过滤系统，可高效查询特定的Solana账户数据模式。
</ParamField>


## OpenAPI

````yaml zh/openapi/rpc-http/getProgramAccountsV2.yaml POST /
openapi: 3.1.0
info:
  title: Solana RPC API
  version: 1.0.0
  description: >-
    增强的 Solana 程序账户索引 API，支持基于游标的分页和 changedSinceSlot，用于高效查询由特定程序拥有的大量账户集。支持通过基于
    slot 的过滤进行增量更新，实现实时数据同步。
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
  - url: https://mainnet.helius-rpc.com
    description: 主网 RPC 端点
  - url: https://devnet.helius-rpc.com
    description: 开发网 RPC 端点
security: []
paths:
  /:
    post:
      tags:
        - RPC
      summary: getProgramAccountsV2
      description: >
        增强版的getProgramAccounts，具有基于游标的分页和changedSinceSlot支持，以有效查询由特定Solana程序拥有的大型账户集。允许配置每个请求最多10,000个账户的增量数据获取。changedSinceSlot参数允许仅检索自特定区块链槽位以来修改的账户，非常适合实时索引和数据同步工作流程。对涉及大规模程序账户发现的应用程序至关重要，如DeFi协议、NFT市场和区块链分析平台。


        注意：分页结束仅在没有返回账户时指示。API可能由于过滤返回的账户较少 - 持续分页直到paginationKey为null。


        **withContext**：配置对象中的可选boolean（与encoding、limit等一起）。当`withContext`为`true`时，RPC返回标准的Solana包装结构：`result.context`（快照元数据，包括`slot`和通常的`apiVersion`）和`result.value`包含`accounts`、`paginationKey`，当`withContext`为`false`或省略时，这些字段直接返回在`result`上（例如`result.accounts`）。过滤器、限制和分页行为不变；只有`result`的JSON结构不同。
      operationId: getProgramAccountsV2
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - jsonrpc
                - id
                - method
                - params
              properties:
                jsonrpc:
                  type: string
                  description: JSON-RPC 协议版本。
                  enum:
                    - '2.0'
                  example: '2.0'
                  default: '2.0'
                id:
                  type: string
                  description: 请求的唯一标识符。
                  example: '1'
                  default: '1'
                method:
                  type: string
                  description: 要调用的 RPC 方法名称。
                  enum:
                    - getProgramAccountsV2
                  example: getProgramAccountsV2
                  default: getProgramAccountsV2
                params:
                  type: array
                  description: 增强分页方法的参数。
                  default:
                    - TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
                    - encoding: base64
                      limit: 1000
                  items:
                    oneOf:
                      - type: string
                        description: 要查询账户的 Solana 程序公钥（地址），以 base-58 编码的字符串形式。
                        example: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
                      - type: object
                        description: 具有分页支持的增强配置选项，用于优化程序账户查询。
                        properties:
                          commitment:
                            type: string
                            description: 请求的承诺级别。
                            enum:
                              - confirmed
                              - finalized
                              - processed
                            example: finalized
                          minContextSlot:
                            type: integer
                            description: 请求可以评估的最小槽位。
                            example: 1000
                          withContext:
                            type: boolean
                            description: >-
                              当`true`时，返回`result.context`（快照元数据：`slot`，`apiVersion`），并将`accounts`和`paginationKey`嵌套在`result.value`下。当为`false`或省略时，这些字段直接出现在`result`上（例如`result.accounts`）。相同的过滤器和限制适用。
                            example: true
                          encoding:
                            type: string
                            description: 返回账户数据的编码格式。
                            enum:
                              - jsonParsed
                              - base58
                              - base64
                              - base64+zstd
                            example: base64
                          dataSlice:
                            type: object
                            description: 请求账户数据的一个切片。
                            properties:
                              length:
                                type: integer
                                description: 要返回的字节数。
                                example: 50
                              offset:
                                type: integer
                                description: 字节偏移量，从该位置开始读取。
                                example: 0
                          limit:
                            type: integer
                            description: 每个请求返回的最大账户数量（1-10,000）。
                            minimum: 1
                            maximum: 10000
                            example: 1000
                          paginationKey:
                            type: string
                            description: Base-58 编码的分页游标，用于获取后续页面。使用上一个响应中的 paginationKey。
                            example: 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM
                          changedSinceSlot:
                            type: integer
                            description: 仅返回在此槽号或之后修改的账户。适用于增量更新。
                            example: 12345678
                          filters:
                            type: array
                            description: 强大的过滤系统，用于高效查询特定的 Solana 账户数据模式。
                            items:
                              oneOf:
                                - type: object
                                  description: 通过其精确的数据大小（以字节为单位）过滤 Solana 账户。
                                  properties:
                                    dataSize:
                                      type: integer
                                      description: 用于过滤的账户数据的精确大小（以字节为单位）。
                                      example: 165
                                - type: object
                                  description: 通过比较特定内存偏移处的数据来过滤 Solana 账户（最强大的过滤器）。
                                  properties:
                                    memcmp:
                                      type: object
                                      description: 用于查找具有特定数据模式的账户的内存比较过滤器。
                                      properties:
                                        offset:
                                          type: integer
                                          description: 在账户数据中执行比较的字节偏移量。
                                          example: 4
                                        bytes:
                                          type: string
                                          description: 在指定偏移位置进行比较的 Base-58 编码数据。
                                          example: 3Mc6vR
      responses:
        '200':
          description: 成功检索到分页的程序账户。
          content:
            application/json:
              schema:
                type: object
                properties:
                  jsonrpc:
                    type: string
                    description: JSON-RPC 协议版本。
                    enum:
                      - '2.0'
                    example: '2.0'
                  id:
                    type: string
                    description: 与请求匹配的标识符。
                    example: '1'
                  result:
                    oneOf:
                      - $ref: '#/components/schemas/ProgramAccountsV2Page'
                        title: without withContext
                      - type: object
                        title: with withContext
                        description: 当请求选项中的 `withContext` 为 `true` 时，包装结果。
                        required:
                          - context
                          - value
                        properties:
                          context:
                            type: object
                            description: 节点响应的快照元数据（插槽一致性、调试）。
                            properties:
                              slot:
                                type: integer
                                description: 节点生成此响应时的插槽。
                                example: 411895550
                              apiVersion:
                                type: string
                                description: 可用时的RPC API版本。
                                example: 3.1.9
                          value:
                            $ref: '#/components/schemas/ProgramAccountsV2Page'
        '400':
          description: 错误请求 - 请求参数无效或请求格式错误。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32602
                  message: Invalid params
                  data: {}
                id: '1'
        '401':
          description: 未授权 - API密钥无效或缺失。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32001
                  message: Unauthorized
                  data: {}
                id: '1'
        '429':
          description: 请求过多 - 超过速率限制。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32005
                  message: Too many requests
                  data: {}
                id: '1'
        '500':
          description: 内部服务器错误 - 服务器发生错误。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32603
                  message: 内部错误
                  data: {}
                id: '1'
        '503':
          description: 服务不可用 - 服务暂时不可用。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32002
                  message: 服务不可用
                  data: {}
                id: '1'
        '504':
          description: 网关超时 - 请求超时。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32003
                  message: 网关超时
                  data: {}
                id: '1'
      security:
        - ApiKeyQuery: []
components:
  schemas:
    ProgramAccountsV2Page:
      type: object
      description: >-
        分页的程序账户。当 withContext 为 false 或省略时，相同字段出现在结果中；当 withContext 为 true
        时，则出现在 result.value 下。
      properties:
        accounts:
          type: array
          description: 当前页面的程序账户列表。
          items:
            $ref: '#/components/schemas/ProgramAccountV2Entry'
        paginationKey:
          type: string
          description: 下一页的分页游标。仅当没有返回账户时为null（分页结束）。请注意，由于过滤，返回的账户数量可能少于限制，但这并不表示分页结束。
          example: 8WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM
          nullable: true
    ErrorResponse:
      type: object
      properties:
        jsonrpc:
          type: string
          description: JSON-RPC 协议版本。
          enum:
            - '2.0'
          example: '2.0'
        error:
          type: object
          properties:
            code:
              type: integer
              description: 错误代码。
              example: -32602
            message:
              type: string
              description: 错误信息。
            data:
              type: object
              description: 关于错误的附加数据。
        id:
          type: string
          description: 与请求匹配的标识符。
          example: '1'
    ProgramAccountV2Entry:
      type: object
      properties:
        pubkey:
          type: string
          description: 账户公钥，作为 base-58 编码字符串。
          example: CxELquR1gPP8wHe33gZ4QxqGB3sZ9RSwsJ2KshVewkFY
        account:
          type: object
          description: 关于账户的详细信息。
          properties:
            lamports:
              type: integer
              description: 分配给此账户的 lamports 数量。
              example: 15298080
            owner:
              type: string
              description: 此账户所属程序的 base-58 编码公钥。
              example: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
            data:
              type: array
              description: 账户数据，以编码的二进制或 JSON 格式。
              items:
                type: string
              example:
                - 2R9jLfiAQ9bgdcw6h8s44439
                - base64
            executable:
              type: boolean
              description: 指示账户是否包含程序。
              example: false
            rentEpoch:
              type: integer
              description: 此账户下一次将欠租的 epoch。
              example: 28
            space:
              type: integer
              description: 账户的数据大小。
              example: 165
  securitySchemes:
    ApiKeyQuery:
      type: apiKey
      in: query
      name: api-key
      description: >-
        您的 Helius API
        密钥。您可以在[仪表板](https://dashboard.helius.dev/api-keys)中免费获取一个。

````