> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# getFeeForMessage

> Returns the lamports the cluster would charge to process a serialized message at the requested commitment.

<Info>
  **Source**

  [`get_fee_for_message`](https://github.com/anza-xyz/agave/blob/v4.3.2/rpc/src/rpc.rs#L4349)
</Info>

The node returns a fee only while the message's blockhash is valid. The Kit,
web3.js, and Rust examples compile a transfer message with a recent blockhash
from [`getLatestBlockhash`](/developers/docs/rpc/http/getlatestblockhash). The
cURL message carries a placeholder blockhash (all zeros), so the node returns
`"value": null`.

<RequestExample>
  ```bash cURL
  curl https://api.devnet.solana.com -s -X POST \
    -H "Content-Type: application/json" \
    -d '
    {
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getFeeForMessage",
      "params": [
        "AQABAgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQAA",
        {
          "commitment": "processed"
        }
      ]
    }
  '
  ```

  ```ts Kit
  import {
    address,
    appendTransactionMessageInstruction,
    compileTransaction,
    createNoopSigner,
    createSolanaRpc,
    createTransactionMessage,
    getBase64Decoder,
    lamports,
    pipe,
    setTransactionMessageFeePayerSigner,
    setTransactionMessageLifetimeUsingBlockhash,
    type TransactionMessageBytesBase64
  } from "@solana/kit";
  import { getTransferSolInstruction } from "@solana-program/system";

  const rpc_url = "https://api.devnet.solana.com";
  const rpc = createSolanaRpc(rpc_url);

  // The fee depends only on the message, so no private key is needed
  const sender = createNoopSigner(
    address("4kg8oh3jdNtn7j2wcS7TrUua31AgbLzDVkBZgTAe44aF")
  );
  const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();

  const transactionMessage = pipe(
    createTransactionMessage({ version: 0 }),
    (m) => setTransactionMessageFeePayerSigner(sender, m),
    (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
    (m) =>
      appendTransactionMessageInstruction(
        getTransferSolInstruction({
          source: sender,
          destination: address("devFqxUpdo1sYETcWTXT12JE8V53MG2hRsXNMx2bYhA"),
          amount: lamports(1_000_000n)
        }),
        m
      )
  );

  // Compile the message and base64-encode its bytes
  const message = getBase64Decoder().decode(
    compileTransaction(transactionMessage).messageBytes
  ) as TransactionMessageBytesBase64;

  let fee = await rpc.getFeeForMessage(message).send();

  console.log(fee);
  ```

  ```ts web3.js
  import {
    Connection,
    PublicKey,
    SystemProgram,
    TransactionMessage,
    clusterApiUrl
  } from "@solana/web3.js";

  const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

  // The fee depends only on the message, so no private key is needed
  const sender = new PublicKey("4kg8oh3jdNtn7j2wcS7TrUua31AgbLzDVkBZgTAe44aF");
  const { blockhash } = await connection.getLatestBlockhash();

  let message = new TransactionMessage({
    payerKey: sender,
    recentBlockhash: blockhash,
    instructions: [
      SystemProgram.transfer({
        fromPubkey: sender,
        toPubkey: new PublicKey("devFqxUpdo1sYETcWTXT12JE8V53MG2hRsXNMx2bYhA"),
        lamports: 1_000_000
      })
    ]
  }).compileToV0Message();

  let fee = await connection.getFeeForMessage(message);

  console.log(fee);
  ```

  ```rs Rust
  use anyhow::Result;
  use solana_client::nonblocking::rpc_client::RpcClient;
  use solana_commitment_config::CommitmentConfig;
  use solana_sdk::{message::Message, pubkey};
  use solana_system_interface::instruction::transfer;

  #[tokio::main]
  async fn main() -> Result<()> {
      let client = RpcClient::new_with_commitment(
          String::from("https://api.devnet.solana.com"),
          CommitmentConfig::confirmed(),
      );

      // The fee depends only on the message, so no private key is needed
      let sender = pubkey!("4kg8oh3jdNtn7j2wcS7TrUua31AgbLzDVkBZgTAe44aF");
      let recipient = pubkey!("devFqxUpdo1sYETcWTXT12JE8V53MG2hRsXNMx2bYhA");
      let blockhash = client.get_latest_blockhash().await?;

      let message = Message::new_with_blockhash(
          &[transfer(&sender, &recipient, 1_000_000)],
          Some(&sender),
          &blockhash,
      );

      let fee = client.get_fee_for_message(&message).await?;

      println!("{:#?}", fee);

      Ok(())
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Response
  {
    "jsonrpc": "2.0",
    "result": {
      "context": { "apiVersion": "4.3.2", "slot": 518091887 },
      "value": 5000
    },
    "id": 1
  }
  ```

  ```json title="invalid blockhash"
  {
    "jsonrpc": "2.0",
    "result": {
      "context": { "apiVersion": "4.3.2", "slot": 518091887 },
      "value": null
    },
    "id": 1
  }
  ```
</ResponseExample>

## Parameters

<ParamField body="message" type="string" required>
  Base-64 encoded transaction message. Accepts both legacy and v0 (versioned)
  message formats.
</ParamField>

<ParamField body="config" type="object">
  Configuration object.

  <Expandable title="properties" defaultOpen>
    <ParamField body="commitment" type="string" default="finalized">
      Values: `processed`, `confirmed`, `finalized`

      Solana RPC uses the following commitment levels:

      | Value       | Description                                                                                                                                                                               |
      | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
      | `processed` | Return data from the highest slot this node has processed. This is the newest view, but the block can still be skipped.                                                                   |
      | `confirmed` | Return data from the same slot as `finalized`. Kept for compatibility and planned for removal in a later release.                                                                         |
      | `finalized` | Return data from the highest slot with a finalization certificate, from votes by 80% of stake in one round or 60% of stake in each of two rounds. This is the strongest commitment level. |
    </ParamField>

    <ParamField body="minContextSlot" type="number">
      The minimum slot that the request can be evaluated at.

      ```json Example
      { "minContextSlot": 341197000 }
      ```
    </ParamField>
  </Expandable>
</ParamField>

## Result

<ResponseField name="result" type="object">
  RpcResponse object containing:

  <Expandable title="properties" defaultOpen>
    <ResponseField name="context" type="object">
      Slot and API version the node used to answer this request.

      | Field        | Type     | Description                                                                     |
      | ------------ | -------- | ------------------------------------------------------------------------------- |
      | `slot`       | `u64`    | Slot at which the node evaluated this request.                                  |
      | `apiVersion` | `string` | RPC API version reported by the node. This field may be omitted by older nodes. |
    </ResponseField>

    <ResponseField name="value" type="u64 | null">
      Fee for the supplied message at the referenced blockhash, in lamports. Returns
      `null` if the blockhash is no longer valid.
    </ResponseField>
  </Expandable>
</ResponseField>
