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

# Giao dịch

> Thực thi và mô phỏng giao dịch với LiteSVM trong Go

Các phương thức để gửi, mô phỏng và quản lý giao dịch. Hỗ trợ cả giao dịch legacy và
giao dịch có phiên bản v0+.

`litesvm-go` nhận các byte giao dịch được mã hóa bằng bincode, do
`(*solana.Transaction).MarshalBinary` của
[`gagliardetto/solana-go`](https://github.com/gagliardetto/solana-go) tạo ra.

## SendLegacyTransaction

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

Gửi một `Transaction` legacy đã được mã hóa bằng bincode. Khi thành công, giao dịch
sẽ được ghi vào sổ cái trong bộ nhớ.

```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ỗi trả về chỉ khác nil khi không thể giải mã các byte hoặc xảy ra lỗi
  nội bộ. Một giao dịch *được thực thi nhưng thất bại* vẫn
  trả về `*TxOutcome` khác nil; hãy luôn kiểm tra `IsOk()` trước khi sử dụng
  các trạng thái chỉ có khi thành công.
</Warning>

## SendVersionedTransaction

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

Có cấu trúc giống `SendLegacyTransaction`, nhưng dành cho các message v0+. Hàm
`MarshalBinary` của `solana-go` tạo ra đúng các byte cho cả hai trường hợp.

## SimulateLegacyTransaction / SimulateVersionedTransaction

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

Thực thi giao dịch mà không ghi trạng thái. Hàm trả về cùng cấu trúc `*TxOutcome`,
đồng thời `PostAccounts()` được điền trạng thái sau thực thi dự kiến của các
account có thể ghi.

```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>
  Mô phỏng không làm thay đổi trạng thái. Hãy dùng nó để ước lượng compute budget hoặc kiểm tra
  log mà không làm ảnh hưởng đến sổ cái của bạn.
</Info>

## TxOutcome

Mỗi lệnh gọi gửi / mô phỏng đều trả về một `*TxOutcome` chứa cùng một bộ metadata
dù thành công hay thất bại. Tất cả các accessor đều chấp nhận receiver `nil` và
trả về giá trị zero.

| Phương thức                | Giá trị trả về                            | Mô tả                                               |
| --------------------- | ---------------------------------- | --------------------------------------------------------- |
| `IsOk()`              | `bool`                             | Giao dịch thành công                                     |
| `Error()`             | `string`                           | Lỗi dạng JSON theo định dạng wire của Agave, ví dụ `"BlockhashNotFound"` (rỗng khi thành công) |
| `Signature()`         | `solana.Signature`                 | Chữ ký giao dịch                                     |
| `ComputeUnits()`      | `uint64`                           | Compute unit đã tiêu thụ                                    |
| `Fee()`               | `uint64`                           | Phí đã tính                                               |
| `Logs()`              | `[]string`                         | Log của chương trình                                              |
| `ReturnData()`        | `(solana.PublicKey, []byte, bool)` | Dữ liệu trả về được đặt qua `set_return_data`; `ok=false` nếu không có |
| `InnerInstructions()` | `InnerInstructionsList`            | Các CPI được nhóm theo instruction cấp cao nhất                     |
| `PostAccounts()`      | `([]PostAccount, error)`           | Trạng thái sau thực thi - chỉ dành cho mô phỏng                      |

### 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()` trả về một slice được đánh chỉ mục theo instruction cấp cao nhất
đã kích hoạt từng loạt CPI.

### PostAccount

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

Được `PostAccounts()` trả về cho các lần mô phỏng.

## Quản lý Blockhash

### LatestBlockhash

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

Đọc blockhash hiện tại. Truyền nó vào `solana.NewTransaction(...)` khi
xây dựng giao dịch.

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

Chuyển qua blockhash hiện tại để lần gọi `LatestBlockhash` tiếp theo trả về một giá trị
mới. Các giao dịch được ký bằng blockhash cũ hơn sẽ thất bại với lỗi
`"BlockhashNotFound"`, hữu ích để kiểm thử các trường hợp biên khi blockhash hết hạn.

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

## Lịch sử giao dịch

Lịch sử giao dịch được bật theo mặc định và đây chính là cơ chế phát hiện replay: gửi
cùng một giao dịch đã ký hai lần sẽ trả về một outcome với lỗi
`AlreadyProcessed`. Điều chỉnh dung lượng (hoặc tắt chống trùng lặp) bằng
`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)
}
```

Tra cứu một giao dịch trước đó theo chữ ký (theo mặc định, lịch sử giữ 32 giao dịch gần nhất, bao gồm cả các giao dịch đã thực thi nhưng thất bại):

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

## BuildTransferTx (hàm hỗ trợ kiểm thử)

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

Tạo một `Transaction` legacy đã ký, được mã hóa bằng bincode, chuyển `lamports`
từ keypair được suy ra từ `payerSeed` đến `to`, sử dụng `blockhash`. Các
byte trả về sẵn sàng để truyền vào `SendLegacyTransaction`. Payer là
keypair được suy ra từ seed, vì vậy hãy nạp tiền cho địa chỉ của nó trước (ví dụ bằng
`Airdrop`); nếu không, outcome sẽ thất bại với lỗi `"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>
  Hàm này tồn tại để khởi tạo các bài kiểm thử. Khi bạn xây dựng các giao dịch thực tế, hãy ưu tiên dùng cách
  của `solana-go` đã nêu ở trên - cách đó mở rộng được cho các giao dịch nhiều instruction, message v0,
  và các chương trình tùy ý.
</Info>
