> ## 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`の使用を検討してください。

## 一般的な使用例

* **手数料見積もり:** 特定のメッセージに対する予想されるトランザクション手数料（lamports単位）を決定します。
* **コスト最適化:** 異なるトランザクション構造や異なる時間での手数料を分析します。
* **ユーザーインターフェースの表示:** ユーザーがトランザクションに署名して送信する前に、推定トランザクションコストを表示します。

## リクエストパラメータ

1. **`message`** (string, required): トランザクションメッセージ、base64エンコード。これはトランザクションをコンパイルすることで取得できます。
2. **`config`** (object, optional): 以下のフィールドを持つ設定オブジェクト：
   * **`commitment`** (string, optional): 使用する[コミットメントレベル](https://www.helius.dev/blog/solana-commitment-levels)を指定します。デフォルトは`finalized`です。
   * **`minContextSlot`** (number, optional): リクエストが評価可能な最小スロット。

## レスポンス構造

JSON-RPCレスポンスの`result`フィールドは、以下の構造を持つオブジェクトです。

* **`context`** (object):
  * **`slot`** (u64): 手数料が評価されたスロット。
* **`value`** (u64 | null): lamports単位の推定手数料。手数料が決定できない場合（例：メッセージで使用されているブロックハッシュが古すぎるか無効な場合）、これは`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)を見積もってください。
* **Lamports:** 手数料はlamports単位（1 SOL = 1,000,000,000 lamports）で返されます。
* **Null値:** 手数料に`null`の値がある場合は、メッセージに問題があること（例：無効なブロックハッシュ、誤ったメッセージ）や、そのノードが指定されたコミットメントレベルやスロットで手数料を計算できないことを示している可能性があります。

このガイドは、Solanaネットワークでのトランザクション手数料を見積もるための`getFeeForMessage` RPCメソッドを利用するための必要な手順を提供します。

## 関連するメソッド

<CardGroup cols={2}>
  <Card title="getLatestBlockhash" href="/ja/api-reference/rpc/http/getlatestblockhash">
    メッセージ作成用の最近のブロックハッシュを取得
  </Card>

  <Card title="getRecentPrioritizationFees" href="/ja/api-reference/rpc/http/getrecentprioritizationfees">
    迅速な処理のための優先手数料を見積もります
  </Card>
</CardGroup>
