- Kit
- Web3.js v3
- Rust
- Python
- Go
- Web3.js (legacy)
Kit
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" });
Output from a local Surfpool network
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
Web3.js v3
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}`);
Output from a local Surfpool network
Output
Created sender account: B3NE5BEMXdVcAZz8MCo6y5fBe4QTqUUXfTCjqfFzadpm
Created recipient account: GBcvRj7uY3wZL4ayQaFSkSiz4kTXkrvAt1JZUnzNugxg
Estimated compute units: 450
Transaction fee: 5000 lamports
Transaction Signature: 4FqbVrQHNwr2Qo6LZqpG3zx8zULqWn3jhtSFb2UF9enpuvKKEgQ59fqv6ZrdUC5jNPYe7bzjxZ5ddHZSLkB6ksBs
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(())
}
Output from a local Surfpool network
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
Python
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())
Output from a local Surfpool network
Output
Transaction is estimated to cost 5000 lamports
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)
}
Output from a local Surfpool network
Output
Transaction is estimated to cost 5000 lamports
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";
// 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}`);
Output from a local Surfpool network
Output
Created sender account: 4eWK74S7mC1tpVwm3UVek7TmKacbeoS3WnqM8hFTVqYK
Created recipient account: D8zLFm3Rt8LyojsmhMAMWBkVqcKiLzaPMzv3JcJd5BuX
Estimated compute units: 450
Transaction fee: 5000 lamports
Transaction Signature: 2JHCEKRF87Xb8g7G8mM9doYtzF7DfqA4htZrKurwrMjvVNsknqUAMeLbrH8n11zBNuMHdfJZ4k4Pf8ohbDQgqPMQ