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

> 特定のSolanaプログラムが所有する大量のアカウントを効率的にクエリするための、カーソルベースのページネーションとchangedSinceSlotサポートを備えたgetProgramAccountsの強化バージョン。

## 概要

`getProgramAccountsV2`は、特定のSolanaプログラムが所有する大量のアカウントを効率的にクエリする必要があるアプリケーション向けに設計された標準的な`getProgramAccounts`メソッドの強化バージョンです。このメソッドは、カーソルベースのページネーションとインクリメンタルアップデート機能を導入します。

<Info>
  **V2の新機能:**

  * **カーソルベースのページネーション**: 1から10,000アカウントまでのリクエストごとの制限を設定
  * **インクリメンタルアップデート**: `changedSinceSlot`を使用して最近変更されたアカウントのみを取得
  * **パフォーマンスの向上**: 大規模データセットでのタイムアウトを防止し、メモリ使用量を削減
  * **後方互換性**: すべての既存の`getProgramAccounts`パラメータをサポート
  * **オプションの`withContext`**: `true`が`slot`と`apiVersion`を`result.context`の下に追加します。省略または`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>
  **重要なページネーションの動作**: ページネーションの終了は、**アカウントが返されない**ときのみ示されます。フィルタリングのため、制限より少ないアカウントが返される場合があります。`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="/ja/api-reference/rpc/http/getprogramaccounts">
    ページネーションなしの元のメソッド
  </Card>

  <Card title="getTokenAccountsByOwnerV2" icon="wallet" href="/ja/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`の場合、インスタンスメタデータ（`slot`、`apiVersion`）を返し、`accounts`を`result.value`の下にネストします。省略または`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 ja/openapi/rpc-http/getProgramAccountsV2.yaml POST /
openapi: 3.1.0
info:
  title: Solana RPC API
  version: 1.0.0
  description: >-
    特定のプログラムが所有するアカウントの大規模なセットを効率的に照会するために、カーソルベースのページネーションとchangedSinceSlotサポートを備えた強化されたSolanaプログラムアカウントインデックスAPI。スロットベースのフィルタリングを介してインクリメンタルな更新をサポートし、リアルタイムのデータ同期を実現します。
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
  - url: https://mainnet.helius-rpc.com
    description: Mainnet RPC エンドポイント
  - url: https://devnet.helius-rpc.com
    description: Devnet RPC エンドポイント
security: []
paths:
  /:
    post:
      tags:
        - RPC
      summary: getProgramAccountsV2
      description: >
        カーソルベースのページネーションとchangedSinceSlotサポートを備えたgetProgramAccountsの強化バージョンで、特定のSolanaプログラムが所有する大規模なアカウントを効率的にクエリできます。ページサイズを設定し、10,000アカウントまでのインクリメンタルデータ取得を可能にします。changedSinceSlotパラメータにより、特定のブロックチェーンスロット以降に変更されたアカウントのみを取得でき、リアルタイムのインデックス作成やデータ同期ワークフローに最適です。大規模なプログラムアカウントを扱うアプリケーションに必須です。例えばDeFiプロトコル、NFTマーケットプレイス、ブロックチェーン分析プラットフォームなど。注意：ページネーションが終了するのは、アカウントが一切返されない場合に限られます。APIはフィルタリングにより制限より少ないアカウントを返すことがありますが、ページネーションの終了を示すものではありません。**withContext**:設定オブジェクト内のオプションのブール値（エンコーディング、制限などと共に）として指定できます。`withContext`
        が `true` のとき、RPCは標準のSolanaラップシェイプを返します: `result.context`
        (スナップショットメタデータ、`slot` 、通常は `apiVersion` を含む) と `result.value` が
        `accounts`, `paginationKey` を保持しています。`withContext` が `false`
        または省略される場合、これらのフィールドは `result`
        に直接返されます(例えば、`result.accounts`)。フィルタ、制限、ページネーションの動作は変更されません。JSONの
        `result` の形だけが異なります。
      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: ベース58エンコードされた文字列としてのSolanaプログラム公開鍵（アドレス）で、アカウントを照会します。
                        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: >-
                              次のページを取得するためのベース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: 指定されたオフセット位置で比較するベース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: 無効なパラメータ
                  data: {}
                id: '1'
        '401':
          description: 認証されていない - APIキーが無効かまたは不足しています。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32001
                  message: 認証されていません
                  data: {}
                id: '1'
        '429':
          description: リクエストが多すぎます - レートリミットを超えました。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32005
                  message: リクエストが多すぎます
                  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: ベース58エンコードされた文字列としてのアカウントPubkey。
          example: CxELquR1gPP8wHe33gZ4QxqGB3sZ9RSwsJ2KshVewkFY
        account:
          type: object
          description: アカウントの詳細。
          properties:
            lamports:
              type: integer
              description: このアカウントに割り当てられたラムポートの数。
              example: 15298080
            owner:
              type: string
              description: このアカウントが割り当てられているプログラムのベース58エンコードされたPubkey。
              example: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
            data:
              type: array
              description: エンコードされたバイナリまたはJSON形式のアカウントデータ。
              items:
                type: string
              example:
                - 2R9jLfiAQ9bgdcw6h8s44439
                - base64
            executable:
              type: boolean
              description: アカウントにプログラムが含まれているかどうかを示します。
              example: false
            rentEpoch:
              type: integer
              description: このアカウントが次に家賃を支払うべきエポック。
              example: 28
            space:
              type: integer
              description: アカウントのデータサイズ。
              example: 165
  securitySchemes:
    ApiKeyQuery:
      type: apiKey
      in: query
      name: api-key
      description: >-
        あなたのHelius API
        キーです。[dashboard](https://dashboard.helius.dev/api-keys)で無料で取得できます。

````