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

# Transações

> Métodos para lidar com transações

## send_transaction

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

Executa a transação e modifica o estado.

```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 a transação sem modificar o estado.

Retorna `SimulatedTransactionInfo`, que contém:

- `meta`: metadados da transação (logs, unidades de computação, assinatura etc.)
- `post_accounts`: estados das contas após a simulação

```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 usar a simulação

Use `simulate_transaction()` para:

- Testar a validade da transação sem modificar o estado
- Verificar o consumo de unidades de computação
- Verificar os logs da transação sem confirmação
- Testar os caminhos de tratamento de erros

```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
    }
}
```

## Testando casos de erro

Aqui, `invalid_tx` é paga por uma conta que não consegue cobrir a taxa. Um pagador
com apenas 1.000 lamports falha com `InsufficientFundsForFee`; um pagador que
não existe de forma alguma falha antes, com `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"),
}
```

## O estado permanece inalterado

```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);
```

## Metadados da transação

`send_transaction()` retorna `TransactionMetadata` diretamente, enquanto
`simulate_transaction()` retorna `SimulatedTransactionInfo`, que contém
`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,
}
```

### Acessando os dados da transação

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

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

Consulta uma transação no histórico. `LiteSVM::new()` mantém as últimas 32
transações por padrão; chame `with_transaction_history(n)` para manter mais.
Com `with_transaction_history(0)`, o histórico é desativado e `get_transaction`
sempre retorna `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
```

Obtém o blockhash atual para as transações.

```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)
```

Força a expiração do blockhash atual.

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

## Padrões comuns

### Validar antes de executar

```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");
}
```

### Acompanhar unidades de computação

```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
);
```

### Verificar os logs da transação

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

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