> ## 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>
  返されるエラーが非nilになるのは、バイト列をデコードできなかった場合、または内部障害が発生した場合のみです。*実行されたものの失敗した*トランザクションでも、非nilの`*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`            | トップレベルのinstructionごとにグループ化された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のまとまりを発生させたトップレベルのinstructionをインデックスとするスライスを返します。

### PostAccount

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

シミュレーション時に`PostAccounts()`から返されます。

## Blockhashの管理

### LatestBlockhash

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

現在のblockhashを読み取ります。トランザクションを構築する際に、`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
```

現在のblockhashを越えて進めることで、次回の`LatestBlockhash`が新しい値を返すようにします。古いblockhashで署名されたトランザクションは`"BlockhashNotFound"`で失敗するため、blockhashの有効期限切れに関するエッジケースのテストに役立ちます。

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

## トランザクション履歴

トランザクション履歴はデフォルトで有効になっており、リプレイの検出に使われます。同じ署名済みトランザクションを2回送信すると、エラー`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)
```

`payerSeed`から導出されたkeypairから`to`へ、`blockhash`を使って`lamports`を送金する、bincodeエンコード済みで署名済みのレガシー`Transaction`を生成します。返されるバイト列は、そのまま`SendLegacyTransaction`に渡せます。支払者はseedから導出された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`を使う方法を推奨します。複数のinstructionを含むトランザクション、v0メッセージ、任意のプログラムにも対応できます。
</Info>
