> ## Documentation Index
> Fetch the complete documentation index at: https://www.helius.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# gRPC を介した前処理されたトランザクション

> デコードされたシュレッドは、gRPC を介してコミットメントレベルの約 8 ms 前に配信されます。

<Warning>
  **廃止予定のお知らせ。** gRPC を介した前処理されたトランザクションは廃止されます。[WebSocket メソッド](/docs/ja/preprocessed-transactions/preprocessed-subscribe)に切り替えてください—それは同じ事前実行トランザクションデータをより低いレイテンシーで配信します。
</Warning>

前処理されたトランザクションは、gRPC を介して Solana トランザクションを受信する最速の方法です。Helius は、バリデータに届くとすぐにシュレッドを直接デコードし、結果のトランザクションを送信することで、ポストエクスキューションのサブスクリプションよりミリ秒早くトランザクションデータにアクセスできます — **平均してコミットメントレベルの約 8 ms 前**です。

このガイドでは、前処理されたトランザクションを使用するタイミング、利用可能なデータ、LaserStream SDK を使用してそれらにサブスクライブする方法を説明します（同じ gRPC 接続を介して前処理されたトランザクションも提供します）。

## 元のトランザクションのライフサイクル内での位置

Solana のアーキテクチャでは、トランザクションは完全に処理される前にいくつかの段階を経ます:

1. **シュレッド受付** → バリデータがトランザクションシュレッド（データ断片）を受信。 ← ここで Helius の **[生のシュレッド (UDP)](/docs/ja/shred-delivery/raw-shreds)** が配信されます。
2. **シュレッドデコード** → シュレッドが生のトランザクションにデコードされます。 ← **ここで前処理されたトランザクションが利用可能です。**
3. **トランザクション実行** → トランザクションがランタイムによって実行されます。
4. **メタデータ生成** → 前／後のバランス、ログ、およびエラー情報が計算されます。
5. **コミットメント** → トランザクションが処理済み／確認済み／確定済みの状態に達します。 ← **[LaserStream gRPC](/docs/ja/laserstream)** および **[LaserStream WebSocket](/docs/ja/rpc/websocket)** はここで配信されます。

ポストエクスキューションのサブスクリプションは、完全な実行とメタデータ生成の後の段階 5 でデータを配信します。前処理されたサブスクリプションは、シュレッドがデコードされた直後、実行が完了する前に段階 2 で配信されます。

**トレードオフ:** トランザクションデータをミリ秒単位で早く受け取れますが、バランス変化やログ、エラー情報などの実行メタデータはありません。

<Warning>
  **これはトランザクション専用のストリームです。** アカウントおよびプログラム状態の更新は、ランタイムがトランザクションを実行するまで存在しません（段階 4）。リアルタイムのアカウントまたはプログラムの更新（トークンバランス、ボンディングカーブの状態、プログラムアカウント、生のトランザクション以外のもの）が必要な場合、\*\*[LaserStream gRPC](/docs/ja/laserstream) にてコミットメントで受け取るのが最速です。
</Warning>

<Tip>
  さらに速いトランザクションシグナルが必要ですか？[Preconfirmations](/docs/ja/pre-confirmations/overview)を使用してスケジュールされたトランザクションをストリームし、[生のシュレッド (UDP)](/docs/ja/shred-delivery/raw-shreds)を使用して未処理のトランザクションデータを取得してください。
</Tip>

## 最善の努力による配信保証

前処理されたトランザクションの配信はベストエフォートであり、保証されていません。99.99% の配信率を目指していますが、次の場合にいくつかのトランザクションが失われる可能性があります:

* インフラストラクチャの更新と再配置
* ネットワークの問題やバリデータの接続性の問題
* シュレッドのデコードまたは処理のエッジケース

保証された配信が必要な重要なアプリケーションの場合は、標準の[トランザクションサブスクリプション](/docs/ja/laserstream/guides/decoding-transaction-data)を使用してください。

## 利用可能なデータは？

前処理されたトランザクションには、完全なトランザクションメッセージが含まれていますが、実行メタデータは含まれていません:

### 利用可能なデータ

* ✅ **トランザクション署名** - ユニークなトランザクション識別子
* ✅ **アカウントキー** - トランザクションで参照されるすべてのアカウント
* ✅ **命令** - 完全な命令データとプログラム呼び出し
* ✅ **最近のブロックハッシュ** - トランザクションの有効期限の参照
* ✅ **署名** - すべてのトランザクション署名
* ✅ **投票トランザクションであるか** - これが投票トランザクションであるかどうか
* ✅ **スロット番号** - このトランザクションを含むスロット

### 不足しているデータ

* ❌ **トランザクションメタデータ** - トークンバランスの変化、前／後のバランス、トランザクションステータス
* ❌ **トランザクションエラー** - トランザクションが失敗したかどうかを判断できません
* ❌ **内部命令** - クロスプログラム呼び出し（CPI）は含まれません
* ❌ **ログメッセージ** - プログラムのログは実行中に生成されます
* ❌ **消費した計算ユニット** - 実行メトリクスは利用できません

前処理されたトランザクションは「結果」のない「提案」を受け取るようなものと考えてください。ユーザーが何をしようとしたのかはわかりますが、実際に何が起きたのかはわかりません。

## SDK サポートとバージョン要件

前処理されたトランザクションのサブスクリプションは、すべての LaserStream SDK でサポートされています:

<CardGroup cols={3}>
  <Card title="JavaScript/TypeScript" icon="js" href="https://github.com/helius-labs/laserstream-sdk/tree/main/javascript">
    バージョン **0.2.8** 以上
  </Card>

  <Card title="Rust" icon="rust" href="https://github.com/helius-labs/laserstream-sdk/tree/main/rust">
    バージョン **0.1.5** 以上
  </Card>

  <Card title="Go" icon="golang" href="https://github.com/helius-labs/laserstream-sdk/tree/main/go">
    バージョン **0.1.0** 以上
  </Card>
</CardGroup>

***

## 実装例

### JavaScript/TypeScript

JavaScript SDK は自動再接続を備えた専用の関数を提供しています:

```typescript [expandable] theme={"system"}
import {
  subscribePreprocessed,
  CommitmentLevel,
  LaserstreamConfig,
  SubscribePreprocessedRequest,
  SubscribePreprocessedUpdate
} from 'helius-laserstream';
import bs58 from 'bs58';

async function streamPreprocessedTransactions() {
  const config: LaserstreamConfig = {
    apiKey: 'YOUR_API_KEY',
    endpoint: 'https://laserstream-mainnet-ewr.helius-rpc.com',
  };

  const request: SubscribePreprocessedRequest = {
    transactions: {
      "jupiter-swaps": {
        vote: false,
        accountInclude: ['JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4']
      }
    }
  };

  const stream = await subscribePreprocessed(
    config,
    request,
    async (update: SubscribePreprocessedUpdate) => {
      if (update.transaction) {
        const tx = update.transaction;
        const signature = bs58.encode(tx.transaction.signature);

        console.log('⚡ Preprocessed transaction received:');
        console.log(`  Signature: ${signature}`);
        console.log(`  Slot: ${tx.slot}`);
        console.log(`  Is Vote: ${tx.transaction.isVote}`);
        console.log(`  Filters: ${update.filters.join(', ')}`);
        console.log('---');
      }
    },
    async (error) => {
      console.error('Stream error:', error);
    }
  );

  console.log(`✅ Preprocessed stream started (id: ${stream.id})`);

  // Graceful shutdown
  process.on('SIGINT', () => {
    console.log('\n🛑 Shutting down stream...');
    stream.cancel();
    process.exit(0);
  });
}

streamPreprocessedTransactions().catch(console.error);
```

**完全な例:** [preprocessed-transaction-sub.ts](https://github.com/helius-labs/laserstream-sdk/blob/main/javascript/examples/preprocessed-transaction-sub.ts)

### Rust

Rust SDK はネイティブのパフォーマンスを提供します:

```rust [expandable] theme={"system"}
use futures::StreamExt;
use helius_laserstream::{
    grpc::{SubscribePreprocessedRequest, SubscribePreprocessedRequestFilterTransactions},
    subscribe_preprocessed, LaserstreamConfig,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = LaserstreamConfig {
        endpoint: "https://laserstream-mainnet-ewr.helius-rpc.com".to_string(),
        api_key: "YOUR_API_KEY".to_string(),
        ..Default::default()
    };

    let mut request = SubscribePreprocessedRequest::default();
    request.transactions.insert(
        "jupiter-swaps".to_string(),
        SubscribePreprocessedRequestFilterTransactions {
            vote: Some(false),
            account_include: vec![
                "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4".to_string()
            ],
            ..Default::default()
        },
    );

    let (stream, _handle) = subscribe_preprocessed(config, request);
    tokio::pin!(stream);

    println!("✅ Preprocessed stream started");

    while let Some(result) = stream.next().await {
        match result {
            Ok(update) => {
                if let Some(tx) = update.transaction {
                    println!("⚡ Preprocessed transaction:");
                    println!("  Slot: {}", tx.slot);
                    println!("  Is Vote: {}", tx.transaction.is_vote);
                    println!("---");
                }
            }
            Err(e) => {
                eprintln!("Stream error: {:?}", e);
                break;
            }
        }
    }

    Ok(())
}
```

**完全な例:** [preprocessed\_transaction\_sub.rs](https://github.com/helius-labs/laserstream-sdk/blob/main/rust/examples/preprocessed_transaction_sub.rs)

### Go

Go SDK は Go の慣用的なインターフェースを提供します:

```go [expandable] theme={"system"}
package main

import (
    "log"
    "os"
    "os/signal"
    "syscall"

    laserstream "github.com/helius-labs/laserstream-sdk/go"
    pb "github.com/helius-labs/laserstream-sdk/go/proto"
)

func main() {
    log.SetFlags(0)

    clientConfig := laserstream.LaserstreamConfig{
        Endpoint: "https://laserstream-mainnet-ewr.helius-rpc.com",
        APIKey:   "YOUR_API_KEY",
    }

    voteFilter := false
    subscriptionRequest := &pb.SubscribePreprocessedRequest{
        Transactions: map[string]*pb.SubscribePreprocessedRequestFilterTransactions{
            "jupiter-swaps": {
                Vote: &voteFilter,
                AccountInclude: []string{
                    "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",
                },
            },
        },
    }

    client := laserstream.NewPreprocessedClient(clientConfig)

    dataCallback := func(data *pb.SubscribePreprocessedUpdate) {
        if data.Transaction != nil {
            log.Println("⚡ Preprocessed transaction:")
            log.Printf("  Slot: %d\n", data.Transaction.Slot)
            log.Printf("  Is Vote: %t\n", data.Transaction.Transaction.IsVote)
            log.Println("---")
        }
    }

    errorCallback := func(err error) {
        log.Printf("Error: %v", err)
    }

    err := client.Subscribe(subscriptionRequest, dataCallback, errorCallback)
    if err != nil {
        log.Fatalf("Failed to subscribe: %v", err)
    }

    log.Println("✅ Preprocessed stream started")
    log.Println("Press Ctrl+C to exit")

    sigChan := make(chan os.Signal, 1)
    signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
    <-sigChan

    log.Println("\nShutting down...")
    client.Close()
}
```

**完全な例:** [preprocessed-transaction-sub.go](https://github.com/helius-labs/laserstream-sdk/blob/main/go/examples/preprocessed-transaction-sub.go)

***

## サブスクリプション構造とフィルタリング

### リクエスト構造

前処理されたサブスクリプションリクエストは、標準のサブスクリプションに似た構造ですが、特定のフィルタに焦点を当てています:

```typescript theme={"system"}
interface SubscribePreprocessedRequest {
  transactions: {
    [filterName: string]: SubscribePreprocessedRequestFilterTransactions
  };
  ping?: SubscribeRequestPing;
}

interface SubscribePreprocessedRequestFilterTransactions {
  vote?: boolean;              // Include/exclude vote transactions
  signature?: string;          // Filter by specific transaction signature
  accountInclude?: string[];   // Include transactions touching these accounts
  accountExclude?: string[];   // Exclude transactions touching these accounts
  accountRequired?: string[];  // Require all these accounts to be present
}
```

### レスポンス構造

更新は完全なトランザクションメッセージと基本的なメタデータと共に到着します:

```typescript theme={"system"}
interface SubscribePreprocessedUpdate {
  filters: string[];                             // Which filters matched
  transaction?: SubscribePreprocessedTransaction; // The transaction data
  ping?: SubscribeUpdatePing;                    // Keepalive ping
  pong?: SubscribeUpdatePong;                    // Ping response
  createdAt: Date;                               // When update was created
}

interface SubscribePreprocessedTransaction {
  transaction: SubscribePreprocessedTransactionInfo;
  slot: number;                                  // Slot containing transaction
}

interface SubscribePreprocessedTransactionInfo {
  signature: Uint8Array;                         // Transaction signature
  isVote: boolean;                               // Is this a vote transaction
  transaction: solana.storage.Transaction;       // Full transaction message
}
```

フィールドには、Solana トランザクションの完全な構造が含まれています:

* **メッセージ** - アカウントキー、命令、最近のブロックハッシュ
* **署名** - すべてのトランザクション署名
* **アドレスタブルックアップ** - バージョン付きトランザクション用

これは、標準的なサブスクリプションでのトランザクション構造と同一ですが、実行結果を含むフィールドがありません。
