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

# getLatestBlockhash 사용법

> getLatestBlockhash 사용 사례, 코드 예제, 요청 매개변수, 응답 구조 및 팁을 학습하십시오.

[`getLatestBlockhash`](https://www.helius.dev/docs/api-reference/rpc/http/getlatestblockhash) RPC 방법은 Solana 네트워크에서 트랜잭션을 준비하고 전송하는 데 필수적입니다. 이 메서드는 노드에서 처리한 가장 최근의 blockhash와 이 blockhash가 유효할 마지막 블록 높이를 검색합니다. blockhash를 효과적으로 사용하고 [트랜잭션을 착지](https://www.helius.dev/blog/how-to-land-transactions-on-solana)하는 방법에 대한 자세한 내용은 포괄적인 가이드를 참조하세요.

Solana의 모든 트랜잭션은 최근의 blockhash를 참조해야 합니다. 이 메커니즘은 포크된 체인에서 트랜잭션 재생 등의 특정 유형의 공격을 방지합니다.

**버전 참고:** 이 방법은 `solana-core` v1.9 이상에서 사용할 수 있습니다. `solana-core` v1.8 이하를 실행하는 노드의 경우 `getRecentBlockhash` 방법을 사용하세요.

## 일반적인 사용 사례

* **트랜잭션 빌딩:** 서명 및 전송하기 전에 새 트랜잭션에 포함할 최근 blockhash를 얻습니다.
* **트랜잭션 수명 관리:** 가져온 blockhash를 참조하는 트랜잭션이 얼마나 오래 유효할 수 있는지를 이해하기 위해 `lastValidBlockHeight`를 사용합니다.
* **사전 검사:** `simulateTransaction`가 이를 암시적으로 수행할 수 있지만, 응용 프로그램은 시뮬레이션을 위해 트랜잭션을 수동으로 준비하기 위해 blockhash를 가져올 수 있습니다.

## 요청 매개변수

이 방법은 다음 매개변수를 포함한 구성 객체를 선택적으로 취할 수 있습니다:

* **`commitment`** (string, optional): 쿼리의 [commitment 수준](https://www.helius.dev/blog/solana-commitment-levels)을 지정합니다. 생략된 경우 노드의 기본 commitment가 사용됩니다. 트랜잭션의 경우, 체인의 적절히 안정된 부분에서 blockhash를 보장하기 위해 `confirmed` 또는 `finalized`를 사용하는 것이 일반적입니다.
* **`minContextSlot`** (integer, optional): 요청을 평가할 수 있는 최소 슬롯입니다. 이 슬롯을 처리한 원장 상태에 대해 쿼리가 수행되도록 보장합니다.

## 응답 구조

JSON-RPC 응답의 `result` 필드는 `RpcResponse` 객체입니다. 이 객체 내의 `value` 필드에는 다음이 포함됩니다:

* **`blockhash`** (string): 최신 blockhash를 나타내는 base-58 인코딩 문자열입니다.
* **`lastValidBlockHeight`** (u64): `blockhash`가 만료될 블록 높이입니다. 이 `blockhash`를 참조하는 트랜잭션은 네트워크가 이 `lastValidBlockHeight`에 도달할 때까지 유효합니다.

응답에는 정보가 검색된 `slot`와 함께 `context` 객체도 포함됩니다.

## 예시

### 1. 기본 Commitment로 최신 Blockhash 가져오기

이 예제는 노드의 기본 commitment를 사용하여 최신 blockhash를 가져옵니다.

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getLatestBlockhash"
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  // Replace <api-key> with your Helius API key
  const { Connection } = require('@solana/web3.js');

  async function fetchLatestBlockhash() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
      console.log('Latest Blockhash Info:');
      console.log(`  Blockhash: ${blockhash}`);
      console.log(`  Last Valid Block Height: ${lastValidBlockHeight}`);
      // This blockhash can now be used in a transaction
    } catch (error) {
      console.error('Error fetching latest blockhash:', error);
    }
  }

  fetchLatestBlockhash();
  ```
</CodeGroup>

### 2. 'confirmed' Commitment로 최신 Blockhash 가져오기

이 예제는 `confirmed` commitment로 최신 blockhash를 명시적으로 요청합니다.

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

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  // Replace <api-key> with your Helius API key
  const { Connection } = require('@solana/web3.js');

  async function fetchConfirmedBlockhash() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
      console.log('Confirmed Blockhash Info:');
      console.log(`  Blockhash: ${blockhash}`);
      console.log(`  Last Valid Block Height: ${lastValidBlockHeight}`);
    } catch (error) {
      console.error('Error fetching confirmed blockhash:', error);
    }
  }

  fetchConfirmedBlockhash();
  ```
</CodeGroup>

## 개발자 팁

* **Blockhash 유효성:** Blockhash는 제한된 시간 동안 유효하며, 약 2분 정도입니다(이 기간은 달라질 수 있음). 트랜잭션은 `lastValidBlockHeight`가 지나기 전에 네트워크에 의해 확인되어야 합니다. 마지막 blockhash를 가져온 이후 많은 시간이 지났다면 항상 새 blockhash를 가져옵니다.
* **Commitment 선택:** 중요한 거래의 경우, `finalized` commitment를 사용하는 것이 main chain fork에서 blockhash가 있다는 가장 강력한 보증을 제공하지만, 약간 오래될 수 있습니다. `confirmed`는 좋은 균형을 제공합니다. [commitment 수준](https://www.helius.dev/blog/solana-commitment-levels)에 대한 자세한 정보를 학습하세요.
* **거래 수수료:** 적절한 거래 수수료도 계산해서 포함해야 합니다. Blockhash 자체가 수수료를 결정하지 않습니다.
* **재시도 로직:** 트랜잭션이 `lastValidBlockHeight`가 지나서 만료되면, 새로운 최신 blockhash로 다시 서명하여 재제출해야 합니다.

이 가이드는 Solana 네트워크를 통해 트랜잭션과 상호작용하는 데 있어 중요한 역할을 하는 `getLatestBlockhash`를 효과적으로 사용하는 단계를 제공합니다.

## 관련 메서드

<CardGroup cols={2}>
  <Card title="simulateTransaction" href="/docs/ko/api-reference/rpc/http/simulatetransaction">
    전송 전에 트랜잭션 시뮬레이션
  </Card>

  <Card title="isBlockhashValid" href="/docs/ko/api-reference/rpc/http/isblockhashvalid">
    blockhash가 여전히 유효한지 확인
  </Card>
</CardGroup>
