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

# 交易

> 在 Go 中使用 LiteSVM 执行和模拟交易

用于发送、模拟和管理交易的方法。同时支持旧版交易和 v0+ 版本化交易。

`litesvm-go` 接受由 [`gagliardetto/solana-go`](https://github.com/gagliardetto/solana-go) 的 `(*solana.Transaction).MarshalBinary` 生成的 bincode 编码交易字节。

## SendLegacyTransaction

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

提交经 bincode 编码的旧版 `Transaction`。成功后，该交易会提交到内存账本中。

```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>
  仅当字节无法解码或发生内部故障时，返回的 error 才为非空。*已执行但失败*的交易仍会返回非空的 `*TxOutcome`；在使用仅成功时才有效的状态之前，请务必先检查 `IsOk()`。
</Warning>

## SendVersionedTransaction

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

与 `SendLegacyTransaction` 结构相同，但适用于 v0+ 消息。`solana-go` 的 `MarshalBinary` 可为这两种情况生成正确的字节。

## SimulateLegacyTransaction / SimulateVersionedTransaction

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

执行交易但不提交状态。返回的 `*TxOutcome` 结构相同，此外 `PostAccounts()` 会填充可写账户在执行后将会呈现的状态。

```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>
  模拟不会更改状态。可以用它来估算计算预算，或对日志进行断言，而不会污染您的账本。
</Info>

## TxOutcome

每次发送/模拟调用都会返回一个 `*TxOutcome`，无论成功或失败，其携带的元数据都相同。所有访问器都能容忍 `nil` 接收者，并返回零值。

| 方法                | 返回值                            | 说明                                               |
| --------------------- | ---------------------------------- | --------------------------------------------------------- |
| `IsOk()`              | `bool`                             | 交易是否成功                                     |
| `Error()`             | `string`                           | Agave 网络传输格式的 JSON 失败信息，例如 `"BlockhashNotFound"`（成功时为空） |
| `Signature()`         | `solana.Signature`                 | 交易签名                                     |
| `ComputeUnits()`      | `uint64`                           | 消耗的计算单元                                    |
| `Fee()`               | `uint64`                           | 收取的手续费                                               |
| `Logs()`              | `[]string`                         | 程序日志                                              |
| `ReturnData()`        | `(solana.PublicKey, []byte, bool)` | 通过 `set_return_data` 设置的返回数据；若无则 `ok=false` |
| `InnerInstructions()` | `InnerInstructionsList`            | 按顶层指令分组的 CPI                     |
| `PostAccounts()`      | `([]PostAccount, error)`           | 执行后的状态 - 仅限模拟                      |

### 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()` 返回一个切片，其索引对应触发每批 CPI 的顶层指令。

### PostAccount

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

在模拟时由 `PostAccounts()` 返回。

## 区块哈希管理

### LatestBlockhash

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

读取当前区块哈希。构建交易时，将其传入 `solana.NewTransaction(...)`。

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

推进到当前区块哈希之后，使下一次 `LatestBlockhash` 返回新值。之后，使用旧区块哈希签名的交易会失败并返回 `"BlockhashNotFound"`，这对于测试区块哈希过期的边界情况很有用。

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

## 交易历史

交易历史默认开启，重放检测正是依赖它：重复发送同一笔已签名交易时，会返回错误为 `AlreadyProcessed` 的结果。可使用 `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)
}
```

按签名查找先前的交易（历史记录默认保留最近的 32 笔交易，包括已执行但失败的交易）：

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

## BuildTransferTx（测试辅助函数）

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

生成一笔经 bincode 编码并已签名的旧版 `Transaction`，使用 `blockhash`，将 `lamports` 从由 `payerSeed` 派生的 keypair 转给 `to`。返回的字节可直接交给 `SendLegacyTransaction`。付款方是由该种子派生的 keypair，因此请先为其地址充值（例如使用 `Airdrop`）；否则结果会失败并返回 `"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>
  此函数用于快速搭建测试。当您开始构建真实交易时，建议使用上文所示的 `solana-go` 方式，它可扩展到多指令交易、v0 消息和任意程序。
</Info>
