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

# Bắt đầu

> Sử dụng LiteSVM từ Go với litesvm-go để kiểm thử Solana nhanh chóng ngay trong tiến trình

Các bộ test Solana khởi chạy `solana-test-validator` mất vài giây cho mỗi test -
bạn phải chờ khởi động tiến trình, kết nối RPC và các vòng trao đổi qua mạng.
LiteSVM chạy cùng các test đó chỉ trong vài mili giây. Không cần tiến trình bên ngoài, không cần mạng,
toàn bộ chạy trong bộ nhớ ngay bên trong trình chạy test của bạn.

`litesvm-go` là binding Go chính thức. Các kiểu cốt lõi (`PublicKey`, `Hash`,
`Signature`) được lấy trực tiếp từ
[`gagliardetto/solana-go`](https://github.com/gagliardetto/solana-go), nên các giá trị
có thể luân chuyển tự nhiên giữa `litesvm-go` và phần còn lại của hệ sinh thái Solana trong Go.

<Info>
  **Yêu cầu:** Go 1.25.7+. `litesvm-go` v0.3.0 trở lên là Go thuần, không dùng
  cgo, nên không cần Rust toolchain, không có archive vendored và không cần build tag,
  và có thể biên dịch chéo chỉ với `GOOS` / `GOARCH` thông thường.
</Info>

Một handle `LiteSVM` mới cung cấp các chức năng airdrop, giao dịch (legacy + v0),
mô phỏng, đọc/ghi tài khoản, sysvar, compute budget, feature gate, du hành
thời gian, chương trình tùy chỉnh và lịch sử giao dịch. Engine này là SVM từ
[mithril](https://github.com/Overclock-Validator/mithril), chạy dưới dạng Go thuần
bên trong tiến trình test của bạn.

## Bắt đầu nhanh

<Steps titleSize="h3">

<Step title="Cài đặt module">
`go get` phân giải các dependency vào một Go module, vì vậy hãy khởi tạo một module trước nếu bạn
chưa có `go.mod`:

```bash
go mod init mytest
```

Sau đó thêm module:

```bash
go get github.com/LiteSVM/litesvm-go
```

Đồng thời kéo `solana-go` về để tạo keypair, instruction và transaction:

```bash
go get github.com/gagliardetto/solana-go
```

<Warning>
  `go get github.com/LiteSVM/litesvm-go` cài đặt tag mới nhất. v0.3.0 là bản viết lại
  bằng Go thuần với API khác so với các binding cgo v0.1 / v0.2:
  tài khoản là các giá trị `*solana.Account` thông thường (không có handle và không có `Close`), và
  sysvar sử dụng các kiểu của `github.com/gagliardetto/solana-go/sysvar`. Các trang này
  mô tả v0.3.0 trở lên.
</Warning>

</Step>

<Step title="Tạo SVM của bạn">
Lưu test này thành `setup_test.go` trong module của bạn, rồi chạy bằng
`go test ./...` (thêm `-v` để xem số dư được ghi log):

```go
package mytest

import (
    "testing"

    litesvm "github.com/LiteSVM/litesvm-go"
    solana "github.com/gagliardetto/solana-go"
)

func TestSetup(t *testing.T) {
    svm, err := litesvm.New()
    if err != nil {
        t.Fatal(err)
    }
    defer svm.Close()

    // Fund a payer
    priv, err := solana.NewRandomPrivateKey()
    if err != nil {
        t.Fatal(err)
    }
    payer := priv.PublicKey()

    if err := svm.Airdrop(payer, 5_000_000_000); err != nil {
        t.Fatal(err)
    }

    // Check the balance
    lamports, ok, err := svm.Balance(payer)
    if err != nil {
        t.Fatal(err)
    }
    if !ok {
        t.Fatal("payer account missing")
    }
    t.Logf("balance: %d lamports", lamports)
}
```

<Info>
  `litesvm.New()` trả về một `*LiteSVM` và một `error`. Mọi điểm vào trong
  `litesvm-go` đều theo cùng dạng `(value, error)`, và mọi lỗi đều bọc
  sentinel `litesvm.ErrLiteSVM`, nên bạn có thể phát hiện bằng `errors.Is`.
  `svm.Close()` là no-op được giữ lại để `defer svm.Close()` vẫn hợp lệ.
</Info>

</Step>

</Steps>

## Tìm hiểu về Handle

Sau `litesvm.New()`, `*LiteSVM` được trả về cung cấp các nhóm chức năng sau:

| Nhóm                | Phương thức                                                                                                                            |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| Tài khoản             | `Airdrop`, `Balance`, `GetAccount`, `SetAccount`, `MinimumBalanceForRentExemption`                                                 |
| Giao dịch         | `SendLegacyTransaction`, `SendVersionedTransaction`, `SimulateLegacyTransaction`, `SimulateVersionedTransaction`, `GetTransaction` |
| Blockhash            | `LatestBlockhash`, `ExpireBlockhash`                                                                                               |
| Chương trình             | `AddProgram`, `AddProgramFromFile`, `AddProgramWithLoader`                                                                         |
| Thời gian và sysvar     | `WarpToSlot`, `Clock`, `SetClock`, `Rent`, `SetRent`, `EpochSchedule`, `SetEpochSchedule`, `EpochRewards`, ...                     |
| Cấu hình        | `SetSigverify`, `SetBlockhashCheck`, `SetTransactionHistory`, `SetLogBytesLimit`, `SetSysvars`, `SetBuiltins`, ...                 |
| Compute và tính năng | `ComputeBudget`, `SetComputeBudget`, `SetFeatureSet`                                                                               |

Một `LiteSVM` mới được tải sẵn các chương trình Solana cốt lõi (System Program, SPL
Token, v.v.), nên các giao dịch chuyển tiền đơn giản hoạt động ngay.

## Gửi giao dịch

Hãy tạo các instruction bằng `solana-go`, marshal transaction và gửi
các byte đó đi. `litesvm-go` chấp nhận các byte mã hóa bincode được tạo bởi
`(*solana.Transaction).MarshalBinary`:

```go
package mytest

import (
    "testing"

    litesvm "github.com/LiteSVM/litesvm-go"
    solana "github.com/gagliardetto/solana-go"
    "github.com/gagliardetto/solana-go/programs/system"
)

func TestTransfer(t *testing.T) {
    svm, err := litesvm.New()
    if err != nil {
        t.Fatal(err)
    }
    defer svm.Close()

    priv, err := solana.NewRandomPrivateKey()
    if err != nil {
        t.Fatal(err)
    }
    payer := priv.PublicKey()
    recipient := solana.NewWallet().PublicKey()

    if err := svm.Airdrop(payer, 2_000_000_000); err != nil {
        t.Fatal(err)
    }

    blockhash, err := svm.LatestBlockhash()
    if err != nil {
        t.Fatal(err)
    }
    ix := system.NewTransferInstruction(1_000_000_000, payer, recipient).Build()
    tx, err := solana.NewTransaction(
        []solana.Instruction{ix},
        blockhash,
        solana.TransactionPayer(payer),
    )
    if err != nil {
        t.Fatal(err)
    }
    if _, err := tx.Sign(func(k solana.PublicKey) *solana.PrivateKey {
        if k.Equals(payer) {
            return &priv
        }
        return nil
    }); err != nil {
        t.Fatal(err)
    }
    txBytes, err := tx.MarshalBinary()
    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\nlogs: %v", out.Error(), out.Logs())
    }

    lamports, _, err := svm.Balance(recipient)
    if err != nil {
        t.Fatal(err)
    }
    if lamports != 1_000_000_000 {
        t.Fatalf("recipient balance = %d, want 1_000_000_000", lamports)
    }
}
```

<Info>
  `SendLegacyTransaction` và `SendVersionedTransaction` đều trả về một
  `*TxOutcome` dù giao dịch thành công hay thất bại. Hãy gọi `IsOk()` trước khi
  đọc các trường chỉ có khi thành công.
</Info>

## Làm việc với TxOutcome

Mọi điểm vào gửi / mô phỏng đều trả về một `*TxOutcome`. Cùng một handle
mang metadata cho cả trường hợp thành công và thất bại:

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

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

_ = out.Signature()    // solana.Signature
_ = out.ComputeUnits() // uint64
_ = out.Fee()          // uint64
_ = out.Logs()         // []string
_ = out.InnerInstructions()

// Programs that call set_return_data expose it here.
if pid, data, ok := out.ReturnData(); ok {
    _ = pid
    _ = data
}
```

Với `SimulateLegacyTransaction` / `SimulateVersionedTransaction`, cùng
`*TxOutcome` đó còn cung cấp thêm `PostAccounts()` - trạng thái tài khoản dự kiến
sau khi thực thi:

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

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

## Cấu hình

`litesvm-go` cung cấp các công tắc builder giống như Rust crate, được hiển thị dưới dạng
các phương thức `Set*`:

```go
// Each setter returns an error. In tests where the values are known good,
// the calls are infallible and assigning to _ keeps the example readable;
// in production code, check the error or wrap with require.NoError(t, ...).
_ = svm.SetSigverify(false)        // accept unsigned / badly-signed txs
_ = svm.SetBlockhashCheck(false)   // skip recent-blockhash enforcement
_ = svm.SetTransactionHistory(0)   // 0 disables dedup; any N caps history
_ = svm.SetLogBytesLimit(-1)       // negative = unlimited
_ = svm.SetLamports(1 << 40)       // reset the airdrop pool balance
_ = svm.SetSysvars()               // reset sysvars to defaults
_ = svm.SetBuiltins()              // reload built-in programs
_ = svm.SetDefaultPrograms()       // reload SPL Token, Memo, etc.
_ = svm.SetPrecompiles()           // enable ed25519 / secp256k1 precompiles
_ = svm.WithNativeMints()          // seed wrapped-SOL mint
```

## Ghi chú

**An toàn luồng.** Một handle `*LiteSVM` không an toàn khi được dùng đồng thời từ
nhiều goroutine (hầu hết các phương thức đều thay đổi trạng thái nội bộ). Hãy giới hạn một handle trong
một goroutine duy nhất, hoặc bảo vệ nó bằng `sync.Mutex`. Các instance riêng biệt được
cô lập hoàn toàn với nhau.

**Chuỗi lỗi.** `TxOutcome.Error()` trả về JSON theo định dạng wire của Agave cho
lỗi đó, ví dụ `"BlockhashNotFound"`,
`{"InstructionError":[0,{"Custom":1}]}`, hoặc
`{"InstructionError":[0,"SystemProgErrResultWithNegativeLamports"]}` cho một lần
chuyển SOL không đủ số dư.

## Tiếp theo

Phần này đã đề cập handle cốt lõi - tạo tài khoản, gửi instruction và
đọc trạng thái. Để xem tài liệu tham khảo đầy đủ theo từng phương thức, hãy xem
[tài liệu API](/developers/docs/tools/litesvm/go/api-reference). Để xem các ví dụ có thể chạy được (chuyển SOL,
thiết lập tài khoản, kiểm thử chương trình, logic dựa trên thời gian), hãy xem
[Ví dụ](/developers/docs/tools/litesvm/go/examples).
