> ## 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>
  **중요한 페이지네이션 동작**: 페이지네이션의 끝은 **아무 계정도 반환되지 않을 때**만 표시됩니다. 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="/docs/ko/api-reference/rpc/http/getprogramaccounts">
    페이지네이션 없는 기본 메서드
  </Card>

  <Card title="getTokenAccountsByOwnerV2" icon="wallet" href="/docs/ko/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`)을 반환하고,
  `accounts` 및 `paginationKey`을 `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 ko/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: 메인넷 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
        마켓플레이스, 블록체인 분석 플랫폼과 같은 대규모 프로그램 계정 검색을 처리하는 애플리케이션에 필수적입니다.


        참고: 페이징이 끝났다는 것은 계정이 반환되지 않을 때만 나타납니다. 필터링으로 인해 제한보다 적은 계정이 반환될 수 있으며 -
        paginationKey가 null이 될 때까지 페이징을 계속하십시오.


        **withContext**: 구성 개체(인코딩, 제한 등과 함께)에서 선택적인 boolean입니다. `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`)를 반환하고

                              `result.value` 아래에 `accounts`와 `paginationKey`를
                              중첩시키며, `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: Internal error
                  data: {}
                id: '1'
        '503':
          description: 서비스 불가 - 서비스가 일시적으로 불가능합니다.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32002
                  message: Service unavailable
                  data: {}
                id: '1'
        '504':
          description: 게이트웨이 시간 초과 - 요청이 시간 초과되었습니다.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                jsonrpc: '2.0'
                error:
                  code: -32003
                  message: Gateway timeout
                  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로 인코딩된 계정 Pubkey입니다.
          example: CxELquR1gPP8wHe33gZ4QxqGB3sZ9RSwsJ2KshVewkFY
        account:
          type: object
          description: 계정에 대한 세부사항입니다.
          properties:
            lamports:
              type: integer
              description: 이 계정에 할당된 lamports의 수입니다.
              example: 15298080
            owner:
              type: string
              description: 이 계정이 할당된 프로그램의 base-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: 이 계정이 다음에 렌트를 지불해야 하는 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)에서 무료로
        얻을 수 있습니다.

````