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

> Esegui e simula transazioni con LiteSVM in Go

Metodi per inviare, simulare e gestire le transazioni. Sono supportate sia le
transazioni legacy sia quelle versioned v0+.

`litesvm-go` accetta i byte di transazione codificati in bincode prodotti da
`(*solana.Transaction).MarshalBinary` di
[`gagliardetto/solana-go`](https://github.com/gagliardetto/solana-go).

## SendLegacyTransaction

```go
func (s *LiteSVM) SendLegacyTransaction(txBytes []byte) (*TxOutcome, error)
```

Invia una `Transaction` legacy codificata in bincode. In caso di successo, la
transazione viene registrata nel ledger in memoria.

```go
out, err := svm.SendLegacyTransaction(txBytes)
if err != nil {
    t.Fatal(err)
}

if !out.IsOk() {
    t.Fatalf("tx failed: %s\nlogs: %v", out.Error(), out.Logs())
}

t.Logf("signature: %s", out.Signature())
t.Logf("compute:   %d CU", out.ComputeUnits())
t.Logf("fee:       %d lamports", out.Fee())
```

<Warning>
  L'errore restituito è non-nil solo quando non è stato possibile decodificare i
  byte o si è verificato un errore interno. Una transazione che *viene eseguita
  ma fallisce* restituisce comunque un `*TxOutcome` non-nil; controlla sempre
  `IsOk()` prima di usare lo stato disponibile solo in caso di successo.
</Warning>

## SendVersionedTransaction

```go
func (s *LiteSVM) SendVersionedTransaction(txBytes []byte) (*TxOutcome, error)
```

Stessa struttura di `SendLegacyTransaction`, ma per i messaggi v0+.
`MarshalBinary` di `solana-go` produce i byte corretti in entrambi i casi.

## SimulateLegacyTransaction / SimulateVersionedTransaction

```go
func (s *LiteSVM) SimulateLegacyTransaction(txBytes []byte) (*TxOutcome, error)
func (s *LiteSVM) SimulateVersionedTransaction(txBytes []byte) (*TxOutcome, error)
```

Esegue la transazione senza registrare lo stato. Viene restituito lo stesso
`*TxOutcome`, e inoltre `PostAccounts()` viene popolato con lo stato
post-esecuzione che avrebbero gli account scrivibili.

```go
sim, err := svm.SimulateLegacyTransaction(txBytes)
if err != nil {
    t.Fatal(err)
}

if !sim.IsOk() {
    t.Fatalf("sim failed: %s", sim.Error())
}

t.Logf("would use %d compute units", sim.ComputeUnits())
t.Logf("logs: %v", sim.Logs())

posts, err := sim.PostAccounts()
if err != nil {
    t.Fatal(err)
}
for _, p := range posts {
    t.Logf("%s: %d lamports", p.Address, p.Account.Lamports)
}
```

<Info>
  La simulazione non modifica lo stato. Usala per dimensionare i compute budget o
  per verificare i log senza alterare il tuo ledger.
</Info>

## TxOutcome

Ogni chiamata di invio / simulazione restituisce un `*TxOutcome` con gli stessi
metadati, indipendentemente dal successo o dal fallimento. Tutti gli accessor
accettano un receiver `nil` e restituiscono valori zero.

| Metodo                | Restituisce                            | Descrizione                                               |
| --------------------- | ---------------------------------- | --------------------------------------------------------- |
| `IsOk()`              | `bool`                             | La transazione è riuscita                                     |
| `Error()`             | `string`                           | Errore JSON in formato wire di Agave, ad esempio `"BlockhashNotFound"` (vuoto in caso di successo) |
| `Signature()`         | `solana.Signature`                 | Firma della transazione                                     |
| `ComputeUnits()`      | `uint64`                           | Compute unit consumate                                    |
| `Fee()`               | `uint64`                           | Commissione addebitata                                               |
| `Logs()`              | `[]string`                         | Log del programma                                              |
| `ReturnData()`        | `(solana.PublicKey, []byte, bool)` | Dati di ritorno impostati tramite `set_return_data`; `ok=false` se assenti |
| `InnerInstructions()` | `InnerInstructionsList`            | CPI raggruppate per istruzione di primo livello                     |
| `PostAccounts()`      | `([]PostAccount, error)`           | Stato post-esecuzione - solo simulazione                      |

### InnerInstruction

```go
type InnerInstruction struct {
    Instruction solana.CompiledInstruction // indices point into the transaction's account table
    StackHeight uint16                     // 1 for top-level, higher for deeper CPIs
}

type InnerInstructionsList [][]InnerInstruction
```

`InnerInstructions()` restituisce uno slice indicizzato per l'istruzione di primo
livello che ha innescato ciascun gruppo di CPI.

### PostAccount

```go
type PostAccount struct {
    Address solana.PublicKey
    Account *solana.Account
}
```

Restituito da `PostAccounts()` per le simulazioni.

## Gestione del blockhash

### LatestBlockhash

```go
func (s *LiteSVM) LatestBlockhash() (solana.Hash, error)
```

Legge il blockhash corrente. Passalo a `solana.NewTransaction(...)` quando
costruisci le transazioni.

```go
blockhash, err := svm.LatestBlockhash()
if err != nil {
    t.Fatal(err)
}

tx, _ := solana.NewTransaction(
    []solana.Instruction{ix},
    blockhash,
    solana.TransactionPayer(payer),
)
_ = tx // sign, marshal and send it
```

### ExpireBlockhash

```go
func (s *LiteSVM) ExpireBlockhash() error
```

Avanza oltre il blockhash corrente, in modo che il successivo `LatestBlockhash`
restituisca un nuovo valore. Le transazioni firmate con un blockhash precedente
falliscono quindi con `"BlockhashNotFound"`, utile per testare i casi limite di
scadenza del blockhash.

```go
bh1, err := svm.LatestBlockhash()
if err != nil {
    t.Fatal(err)
}
if err := svm.ExpireBlockhash(); err != nil {
    t.Fatal(err)
}
bh2, err := svm.LatestBlockhash()
if err != nil {
    t.Fatal(err)
}
// bh1 != bh2
_, _ = bh1, bh2
```

## Cronologia delle transazioni

La cronologia delle transazioni è attiva per impostazione predefinita ed è ciò
che rileva i replay: inviare due volte la stessa transazione firmata restituisce
un outcome con errore `AlreadyProcessed`. Regola la capacità (o disattiva la
deduplicazione) con `SetTransactionHistory`:

```go
// Cap history at 100 entries.
if err := svm.SetTransactionHistory(100); err != nil {
    t.Fatal(err)
}

// Disable dedup entirely (allows replaying identical transactions).
if err := svm.SetTransactionHistory(0); err != nil {
    t.Fatal(err)
}
```

Cerca una transazione precedente tramite la firma (per impostazione predefinita la cronologia conserva le 32 transazioni più recenti, incluse quelle eseguite ma fallite):

```go
prior := svm.GetTransaction(sig) // nil if unknown
if prior != nil {
    t.Logf("found: %s, fee=%d", prior.Signature(), prior.Fee())
}
```

## BuildTransferTx (helper per i test)

```go
func BuildTransferTx(
    payerSeed [32]byte,
    to solana.PublicKey,
    lamports uint64,
    blockhash solana.Hash,
) ([]byte, error)
```

Produce una `Transaction` legacy firmata e codificata in bincode che trasferisce
`lamports` dal keypair derivato da `payerSeed` a `to`, usando `blockhash`. I
byte restituiti sono pronti per essere passati a `SendLegacyTransaction`. Il
payer è il keypair derivato dal seed, quindi finanzia prima il suo indirizzo
(ad esempio con `Airdrop`); altrimenti l'outcome fallisce con
`"InsufficientFundsForFee"`.

```go
var seed [32]byte
copy(seed[:], somePayerSeedBytes)

bh, err := svm.LatestBlockhash()
if err != nil {
    t.Fatal(err)
}
txBytes, err := litesvm.BuildTransferTx(seed, recipient, 1_000_000_000, bh)
if err != nil {
    t.Fatal(err)
}

out, err := svm.SendLegacyTransaction(txBytes)
if err != nil {
    t.Fatal(err)
}
if !out.IsOk() {
    t.Fatalf("tx failed: %s", out.Error())
}
```

<Info>
  Esiste per avviare i test. Quando costruisci transazioni reali, preferisci il
  percorso `solana-go` mostrato sopra: scala fino a transazioni con più
  istruzioni, messaggi v0 e programmi arbitrari.
</Info>
