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

# How to Calculate Transaction Cost

> Every transaction costs compute units and a fee in lamports to execute on Solana. Learn how to calculate the cost of a transaction on Solana.

Every transaction consumes compute units and requires a transaction fee in
lamports to execute. The number of signatures included on a transaction
determines the base transaction fee (5000 lamports per signature).

<Tabs>
<Tab title="Kit">
<div className="sol-tab-label">Kit</div>

```ts
import {
  appendTransactionMessageInstructions,
  assertIsTransactionWithBlockhashLifetime,
  compileTransactionMessage,
  createClient,
  createTransactionMessage,
  estimateResourceLimitsFactory,
  generateKeyPairSigner,
  getBase64Decoder,
  getCompiledTransactionMessageEncoder,
  getSignatureFromTransaction,
  lamports,
  pipe,
  prependTransactionMessageInstructions,
  sendAndConfirmTransactionFactory,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signTransactionMessageWithSigners,
  type TransactionMessageBytesBase64,
} from "@solana/kit";
import { rpcAirdrop, solanaRpc } from "@solana/kit-plugin-rpc";
import { airdropPayer, payer } from "@solana/kit-plugin-signer";
import {
  getSetComputeUnitLimitInstruction,
  getSetComputeUnitPriceInstruction,
} from "@solana-program/compute-budget";
import { getAddMemoInstruction } from "@solana-program/memo";

// 1. Spin up a client with localhost RPC, fund the payer.
const signer = await generateKeyPairSigner();
const client = await createClient()
  .use(payer(signer))
  .use(
    solanaRpc({
      rpcUrl: "http://localhost:8899",
      rpcSubscriptionsUrl: "ws://localhost:8900",
    }),
  )
  .use(rpcAirdrop())
  .use(airdropPayer(lamports(1_000_000_000n)));
console.log("Create and fund account with address", signer.address);

// 2. Build a memo transaction manually so we can inspect its fee before sending.
const estimateResourceLimits = estimateResourceLimitsFactory({
  rpc: client.rpc,
});

const { value: latestBlockhash } = await client.rpc.getLatestBlockhash().send();
const transactionMessage = pipe(
  createTransactionMessage({ version: "legacy" }),
  (m) => setTransactionMessageFeePayerSigner(signer, m),
  (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
  (m) =>
    appendTransactionMessageInstructions(
      [
        getSetComputeUnitPriceInstruction({ microLamports: 5000n }),
        getAddMemoInstruction({ memo: "Hello, world!" }),
      ],
      m,
    ),
);

// 3. Estimate compute units and add a SetComputeUnitLimit instruction.
const { computeUnitLimit: estimatedComputeUnits } =
  await estimateResourceLimits(transactionMessage);
console.log(
  `Transaction is estimated to consume ${estimatedComputeUnits} compute units`,
);

const budgetedTransactionMessage = prependTransactionMessageInstructions(
  [getSetComputeUnitLimitInstruction({ units: estimatedComputeUnits })],
  transactionMessage,
);

// 4. Calculate the transaction fee with getFeeForMessage.
const base64EncodedMessage = pipe(
  budgetedTransactionMessage,
  compileTransactionMessage,
  getCompiledTransactionMessageEncoder().encode,
  getBase64Decoder().decode,
) as TransactionMessageBytesBase64;

const transactionCost = await client.rpc
  .getFeeForMessage(base64EncodedMessage)
  .send();
console.log(
  "Transaction is estimated to cost " + transactionCost.value + " lamports",
);

// 5. Sign and send.
const signedTx = await signTransactionMessageWithSigners(
  budgetedTransactionMessage,
);
assertIsTransactionWithBlockhashLifetime(signedTx);
const transactionSignature = getSignatureFromTransaction(signedTx);
console.log("Transaction Signature:", transactionSignature);

await sendAndConfirmTransactionFactory({
  rpc: client.rpc,
  rpcSubscriptions: client.rpcSubscriptions,
})(signedTx, { commitment: "confirmed" });
```

<div className="sol-run" data-run="cookbook/transactions/calculate-cost/cost" data-tab="Kit">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Create and fund account with address FYszPrjaiDEWJnmr4wg7FSgM4ze3E9d46YrYSqWizxEa
Transaction is estimated to consume 587 compute units
Transaction is estimated to cost 5000 lamports
Transaction Signature: 2TVyCEi4bwDw7m9n8y1nbUTq17YHjWre3tyY75EpPBn4e3AQvb1k7i4Wb3X91abmPehgNKXkYzmF7rari9ikGeMZ
```

</div>
</div>

</Tab>
<Tab title="Web3.js v3">
<div className="sol-tab-label">Web3.js v3</div>

```ts
import {
  ComputeBudgetProgram,
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
} from "@solana/web3.js";

// Connect to Solana network
const connection = new Connection("http://localhost:8899", "confirmed");

const { blockhash, lastValidBlockHeight } =
  await connection.getLatestBlockhash();

// Create keypairs for transaction
const sender = await Keypair.generate();
const recipient = await Keypair.generate();
console.log(`Created sender account: ${sender.publicKey.toString()}`);
console.log(`Created recipient account: ${recipient.publicKey.toString()}`);

// Request and confirm airdrop
const airdropSignature = await connection.requestAirdrop(
  sender.publicKey,
  LAMPORTS_PER_SOL,
);

await connection.confirmTransaction({
  signature: airdropSignature,
  blockhash,
  lastValidBlockHeight,
});

// Create a transfer instruction
const transferInstruction = SystemProgram.transfer({
  fromPubkey: sender.publicKey,
  toPubkey: recipient.publicKey,
  lamports: 1000000, // 0.001 SOL
});

// Create simulation instructions with placeholder compute unit limit
const simulationInstructions = [
  ComputeBudgetProgram.setComputeUnitLimit({
    units: 1_400_000, // High value for simulation
  }),
  ComputeBudgetProgram.setComputeUnitPrice({
    microLamports: 1n,
  }),
  transferInstruction,
];

// Create transaction for simulation
const simulationTransaction = new VersionedTransaction(
  new TransactionMessage({
    instructions: simulationInstructions,
    payerKey: sender.publicKey,
    recentBlockhash: blockhash,
  }).compileToV0Message(),
);

// Simulate transaction to get compute unit estimate
const simulationResponse = await connection.simulateTransaction(
  simulationTransaction,
);

const estimatedUnits = simulationResponse.value.unitsConsumed;
console.log(`Estimated compute units: ${estimatedUnits}`);

// Create final transaction with compute budget instructions
const computeUnitLimitInstruction = ComputeBudgetProgram.setComputeUnitLimit({
  units: Number(estimatedUnits),
});

const computeUnitPriceInstruction = ComputeBudgetProgram.setComputeUnitPrice({
  microLamports: 1n,
});

// Build transaction with all instructions
const messageV0 = new TransactionMessage({
  payerKey: sender.publicKey,
  recentBlockhash: blockhash,
  instructions: [
    computeUnitPriceInstruction,
    computeUnitLimitInstruction,
    transferInstruction,
  ],
}).compileToV0Message();

// Calculate fee
const fees = await connection.getFeeForMessage(messageV0);
console.log(`Transaction fee: ${fees.value} lamports`);

const transaction = new VersionedTransaction(messageV0);
await transaction.sign([sender]);

// Send and confirm transaction
const signature = await connection.sendTransaction(transaction);
console.log(`Transaction Signature: ${signature}`);
```

<div className="sol-run" data-run="cookbook/transactions/calculate-cost/cost" data-tab="Web3.js v3">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Created sender account: B3NE5BEMXdVcAZz8MCo6y5fBe4QTqUUXfTCjqfFzadpm
Created recipient account: GBcvRj7uY3wZL4ayQaFSkSiz4kTXkrvAt1JZUnzNugxg
Estimated compute units: 450
Transaction fee: 5000 lamports
Transaction Signature: 4FqbVrQHNwr2Qo6LZqpG3zx8zULqWn3jhtSFb2UF9enpuvKKEgQ59fqv6ZrdUC5jNPYe7bzjxZ5ddHZSLkB6ksBs
```

</div>
</div>

</Tab>
<Tab title="Rust">
<div className="sol-tab-label">Rust</div>

```rust
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
    native_token::LAMPORTS_PER_SOL, signature::Keypair, signer::Signer, transaction::Transaction,
};
use spl_memo_interface::{instruction::build_memo, v3::ID as MEMO_V3_PROGRAM_ID};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = RpcClient::new_with_commitment(
        String::from("http://localhost:8899"),
        CommitmentConfig::confirmed(),
    );

    let signer_keypair = Keypair::new();

    // Airdrop SOL to the signer account so it exists for simulation
    let airdrop_signature = client
        .request_airdrop(&signer_keypair.pubkey(), LAMPORTS_PER_SOL)
        .await?;

    loop {
        if client.confirm_transaction(&airdrop_signature).await? {
            break;
        }
    }

    let memo = String::from("Memo message to be logged in this transaction");
    let memo_ix = build_memo(
        &MEMO_V3_PROGRAM_ID,
        memo.as_bytes(),
        &[&signer_keypair.pubkey()],
    );

    let latest_blockhash = client.get_latest_blockhash().await?;
    let mut transaction = Transaction::new_with_payer(&[memo_ix], Some(&signer_keypair.pubkey()));
    transaction.sign(&[&signer_keypair], latest_blockhash);

    // Simulate transaction to estimate compute units
    let sim_result = client.simulate_transaction(&transaction).await?;

    println!("Simulated transaction: \n{:#?}", sim_result);

    println!(
        "Estimated compute units: \n{:#?}",
        sim_result.value.units_consumed
    );

    let tx_cost = client.get_fee_for_message(transaction.message()).await?;
    println!("Estimated transaction cost: {} lamports", tx_cost);

    Ok(())
}
```

<div className="sol-run" data-run="cookbook/transactions/calculate-cost/cost" data-tab="Rust">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Simulated transaction: 
Response {
    context: RpcResponseContext {
        slot: 438835825,
        api_version: Some(
            RpcApiVersion(
                Version {
                    major: 4,
                    minor: 1,
                    patch: 2,
                },
            ),
        ),
    },
    value: RpcSimulateTransactionResult {
        err: None,
        logs: Some(
            [
                "Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr invoke [1]",
                "Program log: Signed by:",
                "Program log: 6Jsq9CSi7NpWjzGY4PcorGom4V7VN3dgw7zqdDSY1vbq",
                "Program log: Memo (len 45)",
                "Program log: Memo message to be logged in this transaction",
                "Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr consumed 513 of 200000 compute units",
                "Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr success",
            ],
        ),
        accounts: None,
        units_consumed: Some(
            513,
        ),
        loaded_accounts_data_size: Some(
            2304,
        ),
        return_data: Some(
            UiTransactionReturnData {
                program_id: "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr",
                data: (
                    "",
                    Base64,
                ),
            },
        ),
        inner_instructions: None,
        replacement_blockhash: None,
    },
}
Estimated compute units: 
Some(
    513,
)
Estimated transaction cost: 5000 lamports
```

</div>
</div>

</Tab>
<Tab title="Python">
<div className="sol-tab-label">Python</div>

```py
import asyncio

from solana.rpc.async_api import AsyncClient
from solders.instruction import Instruction
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.pubkey import Pubkey

MEMO_PROGRAM_ID = Pubkey.from_string("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")


async def main():
    async with AsyncClient("http://localhost:8899") as client:
        payer = Keypair()

        memo_instruction = Instruction(MEMO_PROGRAM_ID, b"Hello, world!", [])
        blockhash = (await client.get_latest_blockhash()).value.blockhash
        message = MessageV0.try_compile(payer.pubkey(), [memo_instruction], [], blockhash)

        fee = (await client.get_fee_for_message(message)).value
        print(f"Transaction is estimated to cost {fee} lamports")


asyncio.run(main())
```

<div className="sol-run" data-run="cookbook/transactions/calculate-cost/cost" data-tab="Python">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction is estimated to cost 5000 lamports
```

</div>
</div>

</Tab>
<Tab title="Go">
<div className="sol-tab-label">Go</div>

```go
package main

import (
	"context"
	"fmt"

	"github.com/solana-foundation/solana-go/v2"
	"github.com/solana-foundation/solana-go/v2/programs/memo"
	"github.com/solana-foundation/solana-go/v2/rpc"
)

func main() {
	ctx := context.Background()
	client := rpc.New("http://localhost:8899")
	payer := solana.NewWallet()

	recent, err := client.GetLatestBlockhash(ctx, rpc.CommitmentFinalized)
	if err != nil {
		panic(err)
	}

	tx, err := solana.NewTransaction(
		[]solana.Instruction{
			memo.NewMemoInstruction([]byte("Hello, world!")).Build(),
		},
		recent.Value.Blockhash,
		solana.TransactionPayer(payer.PublicKey()),
	)
	if err != nil {
		panic(err)
	}

	fee, err := client.GetFeeForMessage(ctx, tx.Message.ToBase64(), rpc.CommitmentFinalized)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Transaction is estimated to cost %d lamports\n", *fee.Value)
}
```

<div className="sol-run" data-run="cookbook/transactions/calculate-cost/cost" data-tab="Go">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Transaction is estimated to cost 5000 lamports
```

</div>
</div>

</Tab>
<Tab title="Web3.js (legacy)">
<div className="sol-tab-label">Web3.js (legacy)</div>

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

```ts
import {
  ComputeBudgetProgram,
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
} from "@solana/web3.js";

// Connect to Solana network
const connection = new Connection("http://localhost:8899", "confirmed");

const { blockhash, lastValidBlockHeight } =
  await connection.getLatestBlockhash();

// Create keypairs for transaction
const sender = Keypair.generate();
const recipient = Keypair.generate();
console.log(`Created sender account: ${sender.publicKey.toString()}`);
console.log(`Created recipient account: ${recipient.publicKey.toString()}`);

// Request and confirm airdrop
const airdropSignature = await connection.requestAirdrop(
  sender.publicKey,
  LAMPORTS_PER_SOL,
);

await connection.confirmTransaction({
  signature: airdropSignature,
  blockhash,
  lastValidBlockHeight,
});

// Create a transfer instruction
const transferInstruction = SystemProgram.transfer({
  fromPubkey: sender.publicKey,
  toPubkey: recipient.publicKey,
  lamports: 1000000, // 0.001 SOL
});

// Create simulation instructions with placeholder compute unit limit
const simulationInstructions = [
  ComputeBudgetProgram.setComputeUnitLimit({
    units: 1_400_000, // High value for simulation
  }),
  ComputeBudgetProgram.setComputeUnitPrice({
    microLamports: 1n,
  }),
  transferInstruction,
];

// Create transaction for simulation
const simulationTransaction = new VersionedTransaction(
  new TransactionMessage({
    instructions: simulationInstructions,
    payerKey: sender.publicKey,
    recentBlockhash: blockhash,
  }).compileToV0Message(),
);

// Simulate transaction to get compute unit estimate
const simulationResponse = await connection.simulateTransaction(
  simulationTransaction,
);

const estimatedUnits = simulationResponse.value.unitsConsumed;
console.log(`Estimated compute units: ${estimatedUnits}`);

// Create final transaction with compute budget instructions
const computeUnitLimitInstruction = ComputeBudgetProgram.setComputeUnitLimit({
  units: estimatedUnits!,
});

const computeUnitPriceInstruction = ComputeBudgetProgram.setComputeUnitPrice({
  microLamports: 1n,
});

// Build transaction with all instructions
const messageV0 = new TransactionMessage({
  payerKey: sender.publicKey,
  recentBlockhash: blockhash,
  instructions: [
    computeUnitPriceInstruction,
    computeUnitLimitInstruction,
    transferInstruction,
  ],
}).compileToV0Message();

// Calculate fee
const fees = await connection.getFeeForMessage(messageV0);
console.log(`Transaction fee: ${fees.value} lamports`);

const transaction = new VersionedTransaction(messageV0);
transaction.sign([sender]);

// Send and confirm transaction
const signature = await connection.sendTransaction(transaction);
console.log(`Transaction Signature: ${signature}`);
```

<div className="sol-run" data-run="cookbook/transactions/calculate-cost/cost" data-tab="Web3.js (legacy)">
<div className="sol-run-bar"><button type="button" className="sol-run-btn">Run</button><span className="sol-run-note">Output from a local Surfpool network</span></div>
<div className="sol-run-out">

```text Output
Created sender account: 4eWK74S7mC1tpVwm3UVek7TmKacbeoS3WnqM8hFTVqYK
Created recipient account: D8zLFm3Rt8LyojsmhMAMWBkVqcKiLzaPMzv3JcJd5BuX
Estimated compute units: 450
Transaction fee: 5000 lamports
Transaction Signature: 2JHCEKRF87Xb8g7G8mM9doYtzF7DfqA4htZrKurwrMjvVNsknqUAMeLbrH8n11zBNuMHdfJZ4k4Pf8ohbDQgqPMQ
```

</div>
</div>

</Tab>
</Tabs>
