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

# calculateSolanaTransactionFee

> Estimate the fee for a Solana transaction

Estimates the fee for a Solana transaction without running a full simulation. Returns fee data in
lamports, human-readable SOL, and optionally USD — but no asset diffs or security validation.

Supports both legacy `Transaction` and `VersionedTransaction` objects. Includes automatic retry
logic for network reliability.

Use this when you need a fee estimate only. Use
[simulateSolanaTransaction](/javascript/reference/solana/simulate-solana-transaction) when you also
want to preview asset changes and security validation.

## Installation

```bash theme={"system"}
npm install @dynamic-labs-sdk/solana
```

## Usage

```javascript theme={"system"}
import { calculateSolanaTransactionFee } from '@dynamic-labs-sdk/solana';
import { getNetworksData } from '@dynamic-labs-sdk/client';
import {
  Transaction,
  SystemProgram,
  PublicKey,
} from '@solana/web3.js';

const networks = getNetworksData();
const networkData = networks.find((n) => n.networkId === 'mainnet-beta');

const transaction = new Transaction().add(
  SystemProgram.transfer({
    fromPubkey: new PublicKey(walletAccount.address),
    toPubkey: new PublicKey(recipientAddress),
    lamports: 1_000_000_000,
  })
);

if (networkData) {
  const feeData = await calculateSolanaTransactionFee({
    transaction,
    networkData,
  });

  console.log(`Estimated fee: ${feeData.humanReadableAmount} SOL`);
}
```

## Parameters

| Parameter             | Type                                  | Description                                              |
| --------------------- | ------------------------------------- | -------------------------------------------------------- |
| `transaction`         | `Transaction \| VersionedTransaction` | The Solana transaction to estimate fees for              |
| `networkData`         | `NetworkData`                         | Network configuration. Get this from `getNetworksData()` |
| `nativeTokenPriceUsd` | `number` (optional)                   | USD price of SOL, used to calculate `usdAmount`          |

## Returns

`Promise<SolanaTransactionFeeData>`:

| Field                 | Type                | Description                                                     |
| --------------------- | ------------------- | --------------------------------------------------------------- |
| `nativeAmount`        | `bigint`            | Fee in lamports                                                 |
| `humanReadableAmount` | `string`            | Fee in SOL, formatted for display                               |
| `usdAmount`           | `string` (optional) | Fee in USD. Present only when `nativeTokenPriceUsd` is provided |

## Examples

### SOL transfer fee

```javascript theme={"system"}
const feeData = await calculateSolanaTransactionFee({
  transaction,
  networkData,
});

console.log(`Fee: ${feeData.humanReadableAmount} SOL`);
console.log(`Fee in lamports: ${feeData.nativeAmount}`);
```

### With USD conversion

```javascript theme={"system"}
const SOL_PRICE_USD = 180;

const feeData = await calculateSolanaTransactionFee({
  transaction,
  networkData,
  nativeTokenPriceUsd: SOL_PRICE_USD,
});

console.log(`Fee: ${feeData.humanReadableAmount} SOL`);
console.log(`≈ $${feeData.usdAmount}`);
```

### Versioned transaction

```javascript theme={"system"}
import { VersionedTransaction, TransactionMessage, PublicKey } from '@solana/web3.js';

const messageV0 = new TransactionMessage({
  payerKey: new PublicKey(walletAccount.address),
  recentBlockhash: latestBlockhash,
  instructions: [instruction],
}).compileToV0Message();

const versionedTx = new VersionedTransaction(messageV0);

const feeData = await calculateSolanaTransactionFee({
  transaction: versionedTx,
  networkData,
});
```

### Error handling

```javascript theme={"system"}
import { FeeEstimationFailedError } from '@dynamic-labs-sdk/client';

try {
  const feeData = await calculateSolanaTransactionFee({ transaction, networkData });
} catch (error) {
  if (error instanceof FeeEstimationFailedError) {
    console.error('Fee estimation failed:', error.message);
  }
}
```

## React

Estimate fees inside a button handler or effect. Re-estimate when the transaction or network changes:

```tsx theme={"system"}
import { calculateSolanaTransactionFee } from '@dynamic-labs-sdk/solana';
import { isSolanaWalletAccount } from '@dynamic-labs-sdk/solana';
import { getNetworksData } from '@dynamic-labs-sdk/client';
import { useGetWalletAccounts } from '@dynamic-labs-sdk/react-hooks';
import { useState } from 'react';
import { Transaction, SystemProgram, PublicKey } from '@solana/web3.js';

function SolanaFeeEstimator({ recipientAddress }) {
  const { data: walletAccounts = [] } = useGetWalletAccounts();
  const walletAccount = walletAccounts.find(isSolanaWalletAccount);
  const [fee, setFee] = useState('');

  const handleEstimate = async () => {
    if (!walletAccount) return;

    const networks = getNetworksData();
    const networkData = networks.find((n) => n.networkId === 'mainnet-beta');
    if (!networkData) return;

    const transaction = new Transaction().add(
      SystemProgram.transfer({
        fromPubkey: new PublicKey(walletAccount.address),
        toPubkey: new PublicKey(recipientAddress),
        lamports: 1_000_000_000,
      }),
    );

    const feeData = await calculateSolanaTransactionFee({ transaction, networkData });
    setFee(feeData.humanReadableAmount);
  };

  return (
    <div>
      <button onClick={handleEstimate} disabled={!walletAccount}>Estimate Fee</button>
      {fee && <p>Estimated fee: {fee} SOL</p>}
    </div>
  );
}
```

## Related functions

* [simulateSolanaTransaction](/javascript/reference/solana/simulate-solana-transaction) - Full simulation with asset diffs and security validation
* [calculateEvmTransactionFee](/javascript/reference/evm/calculate-evm-transaction-fee) - Fee estimation for EVM
* [calculateFeeForUserOperation](/javascript/reference/zerodev/calculate-fee-for-user-operation) - Fee calculation for ZeroDev user operations
* [getNetworksData](/javascript/reference/wallets/get-networks-data) - Get network configuration objects
