> ## 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는 바이트를 디코딩할 수 없거나 내부 오류가 발생한 경우에만 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

모든 send / simulate 호출은 성공 여부와 관계없이 동일한 메타데이터를 담은
`*TxOutcome`을 반환합니다. 모든 접근자는 `nil` 리시버를 허용하며
제로 값을 반환합니다.

| 메서드                | 반환값                            | 설명                                               |
| --------------------- | ---------------------------------- | --------------------------------------------------------- |
| `IsOk()`              | `bool`                             | 트랜잭션 성공 여부                                     |
| `Error()`             | `string`                           | Agave wire-format 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)
```

`payerSeed`에서 파생된 keypair에서 `to`로 `lamports`를 전송하는, `blockhash`를 사용한
bincode 인코딩의 서명된 레거시 `Transaction`을 생성합니다. 반환된 바이트는
`SendLegacyTransaction`에 바로 전달할 수 있습니다. 결제자(payer)는 시드에서
파생된 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>
