> ## 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.

# Transazioni

> Metodi per la gestione delle transazioni

## send_transaction

```rust
pub fn send_transaction(&mut self, tx: impl Into<VersionedTransaction>) -> Result<TransactionMetadata, FailedTransactionMetadata>
```

Esegue la transazione e modifica lo stato.

```rust
let tx = Transaction::new_signed_with_payer(
    &[instruction],
    Some(&payer.pubkey()),
    &[&payer],
    svm.latest_blockhash(),
);

match svm.send_transaction(tx) {
    Ok(meta) => {
        println!("Success! Signature: {}", meta.signature);
        println!("Compute units: {}", meta.compute_units_consumed);
        println!("Fee: {} lamports", meta.fee);
    }
    Err(e) => {
        println!("Failed: {:?}", e.err);
        println!("Logs: {:?}", e.meta.logs);
    }
}
```

## simulate_transaction

```rust
pub fn simulate_transaction(&self, tx: impl Into<VersionedTransaction>) -> Result<SimulatedTransactionInfo, FailedTransactionMetadata>
```

Simula la transazione senza modificare lo stato.

Restituisce `SimulatedTransactionInfo`, che contiene:

- `meta`: metadati della transazione (log, compute unit, firma, ecc.)
- `post_accounts`: stati degli account dopo la simulazione

```rust
// State before simulation
let balance_before = svm.get_balance(&pubkey).unwrap_or(0);

// Simulate transaction
let result = svm.simulate_transaction(tx.clone());

// State unchanged
assert_eq!(svm.get_balance(&pubkey).unwrap_or(0), balance_before);

// Check simulation result
if let Ok(sim_info) = result {
    println!("Would succeed");
    println!("Compute units: {}", sim_info.meta.compute_units_consumed);

    // Can inspect post_accounts to see what would change
    // (needs `use solana_sdk::account::ReadableAccount;` for `.lamports()`)
    for (pubkey, account) in sim_info.post_accounts {
        println!("Account {} would have {} lamports", pubkey, account.lamports());
    }

    // Safe to send
    svm.send_transaction(tx).unwrap();
}
```

## Quando usare la simulazione

Usa `simulate_transaction()` per:

- Testare la validità della transazione senza modificare lo stato
- Verificare il consumo di compute unit
- Verificare i log della transazione senza eseguirne il commit
- Testare i percorsi di gestione degli errori

```rust
// Test if transaction would succeed
let result = svm.simulate_transaction(tx.clone());

match result {
    Ok(sim_info) => {
        println!("Would succeed");
        println!("Compute units: {}", sim_info.meta.compute_units_consumed);

        // Now execute for real
        svm.send_transaction(tx).unwrap();
    }
    Err(e) => {
        println!("Would fail: {:?}", e.err);
        // Don't send transaction
    }
}
```

## Test dei casi di errore

Qui `invalid_tx` viene pagata da un account che non è in grado di coprire la commissione. Un pagatore
che detiene solo 1.000 lamport fallisce con `InsufficientFundsForFee`; un pagatore che
non esiste affatto fallisce prima, con `AccountNotFound`.

```rust
use solana_sdk::{account::Account, transaction::TransactionError};

// A payer with too few lamports to pay the fee
let poor_payer = Keypair::new();
svm.set_account(poor_payer.pubkey(), Account {
    lamports: 1_000,
    data: vec![],
    owner: Pubkey::default(),
    executable: false,
    rent_epoch: 0,
}).unwrap();

let invalid_tx = Transaction::new_signed_with_payer(
    &[instruction],
    Some(&poor_payer.pubkey()),
    &[&poor_payer],
    svm.latest_blockhash(),
);

// Simulate expected failure
let result = svm.simulate_transaction(invalid_tx);
assert!(result.is_err());

match result.unwrap_err().err {
    TransactionError::InsufficientFundsForFee | TransactionError::AccountNotFound => {
        println!("Expected error occurred");
    }
    _ => panic!("Unexpected error"),
}
```

## Lo stato rimane invariato

```rust
let balance_before = svm.get_balance(&pubkey).unwrap_or(0);

// Simulate multiple times
for _ in 0..10 {
    svm.simulate_transaction(tx.clone()).unwrap();
}

// Balance unchanged
assert_eq!(svm.get_balance(&pubkey).unwrap_or(0), balance_before);
```

## Metadati della transazione

`send_transaction()` restituisce direttamente `TransactionMetadata`, mentre
`simulate_transaction()` restituisce `SimulatedTransactionInfo`, che contiene
`meta: TransactionMetadata`:

```rust
pub struct TransactionMetadata {
    pub signature: Signature,
    pub logs: Vec<String>,
    pub inner_instructions: InnerInstructionsList,
    pub compute_units_consumed: u64,
    pub return_data: TransactionReturnData,
    pub fee: u64,
    pub loaded_accounts_data_size: u32,
}
```

### Accesso ai dati della transazione

```rust
let result = svm.send_transaction(tx).unwrap();

// Signature
println!("Signature: {}", result.signature);

// Logs
for log in &result.logs {
    println!("{}", log);
}

// Compute units
println!("CU consumed: {}", result.compute_units_consumed);

// Return data
if !result.return_data.data.is_empty() {
    println!("Program returned: {:?}", result.return_data.data);
}

// Inner instructions (CPIs)
for inner in &result.inner_instructions {
    println!("CPI: {:?}", inner);
}

// Transaction fee paid by fee payer
println!("Fee paid: {} lamports", result.fee);
```

## get_transaction

```rust
pub fn get_transaction(&self, signature: &Signature) -> Option<&TransactionResult>
```

Dove
`TransactionResult = Result<TransactionMetadata, FailedTransactionMetadata>`.

Interroga una transazione dalla cronologia. `LiteSVM::new()` conserva per impostazione predefinita le ultime 32
transazioni; chiama `with_transaction_history(n)` per conservarne di più.
Con `with_transaction_history(0)` la cronologia è disattivata e `get_transaction`
restituisce sempre `None`.

```rust
let mut svm = LiteSVM::new()
    .with_transaction_history(100);

let result = svm.send_transaction(tx).unwrap();
let signature = result.signature;

// Query later
if let Some(tx_result) = svm.get_transaction(&signature) {
    match tx_result {
        Ok(meta) => println!("Found: {:?}", meta),
        Err(e) => println!("Failed: {:?}", e.err),
    }
}
```

## latest_blockhash

```rust
pub fn latest_blockhash(&self) -> Hash
```

Ottiene il blockhash corrente per le transazioni.

```rust
let blockhash = svm.latest_blockhash();

let tx = Transaction::new_signed_with_payer(
    &[instruction],
    Some(&payer.pubkey()),
    &[&payer],
    blockhash,
);
```

## expire_blockhash

```rust
pub fn expire_blockhash(&mut self)
```

Forza la scadenza del blockhash corrente.

```rust
let old_hash = svm.latest_blockhash();
svm.expire_blockhash();
let new_hash = svm.latest_blockhash();

assert_ne!(old_hash, new_hash);

// Transactions with old_hash will now fail
```

## Pattern comuni

### Validare prima di eseguire

```rust
// Simulate first to check validity
if svm.simulate_transaction(tx.clone()).is_ok() {
    // Execute if simulation passes
    svm.send_transaction(tx).unwrap();
} else {
    println!("Transaction would fail, skipping execution");
}
```

### Monitorare le compute unit

```rust
let result = svm.send_transaction(tx).unwrap();

// Assert within budget
assert!(
    result.compute_units_consumed < 100_000,
    "Transaction used too many compute units: {}",
    result.compute_units_consumed
);
```

### Controllare i log della transazione

```rust
let result = svm.send_transaction(tx).unwrap();

// Check for specific log messages
assert!(result.logs.iter().any(|log|
    log.contains("Transfer successful")
));
```
