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

# getFeeForMessage 사용 방법

> getFeeForMessage 사용 사례, 코드 예제, 요청 매개변수, 응답 구조 및 팁을 배우세요.

[`getFeeForMessage`](https://www.helius.dev/docs/api-reference/rpc/http/getfeeformessage) RPC 메소드는 주어진 트랜잭션 메시지를 처리하기 위해 네트워크가 부과할 수수료를 추정할 수 있게 해줍니다. 이는 네트워크에 제출되기 전에 [트랜잭션 비용](https://www.helius.dev/blog/solana-fees-in-theory-and-practice)을 이해하는 데 유용합니다.

**버전 노트:** 이 메소드는 `solana-core` v1.9 이상에서 사용할 수 있습니다. 이전 버전의 경우 `getFees`를 고려하십시오.

## 일반적인 사용 사례

* **수수료 추정:** 특정 메시지에 대한 예상 트랜잭션 수수료(람포트 단위)를 결정합니다.
* **비용 최적화:** 다른 트랜잭션 구조 또는 다른 시간대에 대한 수수료를 분석합니다.
* **사용자 인터페이스 표시:** 사용자가 서명하고 전송하기 전에 예상 트랜잭션 비용을 표시합니다.

## 요청 매개변수

1. **`message`** (string, 필수): 베이스64로 인코딩된 트랜잭션 메시지. 트랜잭션을 컴파일하여 얻을 수 있습니다.
2. **`config`** (object, 선택 사항): 다음 필드를 포함하는 구성 객체:
   * **`commitment`** (string, 선택 사항): 사용할 [커밋 수준](https://www.helius.dev/blog/solana-commitment-levels)을 지정합니다. 기본값은 `finalized`입니다.
   * **`minContextSlot`** (number, 선택 사항): 요청을 평가할 수 있는 최소 슬롯.

## 응답 구조

JSON-RPC 응답의 `result` 필드는 다음 구조를 가지는 객체입니다:

* **`context`** (object):
  * **`slot`** (u64): 수수료가 평가된 슬롯입니다.
* **`value`** (u64 | null): 람포트 단위로 추정된 수수료입니다. 사용된 메시지의 블록 해시가 너무 오래되었거나 유효하지 않은 경우 수수료를 결정할 수 없는 경우 `null`일 수 있습니다.

## 예제

### 1. 단순 전송 메시지에 대한 수수료 추정하기

이 예제는 단순 전송을 구성하고, 메시지를 컴파일한 다음 추정된 수수료를 가져오는 방법을 보여줍니다.

<CodeGroup>
  ```bash cURL theme={"system"}
  # First, you need a base64 encoded message. 
  # This typically involves creating a transaction, compiling its message, 
  # and then base64 encoding the serialized message.
  # The example message below is illustrative.
  # Replace "MESSAGE_BASE64_ENCODED" with your actual encoded message.
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getFeeForMessage",
      "params": [
        "MESSAGE_BASE64_ENCODED", // Replace with your actual base64 encoded message
        { "commitment": "processed" }
      ]
    }'
  ```

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

  async function estimateTransactionFee() {
    const connection = new Connection('https://devnet.helius-rpc.com/?api-key=<api-key>');

    try {
      const fromPublicKey = Keypair.generate().publicKey;
      const toPublicKey = Keypair.generate().publicKey;

      let transaction = new Transaction().add(
        SystemProgram.transfer({
          fromPubkey: fromPublicKey,
          toPubkey: toPublicKey,
          lamports: 1000,
        })
      );

      transaction.feePayer = fromPublicKey;
      const { blockhash } = await connection.getLatestBlockhash('confirmed');
      transaction.recentBlockhash = blockhash;

      const message = transaction.compileMessage();
      const messageBase64 = message.serialize().toString('base64');

      console.log(`Compiled Message (Base64): ${messageBase64}`);

      const feeResult = await connection.getFeeForMessage(message, 'confirmed');

      if (feeResult && feeResult.value !== null) {
        console.log(`Estimated Fee: ${feeResult.value} lamports`);
      } else {
        console.log('Could not estimate fee. The value was null.');
        console.log('This might happen if the blockhash is too old or the message is invalid.');
      }

    } catch (error) {
      console.error('Error estimating transaction fee:', error);
      if (error.message.includes('failed to get recent blockhash')) {
          console.error('Ensure your RPC endpoint is responsive or try a different commitment level for getLatestBlockhash.');
      }
    }
  }

  estimateTransactionFee();
  ```
</CodeGroup>

## 개발자 팁

* **메시지 구성:** `getFeeForMessage`를 사용하기 위한 핵심은 트랜잭션 `Message`를 올바르게 구성하고 직렬화하는 것입니다. 여기에는 수수료 지불자, 지시사항 및 최근 블록해시 설정이 포함됩니다.
* **최근 블록해시:** 메시지는 최근 블록해시로 구성해야 합니다. 블록해시가 너무 오래된 경우 응답의 `value`는 `null`일 수 있습니다.
* **수수료 대 우선 수수료:** 이 메소드는 기본 네트워크 수수료를 반환합니다. 네트워크 혼잡 시 빠른 처리를 위해 트랜잭션에 추가할 수 있는 우선 수수료는 포함되지 않습니다. `getRecentPrioritizationFees`를 사용하여 [우선 수수료](https://www.helius.dev/blog/priority-fees-understanding-solanas-transaction-fee-mechanics)를 추정하십시오.
* **람포트:** 수수료는 람포트 단위로 반환됩니다 (1 SOL = 1,000,000,000 람포트).
* **널 값:** 수수료에 대한 `null` 값은 메시지에 문제가 있음을 나타낼 수 있습니다 (예: 잘못된 블록해시, 잘못된 메시지) 또는 주어진 커밋 수준이나 슬롯에서 노드가 수수료를 계산할 수 없음을 나타낼 수 있습니다.

이 가이드는 Solana 네트워크에서 트랜잭션 수수료를 추정하기 위해 `getFeeForMessage` RPC 메소드를 활용하는 데 필요한 단계들을 제공합니다.

## 관련 메소드

<CardGroup cols={2}>
  <Card title="getLatestBlockhash" href="/docs/ko/api-reference/rpc/http/getlatestblockhash">
    메시지 구성을 위한 최근 블록해시 가져오기
  </Card>

  <Card title="getRecentPrioritizationFees" href="/docs/ko/api-reference/rpc/http/getrecentprioritizationfees">
    빠른 처리를 위한 우선 수수료 추정하기
  </Card>
</CardGroup>
