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

# Транзакції

> Виконання та симуляція транзакцій за допомогою LiteSVM у TypeScript

Методи для надсилання, симуляції та керування транзакціями.

## sendTransaction

```typescript
sendTransaction(tx: Transaction): TransactionMetadata | FailedTransactionMetadata
```

Виконує транзакцію. У разі успіху повертає `TransactionMetadata`, а в разі
помилки — `FailedTransactionMetadata`. Визначити, який саме результат ви отримали, можна за допомогою
`instanceof FailedTransactionMetadata`. Невдалий результат має `err()` для
помилки та `meta()` для її метаданих, зокрема журналів.

```typescript
import { FailedTransactionMetadata } from "litesvm";

const result = client.svm.sendTransaction(signedTx);

if (result instanceof FailedTransactionMetadata) {
  // Check for errors
  console.error("Transaction failed:", result.err());
  console.error("Logs:", result.meta().logs());
} else {
  // Access result properties (note: these are getter functions)
  console.log("Signature:", result.signature());
  console.log("Compute units:", result.computeUnitsConsumed());
  console.log("Logs:", result.logs());
}
```

<Info>
  `FailedTransactionMetadata` походить із пакета `litesvm`, який
  встановлює `@solana/kit-plugin-litesvm`. Додайте його до власних залежностей за допомогою
  `npm install litesvm`, щоб мати змогу його імпортувати.
</Info>

<Warning>
  Властивості результату транзакції, як-от `err()`, `computeUnitsConsumed()`,
  `logs()` і `signature()`, є **функціями-геттерами**, а не властивостями. Завжди
  викликайте їх із дужками.
</Warning>

### Методи TransactionMetadata

| Метод                   | Повертає                 | Опис                 |
| ------------------------ | ----------------------- | --------------------------- |
| `signature()`            | `Uint8Array`            | Байти підпису транзакції |
| `computeUnitsConsumed()` | `bigint`                | Використані обчислювальні одиниці          |
| `logs()`                 | `string[]`              | Журнали програми                |
| `innerInstructions()`    | `InnerInstruction[]`    | Внутрішні (CPI) інструкції    |
| `returnData()`           | `TransactionReturnData` | Дані, які повертають програми   |
| `prettyLogs()`           | `string`                | Форматовані журнали з кольорами  |

## simulateTransaction

```typescript
simulateTransaction(tx: Transaction): SimulatedTransactionInfo | FailedTransactionMetadata
```

Симулює транзакцію без зміни стану.

```typescript
import { FailedTransactionMetadata } from "litesvm";

const simResult = client.svm.simulateTransaction(signedTx);

if (simResult instanceof FailedTransactionMetadata) {
  console.error("Simulation failed:", simResult.err());
  console.error("Logs:", simResult.meta().logs());
} else {
  // Use .meta() to get TransactionMetadata
  const meta = simResult.meta();
  console.log("Would use", meta.computeUnitsConsumed(), "compute units");
  console.log("Logs:", meta.logs());

  // Get post-execution account states
  const postAccounts = simResult.postAccounts();
  console.log("Post-state accounts:", postAccounts);
}
```

<Info>
  Симуляція не змінює стан. Використовуйте її, щоб перевірити транзакції перед надсиланням.
</Info>

## Керування blockhash

### latestBlockhash

```typescript
latestBlockhash(): Blockhash
```

Отримує поточний blockhash.

```typescript
const blockhash = client.svm.latestBlockhash();
console.log("Blockhash:", blockhash);
```

### getLatestBlockhash (через client.rpc)

Отримує blockhash з інформацією про час життя для ручного створення транзакцій.
Використовуйте допоміжну функцію RPC, оскільки вона повертає і `blockhash`, і `lastValidBlockHeight`.

```typescript
import {
  createTransactionMessage,
  setTransactionMessageLifetimeUsingBlockhash
} from "@solana/kit";

const { value: blockhashLifetime } = await client.rpc
  .getLatestBlockhash()
  .send();

const tx = setTransactionMessageLifetimeUsingBlockhash(
  blockhashLifetime,
  createTransactionMessage({ version: 0 })
);
```

<Info>
  Коли ви використовуєте плагіни програм, як-от `systemProgram()` або `tokenProgram()`, вам
  ніколи не потрібно самостійно отримувати blockhash — `client.sendTransaction()` (і
  допоміжна функція `.sendTransaction()` у ланцюжках інструкцій) зробить це за вас.
</Info>

### expireBlockhash

```typescript
expireBlockhash(): void
```

Переходить до нового blockhash. Корисно для тестування сценаріїв завершення терміну дії blockhash.

```typescript
const oldBlockhash = client.svm.latestBlockhash();
client.svm.expireBlockhash();
const newBlockhash = client.svm.latestBlockhash();

console.log("Old:", oldBlockhash);
console.log("New:", newBlockhash);
// Blockhashes will be different
```

## Історія транзакцій

Увімкніть історію транзакцій, щоб отримувати транзакції після надсилання:

```typescript
// Enable history storage (stores last N transactions)
client.svm.withTransactionHistory(100n);

// Send a transaction
const result = client.svm.sendTransaction(signedTx);

// Later, retrieve it by signature (base58 string)
// Note: getTransaction expects a base58-encoded signature string
```
