light_program_test/utils/
simulation.rs

1use solana_sdk::{
2    instruction::Instruction,
3    signature::{Keypair, Signer},
4    transaction::{Transaction, VersionedTransaction},
5};
6
7use crate::{program_test::LightProgramTest, Rpc};
8
9/// Simulate a transaction and return the compute units consumed.
10///
11/// This is a test utility function for measuring transaction costs.
12pub async fn simulate_cu(
13    rpc: &mut LightProgramTest,
14    payer: &Keypair,
15    instruction: &Instruction,
16) -> u64 {
17    let blockhash = rpc
18        .get_latest_blockhash()
19        .await
20        .expect("Failed to get latest blockhash")
21        .0;
22    let tx = Transaction::new_signed_with_payer(
23        std::slice::from_ref(instruction),
24        Some(&payer.pubkey()),
25        &[payer],
26        blockhash,
27    );
28    let simulate_tx = VersionedTransaction::from(tx);
29
30    let simulate_result = rpc
31        .context
32        .simulate_transaction(simulate_tx)
33        .unwrap_or_else(|err| panic!("Transaction simulation failed: {:?}", err));
34
35    simulate_result.meta.compute_units_consumed
36}