트랜잭션 전송
TransactionHelpers 트레이트는 instruction을 전송하고
결과를 분석하는 편리한 메서드를 제공합니다.
단일 Instruction 전송
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_send_instruction() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
// Create a transfer instruction
let transfer_ix = system_instruction::transfer(
&alice.pubkey(),
&bob.pubkey(),
LAMPORTS_PER_SOL,
);
// Send and get result (returns Result<TransactionResult, TransactionError>)
let result = svm.send_instruction(transfer_ix, &[&alice]).unwrap();
// Assert it succeeded
result.assert_success();
}
여러 Instruction 전송
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_send_multiple_instructions() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
let carol = svm.create_funded_account(0).unwrap();
// Create multiple transfer instructions
let instructions = vec![
system_instruction::transfer(&alice.pubkey(), &bob.pubkey(), LAMPORTS_PER_SOL),
system_instruction::transfer(&alice.pubkey(), &carol.pubkey(), LAMPORTS_PER_SOL),
];
// Send all in one transaction
let result = svm.send_instructions(&instructions, &[&alice]).unwrap();
result.assert_success();
}
TransactionResult
send_instruction 및 send_instructions 메서드는 트랜잭션 메타데이터를
유용한 테스트 유틸리티로 감싼 TransactionResult를 반환합니다.
성공 검증
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_assert_success() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
let ix = system_instruction::transfer(&alice.pubkey(), &bob.pubkey(), LAMPORTS_PER_SOL);
let result = svm.send_instruction(ix, &[&alice]).unwrap();
// Panics with detailed logs if the transaction failed
result.assert_success();
}
assert_success()는 트랜잭션이 실패하면 전체 트랜잭션 로그와 함께 panic을 발생시키므로
디버깅이 훨씬 쉬워집니다.실패 검증
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_assert_failure() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(1 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
// Try to transfer more than Alice has
let ix = system_instruction::transfer(
&alice.pubkey(),
&bob.pubkey(),
100 * LAMPORTS_PER_SOL, // Alice only has 1 SOL
);
let result = svm.send_instruction(ix, &[&alice]).unwrap();
// This should fail
result.assert_failure();
}
특정 오류 검증
assert_log_error는 트랜잭션 로그에서 메시지를 확인합니다. 오류 자체
(예: InstructionError(0, Custom(1)))와 일치하는지 확인하려면 로그가 아닌 오류 문자열과
비교하는 assert_error를 사용하세요:
result.assert_error("InstructionError");
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_assert_error() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(1 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
let ix = system_instruction::transfer(
&alice.pubkey(),
&bob.pubkey(),
100 * LAMPORTS_PER_SOL,
);
let result = svm.send_instruction(ix, &[&alice]).unwrap();
// Assert a specific message is present in the transaction logs
result.assert_log_error("insufficient lamports");
}
오류 코드 검증
커스텀 프로그램 오류의 경우,assert_error로 오류의
Custom(<code>) 부분을 검증합니다:
// Assert a specific custom error code from your program
result.assert_error("Custom(6000)");
litesvm-utils 0.4.0에서는 assert_error_code를 사용하지 마세요. 이 함수는 오류에서
custom program error: 0x…를 찾지만, 실제 오류는
InstructionError(0, Custom(6000)) 형태이므로 항상 panic이 발생합니다. 대신
assert_error("Custom(6000)")를 사용하거나, Anchor
프로그램의 경우 assert_anchor_error를 사용하세요.Anchor 오류 검증
Anchor 프로그램의 경우 오류 이름으로 검증합니다:// Assert an Anchor-specific error
result.assert_anchor_error("InsufficientFunds");
트랜잭션 검사
트랜잭션 로그 확인
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_check_logs() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
let ix = system_instruction::transfer(&alice.pubkey(), &bob.pubkey(), LAMPORTS_PER_SOL);
let result = svm.send_instruction(ix, &[&alice]).unwrap();
// Check if a specific message is in the logs
if result.has_log("Transfer") {
println!("Found transfer log!");
}
// Find a log matching a pattern
if let Some(log) = result.find_log("Program") {
println!("Found log: {}", log);
}
// Get all logs
let logs = result.logs();
for log in logs {
println!("{}", log);
}
}
디버깅을 위한 로그 출력
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_print_logs() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
let ix = system_instruction::transfer(&alice.pubkey(), &bob.pubkey(), LAMPORTS_PER_SOL);
let result = svm.send_instruction(ix, &[&alice]).unwrap();
// Print formatted logs for debugging
result.print_logs();
}
컴퓨트 유닛 확인
use litesvm_utils::{LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_compute_units() {
let mut svm = LiteSVM::new();
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
let ix = system_instruction::transfer(&alice.pubkey(), &bob.pubkey(), LAMPORTS_PER_SOL);
let result = svm.send_instruction(ix, &[&alice]).unwrap();
let compute_units = result.compute_units();
println!("Compute units consumed: {}", compute_units);
// Assert compute usage is within expected bounds
assert!(compute_units < 10_000, "Transaction used too many compute units");
}
컴퓨트 유닛을 모니터링하면 최적화에 도움이 됩니다. Solana는
트랜잭션당 컴퓨트 유닛을 140만 개로 제한하며, 사용량이 많을수록 비용이 더 많이 듭니다.
전체 예제
다음은 트랜잭션 헬퍼를 보여 주는 종합 예제입니다:use litesvm_utils::{AssertionHelpers, LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;
#[test]
fn test_transaction_workflow() {
let mut svm = LiteSVM::new();
// Setup accounts
let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
let bob = svm.create_funded_account(0).unwrap();
// Test successful transfer
let transfer_ix = system_instruction::transfer(
&alice.pubkey(),
&bob.pubkey(),
2 * LAMPORTS_PER_SOL,
);
let result = svm.send_instruction(transfer_ix, &[&alice]).unwrap();
// Verify success
result.assert_success();
// Check compute usage
let cu = result.compute_units();
println!("Transfer used {} compute units", cu);
// Verify balances
svm.assert_sol_balance(&bob.pubkey(), 2 * LAMPORTS_PER_SOL);
// Test expected failure
let bad_transfer = system_instruction::transfer(
&alice.pubkey(),
&bob.pubkey(),
100 * LAMPORTS_PER_SOL, // More than Alice has
);
let fail_result = svm.send_instruction(bad_transfer, &[&alice]).unwrap();
fail_result.assert_failure();
// Print logs for debugging
fail_result.print_logs();
println!("Transaction workflow test passed!");
}
오류 유형
TransactionError 열거형은 구조화된 오류 정보를 제공합니다:
| 베리언트 | 설명 |
|---|---|
ExecutionFailed(String) | 메시지와 함께 트랜잭션 실행에 실패했습니다 |
BuildError(String) | 트랜잭션을 빌드하지 못했습니다 |
AssertionFailed(String) | 결과에 대한 검증에 실패했습니다 |