> ## 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 Add Priority Fees to a Transaction

> Learn how to increase your transaction priority with priority fees on Solana.

A priority fee is an optional fee paid to increase the chance that the current
leader processes your transaction.

To add a priority fee to a transaction, invoke instructions from the
[Compute Budget Program](https://github.com/solana-program/compute-budget).

> The
> [v1 transaction format](/developers/docs/core/transactions/versioned-transactions#v1-format)
> handles this differently: ComputeBudget instructions are ignored (they execute
> as no-ops), and the priority fee is set directly in the message config as a
> **total in lamports** rather than a price in micro-lamports per compute unit.
>
> Because those are different quantities, `@solana/kit` gives them separate
> setters and enforces the split in the type system:
> `setTransactionMessagePriorityFeeLamports` accepts only v1 messages, and
> `setTransactionMessageComputeUnitPrice` accepts only `legacy` and `0`. The
> other resource limits are version-agnostic —
> `setTransactionMessageComputeUnitLimit`,
> `setTransactionMessageLoadedAccountsDataSizeLimit`, and
> `setTransactionMessageHeapSize` take a message of any version.

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

```ts
import {
  createClient,
  generateKeyPairSigner,
  lamports,
  type MicroLamports,
} from "@solana/kit";
import { rpcAirdrop, solanaRpc } from "@solana/kit-plugin-rpc";
import { airdropPayer, payer } from "@solana/kit-plugin-signer";
import { getAddMemoInstruction } from "@solana-program/memo";

// Create and fund an account
const keypairSigner = await generateKeyPairSigner();

// Configure priority fees on the client. The transaction planner will add a
// SetComputeUnitPrice instruction, and the executor will simulate the
// transaction to estimate compute units and add a SetComputeUnitLimit.
const client = await createClient()
  .use(payer(keypairSigner))
  .use(
    solanaRpc({
      rpcUrl: "http://localhost:8899",
      rpcSubscriptionsUrl: "ws://localhost:8900",
      transactionConfig: {
        microLamportsPerComputeUnit: 5000n as MicroLamports,
        version: "legacy",
      },
    }),
  )
  .use(rpcAirdrop())
  .use(airdropPayer(lamports(1_000_000_000n)));

const memoInstruction = getAddMemoInstruction({ memo: "Hello, world!" });

const { context } = await client.sendTransaction([memoInstruction]);
console.log(`Transaction Signature: ${context.signature}`);
```

<div className="sol-run" data-run="cookbook/transactions/add-priority-fees/priority" 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
Transaction Signature: 3YCvs9JdxmAMJ3QbBaThH4PV1tdrgwS944Gd7vzRHa7NyDS1qKJErNXXZn72GnDd9LbMtkY1nMhYFP4gFMBuhELc
```

</div>
</div>

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

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

// Create connection
const connection = new Connection("http://localhost:8899", "confirmed");

// Generate keypairs
const sender = await Keypair.generate();
const recipient = await Keypair.generate();

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

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

// Create instructions
const instructions = [
  // Set compute unit limit (1M units)
  ComputeBudgetProgram.setComputeUnitLimit({
    units: 1000000,
  }),
  // Set priority fee (1 microLamports per compute unit)
  ComputeBudgetProgram.setComputeUnitPrice({
    microLamports: 1,
  }),
  // Transfer 0.01 SOL
  SystemProgram.transfer({
    fromPubkey: sender.publicKey,
    toPubkey: recipient.publicKey,
    lamports: 10000000,
  }),
];

// Get latest blockhash for transaction
const latestBlockhash = await connection.getLatestBlockhash();

// Create transaction using modern VersionedTransaction
const messageV0 = new TransactionMessage({
  payerKey: sender.publicKey,
  recentBlockhash: latestBlockhash.blockhash,
  instructions,
}).compileToV0Message();

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

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

<div className="sol-run" data-run="cookbook/transactions/add-priority-fees/priority" 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
Transaction Signature: 5BzbCsgBDvSP1D2tH78N9W3CfdNaoynMS3vm6uPfJXRejErbmMqe9eUCmSWrrxxWpyJgRkRMTwgcRPdEZcrsgWQk
```

</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_compute_budget_interface::ComputeBudgetInstruction;
use solana_sdk::{
    native_token::LAMPORTS_PER_SOL, signature::Keypair, signer::Signer, transaction::Transaction,
};
use solana_system_interface::instruction::transfer;

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

    let sender = Keypair::new();
    let recipient = Keypair::new();

    let airdrop_signature = client
        .request_airdrop(&sender.pubkey(), 5 * LAMPORTS_PER_SOL)
        .await?;

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

    let set_compute_limit_ix = ComputeBudgetInstruction::set_compute_unit_limit(1_000_000);
    let set_compute_price_ix = ComputeBudgetInstruction::set_compute_unit_price(1);

    let transfer_ix = transfer(&sender.pubkey(), &recipient.pubkey(), LAMPORTS_PER_SOL);

    let latest_blockhash = client.get_latest_blockhash().await?;
    let mut transaction = Transaction::new_with_payer(
        &[set_compute_limit_ix, set_compute_price_ix, transfer_ix],
        Some(&sender.pubkey()),
    );
    transaction.sign(&[&sender], latest_blockhash);

    let signature = client.send_and_confirm_transaction(&transaction).await?;

    println!("Signature: {}", signature);
    println!("{:#?}", transaction);

    Ok(())
}
```

<div className="sol-run" data-run="cookbook/transactions/add-priority-fees/priority" 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
Signature: caFfKUEufhzkr9qnvLkXmSuTiUCDeHK15e5wgBRn1wTF7uQP8FkLqPqobwH3caPNPdijPYMHuTwkumrCSfZWF5b
Transaction {
    signatures: [
        caFfKUEufhzkr9qnvLkXmSuTiUCDeHK15e5wgBRn1wTF7uQP8FkLqPqobwH3caPNPdijPYMHuTwkumrCSfZWF5b,
    ],
    message: Message {
        header: MessageHeader {
            num_required_signatures: 1,
            num_readonly_signed_accounts: 0,
            num_readonly_unsigned_accounts: 2,
        },
        account_keys: [
            HVssPZ6RLugqgk7dk8SYvG8Hg14fKvD4R6ySD8exs6sT,
            DwdQDbz1L5khUeDhPeFH7davCurz7ZNLrNwqXV4ay9eY,
            11111111111111111111111111111111,
            ComputeBudget111111111111111111111111111111,
        ],
        recent_blockhash: SURFNETxSAFEHASHxxxxxxxxxxxxxxxxxxxxxxxxxa8,
        instructions: [
            CompiledInstruction {
                program_id_index: 3,
                accounts: [],
                data: [
                    2,
                    64,
                    66,
                    15,
                    0,
                ],
            },
            CompiledInstruction {
                program_id_index: 3,
                accounts: [],
                data: [
                    3,
                    1,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                ],
            },
            CompiledInstruction {
                program_id_index: 2,
                accounts: [
                    0,
                    1,
                ],
                data: [
                    2,
                    0,
                    0,
                    0,
                    0,
                    202,
                    154,
                    59,
                    0,
                    0,
                    0,
                    0,
                ],
            },
        ],
    },
}
```

</div>
</div>

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

```py
import asyncio

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solders.compute_budget import set_compute_unit_limit, set_compute_unit_price
from solders.instruction import Instruction
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.pubkey import Pubkey
from solders.transaction import VersionedTransaction

MEMO_PROGRAM_ID = Pubkey.from_string("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")


async def main():
    async with AsyncClient("http://localhost:8899", commitment=Confirmed) as client:
        sender = Keypair()
        airdrop = await client.request_airdrop(sender.pubkey(), 1_000_000_000)
        await client.confirm_transaction(airdrop.value)

        instructions = [
            set_compute_unit_limit(200_000),  # max compute units the transaction may use
            set_compute_unit_price(5_000),  # priority fee in micro-lamports per compute unit
            Instruction(MEMO_PROGRAM_ID, b"Hello, world!", []),
        ]

        blockhash = (await client.get_latest_blockhash()).value.blockhash
        message = MessageV0.try_compile(sender.pubkey(), instructions, [], blockhash)
        transaction = VersionedTransaction(message, [sender])

        signature = (await client.send_transaction(transaction)).value
        print("Transaction Signature:", signature)


asyncio.run(main())
```

<div className="sol-run" data-run="cookbook/transactions/add-priority-fees/priority" 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 Signature: 4zFrHoXJqnsDvQX6MTJeBAPBcTZ1TZixt511NXwMGFiWgJXMxADckpGinrzhzZwyfVn9xoFUPEQ7bBqvdcJmJRkT
```

</div>
</div>

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

```go
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/solana-foundation/solana-go/v2"
	computebudget "github.com/solana-foundation/solana-go/v2/programs/compute-budget"
	"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")

	sender := solana.NewWallet()

	// Fund the sender so it can pay the transaction fee.
	_, err := client.RequestAirdrop(ctx, sender.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}
	time.Sleep(2 * time.Second)

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

	tx, err := solana.NewTransaction(
		[]solana.Instruction{
			// Max compute units the transaction may use.
			computebudget.NewSetComputeUnitLimitInstruction(200_000).Build(),
			// Priority fee in micro-lamports per compute unit.
			computebudget.NewSetComputeUnitPriceInstruction(5_000).Build(),
			memo.NewMemoInstruction([]byte("Hello, world!")).Build(),
		},
		recent.Value.Blockhash,
		solana.TransactionPayer(sender.PublicKey()),
	)
	if err != nil {
		panic(err)
	}
	tx.Sign(func(solana.PublicKey) *solana.PrivateKey { return &sender.PrivateKey })

	sig, err := client.SendTransactionWithOpts(ctx, tx, rpc.TransactionOpts{
		PreflightCommitment: rpc.CommitmentConfirmed,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("Transaction Signature:", sig)
}
```

<div className="sol-run" data-run="cookbook/transactions/add-priority-fees/priority" 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 Signature: 4E8NNGMMrUEEbMAi2hEHMDyGC661APS7k5RwbWuFkGUVm4qbZwhJ3ogbTG4qNuL1L9P7ibEXzPURqdwoJzW9FdsP
```

</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 highlight={34-41}
import {
  ComputeBudgetProgram,
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
} from "@solana/web3.js";

// Create connection
const connection = new Connection("http://localhost:8899", "confirmed");

// Generate keypairs
const sender = Keypair.generate();
const recipient = Keypair.generate();

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

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

// Create instructions
const instructions = [
  // Set compute unit limit (1M units)
  ComputeBudgetProgram.setComputeUnitLimit({
    units: 1000000,
  }),
  // Set priority fee (1 microLamports per compute unit)
  ComputeBudgetProgram.setComputeUnitPrice({
    microLamports: 1,
  }),
  // Transfer 0.01 SOL
  SystemProgram.transfer({
    fromPubkey: sender.publicKey,
    toPubkey: recipient.publicKey,
    lamports: 10000000,
  }),
];

// Get latest blockhash for transaction
const latestBlockhash = await connection.getLatestBlockhash();

// Create transaction using modern VersionedTransaction
const messageV0 = new TransactionMessage({
  payerKey: sender.publicKey,
  recentBlockhash: latestBlockhash.blockhash,
  instructions,
}).compileToV0Message();

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

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

<div className="sol-run" data-run="cookbook/transactions/add-priority-fees/priority" 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
Transaction Signature: 5wKeSB5uG6x56YvEvzsYqg3FBrGjJKZp42FKGSQCJkFdbXx8jfikhEgZ39kfV6WhRPgKoB1Q8vQ1YCavB6V814Ld
```

</div>
</div>

</Tab>
</Tabs>
