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