> ## 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を介してデコードされたシュレッドが`processed`コミットメントレベルの約8ミリ秒前に配信されます。HeliusのShred Delivery製品ファミリーの一部です。

<Note>
  **パブリックベータ版。** 前処理されたトランザクションはHeliusの[Shred Delivery](/ja/shred-delivery)製品ファミリーの一部です。**プロフェッショナルプラン以上**の購読者に利用可能で、**1 MBあたり20クレジット**で計測されます。

  平均して、前処理されたトランザクションは\*\*`processed`コミットメントレベル\*\*より約8ミリ秒早く到着しますが、実行メタデータのコストがかかります（下記の[トレードオフ](#what-data-is-available)参照）。
</Note>

前処理されたトランザクションは、gRPCを介してSolanaトランザクションを受け取る最速の方法です。Heliusは、バリデータに到着する際にシュレッドを直接デコードし、結果として生じるトランザクションを提供することで、実行後の購読より数ミリ秒早くトランザクションデータにアクセスできます。平均して\*\*`processed`コミットメントレベルの約8ミリ秒前\*\*です。

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

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

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

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

実行後の購読はメタデータ生成後のステージ5でデータを提供しますが、前処理された購読はシュレッドをデコード直後、実行完了前のステージ2で提供されます。

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

<Warning>
  **これはトランザクションのみに対応したストリームです。** アカウントおよびプログラムの状態更新は、ランタイムがトランザクションを実行するまで存在しません（ステージ4）。リアルタイムのアカウントまたはプログラムの更新が必要な場合は、**[LaserStream gRPC](/ja/laserstream) at `processed`コミットメント**を使用してください。これがアカウント/プログラム変更を受け取る最速の方法です。
</Warning>

<Tip>
  さらに高速なトランザクションシグナルが必要ですか？スケジュールされたトランザクションをストリームする[Pre Confirmations](/ja/pre-confirmations/overview)や、未処理のトランザクションデータのための[Raw Shreds (UDP)](/ja/shred-delivery/raw-shreds)を試してください。
</Tip>

## ベストエフォート配信保証

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

* インフラの更新および再展開
* ネットワークの問題またはバリデータ接続問題
* シュレッドデコードや処理のエッジケース

保証された配信が必要な重要なアプリケーションには、標準の[トランザクション購読](/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は、自動再接続機能を持つ専用の`subscribePreprocessed`関数を提供しています：

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

`transaction.transaction`フィールドには次を含むSolanaトランザクションの完全な構造が含まれています：

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