The v1 transaction 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/kitgives them separate setters and enforces the split in the type system:setTransactionMessagePriorityFeeLamportsaccepts only v1 messages, andsetTransactionMessageComputeUnitPriceaccepts onlylegacyand0. The other resource limits are version-agnostic —setTransactionMessageComputeUnitLimit,setTransactionMessageLoadedAccountsDataSizeLimit, andsetTransactionMessageHeapSizetake a message of any version.
- Kit
- Web3.js v3
- Rust
- Python
- Go
- Web3.js (legacy)
Kit
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}`);
Output from a local Surfpool network
Output
Transaction Signature: 3YCvs9JdxmAMJ3QbBaThH4PV1tdrgwS944Gd7vzRHa7NyDS1qKJErNXXZn72GnDd9LbMtkY1nMhYFP4gFMBuhELc
Web3.js v3
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}`);
Output from a local Surfpool network
Output
Transaction Signature: 5BzbCsgBDvSP1D2tH78N9W3CfdNaoynMS3vm6uPfJXRejErbmMqe9eUCmSWrrxxWpyJgRkRMTwgcRPdEZcrsgWQk
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(())
}
Output from a local Surfpool network
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,
],
},
],
},
}
Python
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())
Output from a local Surfpool network
Output
Transaction Signature: 4zFrHoXJqnsDvQX6MTJeBAPBcTZ1TZixt511NXwMGFiWgJXMxADckpGinrzhzZwyfVn9xoFUPEQ7bBqvdcJmJRkT
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)
}
Output from a local Surfpool network
Output
Transaction Signature: 4E8NNGMMrUEEbMAi2hEHMDyGC661APS7k5RwbWuFkGUVm4qbZwhJ3ogbTG4qNuL1L9P7ibEXzPURqdwoJzW9FdsP
Web3.js (legacy)
@solana/web3.js 1.x is no longer actively maintainedIt receives critical fixes only. Use Kit for new code. To migrate existing code, follow the Kit upgrade guide, or the web3.js v3 migration guide 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.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}`);
Output from a local Surfpool network
Output
Transaction Signature: 5wKeSB5uG6x56YvEvzsYqg3FBrGjJKZp42FKGSQCJkFdbXx8jfikhEgZ39kfV6WhRPgKoB1Q8vQ1YCavB6V814Ld