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

# Guida rapida

> Scopri come usare il crate litesvm-utils per semplificare il testing dei programmi Solana

[Visualizza `litesvm-utils` su crates.io](https://crates.io/crates/litesvm-utils)

## Installazione

Assicurati di avere tutte le dipendenze necessarie:

```bash
cargo add --dev litesvm-utils solana-sdk@3 spl-token
cargo add --dev solana-system-interface@2 --features bincode
```

<Warning>
  `litesvm-utils` fissa la propria versione di `litesvm` e la riesporta. Importa
  `LiteSVM` da `litesvm_utils` (come negli esempi seguenti) e non aggiungere una
  dipendenza `litesvm` separata, altrimenti finirai con due copie incompatibili
  del crate.
</Warning>

## Che cos'è litesvm-utils?

Il crate `litesvm-utils` fornisce trait helper e utility essenziali che
semplificano il testing dei programmi Solana. Riduce il boilerplate tipico dei test da più di 30
righe a codice minimo e leggibile grazie ad API ergonomiche.

<Steps>
<Step title="Trait TestHelpers">
- Crea account finanziati con una singola chiamata di metodo
- Configura facilmente token mint e token account
- Deriva i PDA senza boilerplate
- Gestisci gli slot per i test basati sul tempo
</Step>

<Step title="Trait AssertionHelpers">
- Verifica lo stato degli account (esistenza, chiusura, proprietario)
- Verifica i saldi dei token e le supply dei mint
- Controlla i saldi in SOL
- Convalida la lunghezza dei dati degli account
</Step>

<Step title="Trait TransactionHelpers">
- Esegui istruzioni con una gestione avanzata dei risultati
- Verifica il successo o il fallimento delle transazioni
- Controlla la presenza di errori specifici
- Ispeziona i log delle transazioni e le compute unit
</Step>

<Step title="LiteSVMBuilder">
- Pattern builder fluente per configurare l'ambiente di test
- Distribuisci i programmi con il method chaining
- Comodi metodi factory statici
</Step>
</Steps>

## Esempio rapido

Ecco un esempio completo che mostra la potenza di litesvm-utils:

```rust
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_with_utils() {
    let mut svm = LiteSVM::new();

    // Create funded accounts in one line
    let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
    let bob = svm.create_funded_account(0).unwrap();

    // Create a token mint easily
    let mint = svm.create_token_mint(&alice, 9).unwrap();

    // Create an associated token account (returns Pubkey)
    let alice_ata = svm.create_associated_token_account(&mint.pubkey(), &alice).unwrap();

    // Mint tokens
    svm.mint_to(&mint.pubkey(), &alice_ata, &alice, 1000).unwrap();

    // Assert balances
    svm.assert_token_balance(&alice_ata, 1000);

    // Execute a SOL transfer with rich result handling
    let transfer_ix = system_instruction::transfer(
        &alice.pubkey(),
        &bob.pubkey(),
        LAMPORTS_PER_SOL,
    );

    let result = svm.send_instruction(transfer_ix, &[&alice]).unwrap();
    result.assert_success();

    // Verify the transfer
    svm.assert_sol_balance(&bob.pubkey(), LAMPORTS_PER_SOL);

    // Bob now has SOL, so he can pay for his own associated token account
    let bob_ata = svm.create_associated_token_account(&mint.pubkey(), &bob).unwrap();
    svm.assert_token_balance(&bob_ata, 0);
}
```

## Vantaggi principali

### Prima di litesvm-utils

```rust
// Creating a funded account manually
let keypair = Keypair::new();
let airdrop_tx = Transaction::new_signed_with_payer(
    &[system_instruction::transfer(
        &payer.pubkey(),
        &keypair.pubkey(),
        lamports,
    )],
    Some(&payer.pubkey()),
    &[&payer],
    svm.latest_blockhash(),
);
svm.send_transaction(airdrop_tx).unwrap();
```

### Dopo litesvm-utils

```rust
// One line to create a funded account
let keypair = svm.create_funded_account(lamports).unwrap();
```

## Panoramica dei trait

### TestHelpers

| Metodo                                         | Restituisce                | Descrizione                         |
| ---------------------------------------------- | ---------------------- | ----------------------------------- |
| `create_funded_account(lamports)`              | `Result<Keypair>`      | Crea un keypair e lo finanzia      |
| `create_funded_accounts(count, lamports)`      | `Result<Vec<Keypair>>` | Crea più keypair finanziati    |
| `create_token_mint(authority, decimals)`       | `Result<Keypair>`      | Crea un token mint SPL           |
| `create_token_account(mint, owner)`            | `Result<Keypair>`      | Crea un token account standard     |
| `create_associated_token_account(mint, owner)` | `Result<Pubkey>`       | Crea un ATA e ne restituisce l'indirizzo |
| `mint_to(mint, account, authority, amount)`    | `Result<()>`           | Conia token su un account          |
| `derive_pda(seeds, program_id)`                | `(Pubkey, u8)`         | Deriva un PDA con bump seed        |
| `get_pda(seeds, program_id)`                   | `Pubkey`               | Ottiene solo l'indirizzo del PDA           |
| `get_pda_with_bump(seeds, program_id)`         | `(Pubkey, u8)`         | Alias di `derive_pda`              |
| `get_current_slot()`                           | `u64`                  | Restituisce lo slot corrente                |
| `advance_slot(slots)`                          | `()`                   | Fa avanzare il tempo di N slot            |

### AssertionHelpers

| Metodo                                  | Descrizione                                                            |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `assert_account_exists(pubkey)`         | Va in panic se l'account non esiste                                       |
| `assert_account_closed(pubkey)`         | Va in panic a meno che l'account non sia assente, oppure abbia zero lamport e nessun dato |
| `assert_token_balance(account, amount)` | Verifica il saldo dei token                                                 |
| `assert_sol_balance(pubkey, lamports)`  | Verifica il saldo in SOL                                                   |
| `assert_mint_supply(mint, supply)`      | Verifica la supply totale del mint                                             |
| `assert_account_owner(pubkey, owner)`   | Verifica il proprietario dell'account                                                 |
| `assert_account_data_len(pubkey, len)`  | Verifica la lunghezza dei dati                                                   |

### TransactionHelpers

| Metodo                            | Restituisce                                       | Descrizione                           |
| --------------------------------- | --------------------------------------------- | ------------------------------------- |
| `send_instruction(ix, signers)`   | `Result<TransactionResult, TransactionError>` | Invia una singola istruzione            |
| `send_instructions(ixs, signers)` | `Result<TransactionResult, TransactionError>` | Invia più istruzioni in una singola tx |
| `send_transaction_result(tx)`     | `Result<TransactionResult, TransactionError>` | Invia una `Transaction` raw             |

## Risoluzione dei problemi

### Errori comuni

| Errore               | Causa                                       | Soluzione                          |
| ------------------- | ------------------------------------------- | --------------------------------- |
| `AccountNotFound`   | Tentativo di usare un account che non esiste | Usa prima `create_funded_account` |
| `InsufficientFunds` | Lamport insufficienti per la transazione         | Aumenta l'importo del finanziamento iniziale   |
| `OwnerMismatch`     | Account di proprietà del programma sbagliato              | Verifica che l'ID del programma sia corretto         |
| `AssertionFailed`   | Il saldo o lo stato non corrisponde al valore atteso     | Controlla la logica del test             |
