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

# getBlocks 사용 방법

> getBlocks 사용 사례, 코드 예제, 요청 매개변수, 응답 구조 및 팁을 학습합니다.

[`getBlocks`](https://www.helius.dev/docs/api-reference/rpc/http/getblocks) RPC 메서드는 지정된 시작 슬롯과 선택적 끝 [슬롯](https://www.helius.dev/blog/solana-slots-blocks-and-epochs) 사이의 확인된 블록 슬롯 번호 목록을 검색할 수 있도록 합니다. 이는 특정 범위에서 확인된 블록을 알고자 할 때 각 블록의 전체 내용을 가져오지 않고도 유용합니다.

<Warning>
  **성능 향상을 위해 배치 사용을 피하세요**

  배치된 보관 방법은 지연 시간을 크게 증가시킵니다. 10개 이상의 요청에 대한 배치는 허용되지 않습니다.
</Warning>

## 일반적인 사용 사례

* **블록 확인 범위 식별:** 원장에서 두 지점 사이에 성공적으로 확인된 모든 블록 슬롯의 목록을 빠르게 가져옵니다.
* **블록을 통한 반복:** 필요에 따라 `getBlock`를 사용하여 각 블록에 대한 자세한 정보를 가져오기 위해 반환된 슬롯 목록을 사용합니다.
* **기본 블록 감사:** 특정 범위 내에서 블록의 존재를 확인합니다.

## 요청 매개변수

`getBlocks` 메서드는 다음 매개변수를 사용합니다:

1. **`start_slot`** (u64, 필수): 범위에 대해 고려할 첫 번째 슬롯(포함).
2. **`end_slot`** (u64, 선택): 범위에 대해 고려할 마지막 슬롯(포함).
   * 제공되지 않으면, 쿼리는 `start_slot`부터 최신 확인 슬롯까지 블록을 반환합니다.
   * `start_slot`와 `end_slot`(또는 `end_slot`가 생략된 경우 최신 슬롯) 사이의 범위는 **500,000 슬롯을 초과할 수 없습니다**.
3. **`commitment`** (문자열, 선택): 쿼리에 대한 커밋 수준을 지정합니다. 생략된 경우 노드의 기본 커밋이 사용됩니다. 마지막 매개변수로 구성 객체에서 유일한 필드로 전달됩니다.

## 응답 구조

JSON-RPC 응답의 `result` 필드는 u64 정수 배열입니다. 배열의 각 정수는 지정된 범위 내에서 확인된 블록 슬롯 번호를 나타냅니다.

* 예시: `[5, 6, 7, 8, 9, 10]`

## 예시

### 1. 특정 슬롯 범위 내의 블록 가져오기

이 예시는 슬롯 `250000000`와 `250000010` 사이의 확인된 블록 슬롯 목록을 가져옵니다.

<CodeGroup>
  ```bash cURL theme={"system"}
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getBlocks",
      "params": [
        250000000,
        250000010
      ]
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  const { Connection } = require('@solana/web3.js');

  async function getBlocksInRange(startSlot, endSlot) {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      const blocks = await connection.getBlocks(startSlot, endSlot);
      console.log(`Confirmed blocks between slot ${startSlot} and ${endSlot}:`, blocks);
    } catch (error) {
      console.error('Error fetching blocks:', error);
    }
  }

  // Example usage:
  const startSlot = 250000000;
  const endSlot = 250000010;
  getBlocksInRange(startSlot, endSlot);
  ```
</CodeGroup>

### 2. 시작 슬롯에서 최신 확인 슬롯까지 블록 가져오기

이 예시는 `260000000`부터 노드에 의해 확인된 최신 블록까지 확인된 블록 슬롯을 가져옵니다(시작 슬롯에서 500,000 슬롯 범위 제한을 준수).

<CodeGroup>
  ```bash cURL theme={"system"}
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getBlocks",
      "params": [
        260000000 
      ]
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  const { Connection } = require('@solana/web3.js');

  async function getBlocksFromStart(startSlot) {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      // The endSlot parameter is omitted to fetch up to the latest confirmed block
      const blocks = await connection.getBlocks(startSlot);
      console.log(`Confirmed blocks from slot ${startSlot} to latest:`, blocks);
      if (blocks.length > 0) {
        console.log(`Latest block in range: ${blocks[blocks.length - 1]}`);
      }
    } catch (error) {
      console.error('Error fetching blocks:', error);
    }
  }

  // Example usage (ensure this doesn't exceed the 500,000 slot limit from latest block):
  const recentStartSlot = 260000000; 
  getBlocksFromStart(recentStartSlot);
  ```
</CodeGroup>

### 3. 특정 커밋 수준으로 블록 가져오기

이 예시는 `confirmed` 커밋 수준을 사용하여 블록을 가져옵니다.

<CodeGroup>
  ```bash cURL theme={"system"}
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getBlocks",
      "params": [
        270000000,
        270000005,
        { "commitment": "confirmed" }
      ]
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  const { Connection } = require('@solana/web3.js'); 

  async function getBlocksWithCommitment(startSlot, endSlot) {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      const blocks = await connection.getBlocks(startSlot, endSlot, { commitment: 'confirmed' });
      console.log(`Confirmed blocks (with 'confirmed' commitment) between slot ${startSlot} and ${endSlot}:`, blocks);
    } catch (error) {
      console.error('Error fetching blocks with commitment:', error);
    }
  }

  // Example usage:
  const commitStartSlot = 270000000;
  const commitEndSlot = 270000005;
  getBlocksWithCommitment(commitStartSlot, commitEndSlot);
  ```
</CodeGroup>

## 개발자 팁

* **범위 제한:** 500,000 슬롯 범위 제한을 기억하십시오. 더 큰 범위를 요청하면 오류가 발생합니다.
* **노드 데이터 가용성:** 노드는 모든 역사적 슬롯에 대한 정보를 보유하지 않을 수 있습니다. 매우 오래된 `start_slot` 값은 노드의 구성 및 원장 보유에 따라 빈 배열이나 오류를 반환할 수 있습니다.
* **블록 확인:** 이 메서드는 *확인된* 블록을 반환합니다. 선택한 `commitment` 수준과 쿼리한 노드에 따라 특히 최근 슬롯의 경우 정확한 블록 세트가 약간 다를 수 있습니다.
* **`getBlock`에 대한 보완:** `getBlocks`는 종종 관련 블록 슬롯을 식별한 후 `getBlock`를 사용하여 해당 목록의 개별 블록에 대한 전체 세부 정보를 검색하는 첫 번째 단계로 사용됩니다.
* **페이징 대안:** `getBlocks`에 범위 제한이 있기 때문에 체인의 매우 큰 부분을 검색해야 하는 경우 원하는 총 범위를 500,000 슬롯 이하의 세그먼트로 나누어 여러 번의 호출을 해야 합니다.

이 가이드는 솔라나 네트워크에서 확인된 블록 슬롯을 나열하기 위해 `getBlocks` RPC 메서드를 사용하는 방법에 대한 명확한 개요를 제공합니다.

## 관련 메서드

<CardGroup cols={2}>
  <Card title="getBlock" href="/docs/ko/api-reference/rpc/http/getblock">
    특정 블록에 대한 자세한 정보 가져오기
  </Card>

  <Card title="getBlocksWithLimit" href="/docs/ko/api-reference/rpc/http/getblockswithlimit">
    슬롯에서 시작하여 고정된 수의 블록 가져오기
  </Card>
</CardGroup>
