> For the complete documentation index, see [llms.txt](https://docs.coinvera.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.coinvera.io/integration/solana/rpc/getfeeformessage.md).

# getFeeForMessage

The `getFeeForMessage` RPC method estimates the **base transaction fee** (in lamports) required to process a given **compiled transaction message**. This is especially helpful for displaying cost estimates to users or optimizing fee strategies before submitting transactions.

> **Version Note:** This method is available in `solana-core` v1.9 and above. For older versions, use `getFees`.

***

#### ✅ Common Use Cases

* **Estimate Transaction Fees**\
  Calculate the expected fee for a transaction *before* sending it to the network.
* **Optimize Transaction Costs**\
  Compare fees across different transaction structures or times to identify cost-efficient strategies.
* **Improve User Experience**\
  Show users a real-time fee estimate in your UI before they sign and submit a transaction.

***

#### 🛠 Request Parameters

`getFeeForMessage` takes the following parameters:

* **`message`** (*string, required*):\
  A **base64-encoded** serialized Solana transaction message. Must be a valid compiled message containing instructions, fee payer, and recent blockhash.
* **`config`** (*object, optional*):\
  Configuration object with:
  * `commitment` (*string*):\
    Commitment level (`processed`, `confirmed`, or `finalized`). Defaults to `finalized`.
  * `minContextSlot` (*number*):\
    The minimum slot at which the request is evaluated (for consistency in long-running processes).

***

#### 📦 Response Structure

The `result` field contains:

```json
{
  "context": {
    "slot": <u64>
  },
  "value": <u64 | null>
}
```

* **`context.slot`** – The slot used when evaluating the fee.
* **`value`** – Estimated fee in **lamports** (1 SOL = 1,000,000,000 lamports).\
  `null` if the fee could not be calculated (e.g., expired blockhash or invalid message).

#### 💡 Example: Estimate Fee for a Simple Transfer

> First, compile a transfer transaction and extract its message in base64 format, then call:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getFeeForMessage",
  "params": [
    "base64_encoded_transaction_message_here",
    {
      "commitment": "finalized"
    }
  ]
}
```

**Code Examples**

{% tabs %}
{% tab title="Nodejs" %}

```javascript
const fetch = require('node-fetch');

async function getFeeForMessage(rpcUrl) {
  try {
    const response = await fetch(rpcUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'getFeeForMessage',
        "params": [
            "MESSAGE_BASE64_ENCODED", // Replace with your actual base64 encoded message
            { "commitment": "processed" }
          ]
      }),
    });

    const data = await response.json();
    
    // Print the exact full response
    console.log('Full RPC Response:');
    console.log(JSON.stringify(data, null, 2));
    
    return data;
  } catch (error) {
    console.error('Error getting health:', error.message);
    return null;
  }
}

// Example usage
const RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key';

getFeeForMessage(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def get_fee_for_message(rpc_url):
    try:
        response = requests.post(
            rpc_url,
            headers={
                'Content-Type': 'application/json',
            },
            json={
                'jsonrpc': '2.0',
                'id': 1,
                'method': 'getFeeForMessage',
                'params': [
                    'MESSAGE_BASE64_ENCODED',  # Replace with your actual base64 encoded message
                    {'commitment': 'processed'}
                ]
            }
        )
        
        data = response.json()
        
        # Print the exact full response
        print('Full RPC Response:')
        print(json.dumps(data, indent=2))
        
        return data
        
    except Exception as error:
        print(f'Error getting health: {error}')
        return None

# Example usage
RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key'
get_fee_for_message(RPC_URL)
```

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "result": {
    "context": { "slot": 5068 },
    "value": 5000
  },
  "id": 1
}
```

#### 🧠 Developer Tips

* **Message Construction**\
  Ensure your message is well-formed with:
  * Valid fee payer
  * Correct instructions
  * A **recent** blockhash (within \~2 minutes)
* **Expired Blockhash**\
  If the blockhash is too old, the fee may return as `null`. Always refresh the blockhash before compiling the message.
* **Base Fee Only**\
  This method returns **only the base network fee**. To estimate priority fees, use `getRecentPrioritizationFees`.
* **Lamports, Not SOL**\
  The value is returned in **lamports**. Divide by `1_000_000_000` to convert to SOL for display purposes.
* **Handling Null Responses**\
  A `null` fee indicates:
  * Invalid or expired blockhash
  * Malformed message
  * Inability to compute at current commitment level
