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

# LaserStream WebSocket: リアルタイムSolanaデータストリーミング

> LaserStream WebSocketを使用してWebSocketでリアルタイムのSolanaブロックチェーンデータをストリーム - 標準のSolanaサブスクリプションとHelius拡張機能（transactionSubscribeなど）を備え、Agave RPCベースのWebSocketより最大200 ms速い。

## LaserStream WebSocketとは？

LaserStream WebSocketは、[LaserStream](/ja/laserstream) のWebSocketプロトコル版です。標準のSolana JSON-RPCサブスクリプションメソッド（`accountSubscribe`, `programSubscribe`, `logsSubscribe`, `signatureSubscribe`, `slotSubscribe`, …）をHelius専用の拡張機能と共に提供し、高度なフィルタリングのための[`transactionSubscribe`](/ja/rpc/websocket/transaction-subscribe)など、同じ統合エンドポイント`wss://mainnet.helius-rpc.com`で提供されています。

WebSocketは持続的でリアルタイムな接続を提供します。つまり、「何か変わったか？」と繰り返しポーリングするのではなく、何かが起こるとすぐにブロックチェーンが通知します。

<CardGroup cols={2}>
  <Card title="リアルタイム更新" icon="bolt">
    Solanaアカウントが変わったり、トランザクションが発生したり、新しいブロックが生成されると即座に通知を受け取ります。
  </Card>

  <Card title="効率的なリソース使用" icon="leaf">
    数百のHTTPリクエストをポーリングする代わりに、1つの持続的な接続
  </Card>

  <Card title="低レイテンシー" icon="clock">
    標準のAgave RPCベースのWebSocketより最大で200 ms速く、LaserStreamによって提供
  </Card>

  <Card title="Helius拡張" icon="filter">
    `transactionSubscribe`と標準Solanaメソッド上に高度なフィルタリングのための拡張`accountSubscribe`
  </Card>
</CardGroup>

## エンドポイント

WebSocketは標準のSolanaメソッドとHelius専用拡張機能の両方で、ネットワークごとに単一の統一エンドポイントから提供されます：

**メインネット:** `wss://mainnet.helius-rpc.com/?api-key=<API_KEY>`
**開発ネット:** `wss://devnet.helius-rpc.com/?api-key=<API_KEY>`

### Gatekeeper (ベータ)

最速のWebSocketオファリングをテストするには、新しいGatekeeper (ベータ) エンドポイントを試してください：

`wss://beta.helius-rpc.com/?api-key=<API_KEY>`

## 料金と計測

WebSocketの使用は、ストリームされたデータの**0.1 MBごとに2クレジット**で計測されます。接続を開くには**1クレジット**が必要です。

Professionalプランの高ボリュームワークロードには、予測可能なコストで月次データ許容量（5TB〜100TB）を提供する[**データアドオン**](/ja/billing/plans#data-add-ons)をご利用いただけます。データアドオンはLaserStreamとWebSocketに適用できます。

<Note>
  Helius専用メソッド`transactionSubscribe`と`accountSubscribe`（Heliusフィルタを含む）は、**Developer**、**Business**、または**Professional** [プラン](/ja/billing/plans)が必要です。標準Solanaメソッド`programSubscribe`、`logsSubscribe`、と`signatureSubscribe`はすべてのプランで利用できます。
</Note>

## コアコンセプト

### サブスクリプションタイプ

<AccordionGroup>
  <Accordion title="アカウントサブスクリプション" icon="user">
    特定のアカウントの変更（ウォレット残高、トークンアカウント、プログラムデータなど）を監視します。

    **ユースケース：**

    * ウォレット残高の追跡
    * トークンアカウントの監視
    * スマートコントラクトの状態変更
    * NFT所有権の更新
  </Accordion>

  <Accordion title="プログラムサブスクリプション" icon="code">
    特定のプログラムが所有するすべてのアカウントを監視し、変更を見守ります。

    **ユースケース：**

    * DEX取引の監視
    * DeFiプロトコルトラッキング
    * NFTマーケットプレイスの活動
    * ゲーム資産の変更
  </Accordion>

  <Accordion title="トランザクションサブスクリプション" icon="receipt">
    特定のトランザクションが承認された際、または特定のアカウントに関連するトランザクションが発生した際に通知を受け取ります。

    **ユースケース：**

    * 支払い確認
    * トランザクションステータストラッキング
    * マルチシグネチャ承認
    * コントラクト実行の監視
  </Accordion>

  <Accordion title="スロットサブスクリプション" icon="clock">
    ブロックチェーンの進行状況とファイナリティをスロットレベルで監視します。

    **ユースケース：**

    * ブロックエクスプローラーアプリケーション
    * ネットワークの健康状態の監視
    * コンセンサストラッキング
    * パフォーマンス分析
  </Accordion>
</AccordionGroup>

### コミットメントレベル

コミットメントレベルを理解することは信頼性の高いアプリケーションにとって重要です：

<Tabs>
  <Tab title="Processed">
    **最速** - バリデーターによって処理されたが確認されていないトランザクション

    * レイテンシー：約400ms
    * リスク：取り消しや順序変更の可能性
    * 用途：リアルタイムUI更新（注意が必要）
  </Tab>

  <Tab title="Confirmed">
    **バランスが取れている** - クラスターの過半数がスロットに投票

    * レイテンシー：約2〜3秒
    * リスク：取り消される可能性が低い
    * 用途：ほとんどのアプリケーション
  </Tab>

  <Tab title="Finalized">
    **最も安全** - クラスターのスーパー過半数がスロットに投票

    * レイテンシー：約15〜30秒
    * リスク：取り消される可能性が非常に低い
    * 用途：金融アプリケーション、高価値トランザクション
  </Tab>
</Tabs>

<Info>
  **コミットメントレベルについてもっと知りたいですか？** 詳細なブログポストをお読みください：[Solana Commitment Levelsの理解](https://www.helius.dev/blog/solana-commitment-levels)
</Info>

## 利用可能なWebSocketメソッド

Heliusは、完全なSolana WebSocketサブスクリプションメソッドセットとHelius専用拡張をサポートしています。すべてのメソッドは同じ`wss://mainnet.helius-rpc.com`エンドポイントを共有します。

### Helius拡張

2つのメソッドは、Solana標準を超えたリッチなフィルタリングを提供します：

* [`transactionSubscribe`](/ja/rpc/websocket/transaction-subscribe) — インクルード/エクスクルード/必須アカウントリスト、投票/失敗フラグ、特定の署名を含むトランザクションを購読
* [`accountSubscribe`](/ja/rpc/websocket/account-subscribe) — Heliusは標準の`accountSubscribe`形状に高度なフィルタを追加

### 標準Solanaメソッド

`accountSubscribe`, `blockSubscribe`, `logsSubscribe`, `programSubscribe`, `rootSubscribe`, `signatureSubscribe`, `slotSubscribe`, `slotsUpdatesSubscribe`, `voteSubscribe`とそれらに対応する`*Unsubscribe`ペア。

<Card title="完全なAPIリファレンス" icon="book" href="/ja/api-reference/rpc/websocket-methods">
  **18以上のWebSocketメソッドを探索**。各メソッドには詳細なパラメータ、応答フォーマット、例が含まれています。
</Card>

## 再接続ロジックの実装方法

WebSocket接続は、ネットワーク問題、サーバーメンテナンス、または一時的な障害など、さまざまな理由で切断されることがあります。本番アプリケーションは、信頼性を確保するために再接続ロジックを実装する**必要があります**。

### 切断が発生する理由

<AccordionGroup>
  <Accordion title="ネットワーク問題">
    * インターネット接続の問題
    * モバイルデバイスでのWiFiハンドオフ
    * 企業ファイアウォールのタイムアウト
    * ISPルーティングの変更
  </Accordion>

  <Accordion title="サーバー側イベント">
    * 計画されたメンテナンス期間
    * ロードバランサの再起動
    * RPCノードの更新
    * 一時的なオーバーロード保護
  </Accordion>

  <Accordion title="クライアント側の問題">
    * ブラウザタブのバックグラウンド化
    * モバイルアプリのサスペンド
    * コンピュータのスリープ/ハイバーネーション
    * プロセスクラッシュや再起動
  </Accordion>
</AccordionGroup>

### 切断の検出

<Tabs>
  <Tab title="JavaScript/ブラウザ">
    ```javascript [expandable] theme={"system"}
    class ConnectionMonitor {
      constructor(ws) {
        this.ws = ws;
        this.pingInterval = null;
        this.lastPong = Date.now();
        this.isConnected = false;
        
        this.setupEventListeners();
        this.startPingMonitoring();
      }
      
      setupEventListeners() {
        this.ws.onopen = () => {
          console.log('Connected');
          this.isConnected = true;
          this.lastPong = Date.now();
        };
        
        this.ws.onclose = (event) => {
          console.log('Disconnected:', event.code, event.reason);
          this.isConnected = false;
          this.stopPingMonitoring();
        };
        
        this.ws.onerror = (error) => {
          console.error('WebSocket error:', error);
          this.isConnected = false;
        };
        
        // Listen for pong responses (server acknowledgment)
        this.ws.onmessage = (event) => {
          const data = JSON.parse(event.data);
          if (data.method === 'pong') {
            this.lastPong = Date.now();
          }
          // Handle other messages...
        };
      }
      
      startPingMonitoring() {
        this.pingInterval = setInterval(() => {
          if (this.isConnected) {
            // Send ping to check connection health
            this.ws.send(JSON.stringify({
              jsonrpc: '2.0',
              method: 'ping',
              id: Date.now()
            }));
            
            // Check if we received a pong recently
            const timeSinceLastPong = Date.now() - this.lastPong;
            if (timeSinceLastPong > 30000) { // 30 seconds timeout
              console.warn('No pong received, connection may be stale');
              this.ws.close();
            }
          }
        }, 10000); // Ping every 10 seconds
      }
      
      stopPingMonitoring() {
        if (this.pingInterval) {
          clearInterval(this.pingInterval);
          this.pingInterval = null;
        }
      }
    }
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript [expandable] theme={"system"}
    const WebSocket = require('ws');

    class NodeConnectionMonitor {
      constructor(url) {
        this.url = url;
        this.ws = null;
        this.pingInterval = null;
        this.isAlive = false;
      }
      
      connect() {
        this.ws = new WebSocket(this.url);
        
        this.ws.on('open', () => {
          console.log('Connected');
          this.isAlive = true;
          this.startHeartbeat();
        });
        
        this.ws.on('close', () => {
          console.log('Disconnected');
          this.isAlive = false;
          this.stopHeartbeat();
        });
        
        this.ws.on('error', (error) => {
          console.error('WebSocket error:', error);
          this.isAlive = false;
        });
        
        // Built-in ping/pong handling
        this.ws.on('pong', () => {
          this.isAlive = true;
        });
      }
      
      startHeartbeat() {
        this.pingInterval = setInterval(() => {
          if (!this.isAlive) {
            console.log('Connection lost, terminating');
            return this.ws.terminate();
          }
          
          this.isAlive = false;
          this.ws.ping();
        }, 30000); // Ping every 30 seconds
      }
      
      stopHeartbeat() {
        if (this.pingInterval) {
          clearInterval(this.pingInterval);
          this.pingInterval = null;
        }
      }
    }
    ```
  </Tab>
</Tabs>

### 再接続戦略

<Tabs>
  <Tab title="指数バックオフ">
    ```javascript [expandable] theme={"system"}
    class ExponentialBackoffReconnector {
      constructor(url, maxRetries = 10) {
        this.url = url;
        this.maxRetries = maxRetries;
        this.retryCount = 0;
        this.baseDelay = 1000; // Start with 1 second
        this.maxDelay = 30000; // Cap at 30 seconds
        this.ws = null;
        this.subscriptions = new Map();
        this.isReconnecting = false;
      }
      
      connect() {
        if (this.isReconnecting) return;
        
        try {
          this.ws = new WebSocket(this.url);
          this.setupEventHandlers();
        } catch (error) {
          console.error('Failed to create WebSocket:', error);
          this.scheduleReconnect();
        }
      }
      
      setupEventHandlers() {
        this.ws.onopen = () => {
          console.log('Connected successfully');
          this.retryCount = 0; // Reset retry count on successful connection
          this.isReconnecting = false;
          this.resubscribeAll(); // Restore subscriptions
        };
        
        this.ws.onclose = (event) => {
          console.log('Connection closed:', event.code);
          if (!this.isReconnecting) {
            this.scheduleReconnect();
          }
        };
        
        this.ws.onerror = (error) => {
          console.error('WebSocket error:', error);
        };
      }
      
      scheduleReconnect() {
        if (this.retryCount >= this.maxRetries) {
          console.error('Max retry attempts reached. Giving up.');
          return;
        }
        
        this.isReconnecting = true;
        this.retryCount++;
        
        // Calculate delay with exponential backoff + jitter
        const delay = Math.min(
          this.baseDelay * Math.pow(2, this.retryCount - 1),
          this.maxDelay
        );
        
        // Add jitter to prevent thundering herd
        const jitteredDelay = delay + (Math.random() * 1000);
        
        console.log(`Reconnecting in ${jitteredDelay}ms (attempt ${this.retryCount}/${this.maxRetries})`);
        
        setTimeout(() => {
          this.connect();
        }, jitteredDelay);
      }
      
      subscribe(method, params, callback) {
        const id = this.generateId();
        this.subscriptions.set(id, { method, params, callback });
        
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.sendSubscription(id, method, params);
        }
        
        return id;
      }
      
      resubscribeAll() {
        console.log(`Restoring ${this.subscriptions.size} subscriptions`);
        for (const [id, sub] of this.subscriptions) {
          this.sendSubscription(id, sub.method, sub.params);
        }
      }
      
      sendSubscription(id, method, params) {
        this.ws.send(JSON.stringify({
          jsonrpc: '2.0',
          id: id,
          method: method,
          params: params
        }));
      }
      
      generateId() {
        return Date.now() + Math.random();
      }
    }
    ```
  </Tab>

  <Tab title="サーキットブレーカーパターン">
    ```javascript [expandable] theme={"system"}
    class CircuitBreakerWebSocket {
      constructor(url, options = {}) {
        this.url = url;
        this.failureThreshold = options.failureThreshold || 5;
        this.recoveryTimeout = options.recoveryTimeout || 60000;
        this.checkInterval = options.checkInterval || 10000;
        
        this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
        this.failureCount = 0;
        this.lastFailureTime = null;
        this.ws = null;
        this.subscriptions = new Map();
      }
      
      connect() {
        if (this.state === 'OPEN') {
          if (Date.now() - this.lastFailureTime > this.recoveryTimeout) {
            console.log('Circuit breaker moving to HALF_OPEN state');
            this.state = 'HALF_OPEN';
          } else {
            console.log('Circuit breaker is OPEN, connection blocked');
            return false;
          }
        }
        
        try {
          this.ws = new WebSocket(this.url);
          this.setupEventHandlers();
          return true;
        } catch (error) {
          this.recordFailure();
          return false;
        }
      }
      
      setupEventHandlers() {
        this.ws.onopen = () => {
          console.log('Connected - Circuit breaker CLOSED');
          this.state = 'CLOSED';
          this.failureCount = 0;
          this.resubscribeAll();
        };
        
        this.ws.onclose = () => {
          this.recordFailure();
        };
        
        this.ws.onerror = (error) => {
          console.error('WebSocket error:', error);
          this.recordFailure();
        };
      }
      
      recordFailure() {
        this.failureCount++;
        this.lastFailureTime = Date.now();
        
        console.log(`Failure recorded: ${this.failureCount}/${this.failureThreshold}`);
        
        if (this.failureCount >= this.failureThreshold) {
          console.log('Circuit breaker opened due to repeated failures');
          this.state = 'OPEN';
        }
      }
      
      startHealthCheck() {
        setInterval(() => {
          if (this.state === 'OPEN' || 
              (this.ws && this.ws.readyState !== WebSocket.OPEN)) {
            this.connect();
          }
        }, this.checkInterval);
      }
    }
    ```
  </Tab>
</Tabs>

### 再接続ロジックのテスト

<Tabs>
  <Tab title="ネットワークシミュレーション">
    ```javascript [expandable] theme={"system"}
    // Test disconnection scenarios
    class NetworkSimulator {
      constructor(wsManager) {
        this.wsManager = wsManager;
      }
      
      // Simulate network outage
      simulateNetworkOutage(duration = 5000) {
        console.log('Simulating network outage...');
        
        // Force close the connection
        if (this.wsManager.ws) {
          this.wsManager.ws.close(1006, 'Network outage simulation');
        }
        
        // Block reconnection temporarily
        const originalConnect = this.wsManager.connect.bind(this.wsManager);
        this.wsManager.connect = () => {
          console.log('Connection blocked during outage simulation');
        };
        
        // Restore connection after duration
        setTimeout(() => {
          console.log('Network restored');
          this.wsManager.connect = originalConnect;
          this.wsManager.connect();
        }, duration);
      }
      
      // Simulate intermittent connectivity
      simulateIntermittentConnectivity() {
        setInterval(() => {
          if (Math.random() < 0.1) { // 10% chance every 10 seconds
            console.log('Simulating connection drop...');
            this.wsManager.ws?.close(1006, 'Intermittent connectivity');
          }
        }, 10000);
      }
    }

    // Usage
    const simulator = new NetworkSimulator(wsManager);
    simulator.simulateNetworkOutage(10000); // 10 second outage
    ```
  </Tab>

  <Tab title="自動テスト">
    ```javascript [expandable] theme={"system"}
    // Jest test example
    describe('WebSocket Reconnection', () => {
      let wsManager;
      
      beforeEach(() => {
        wsManager = new ProductionWebSocketManager({
          endpoint: 'ws://localhost:8080',
          apiKey: 'test-key'
        });
      });
      
      test('should reconnect after connection loss', async () => {
        const reconnectPromise = new Promise((resolve) => {
          wsManager.on('connected', resolve);
        });
        
        await wsManager.connect();
        
        // Simulate connection loss
        wsManager.ws.close(1006, 'Test disconnection');
        
        // Wait for reconnection
        await reconnectPromise;
        
        expect(wsManager.connectionState).toBe('CONNECTED');
        expect(wsManager.metrics.reconnections).toBeGreaterThan(0);
      });
      
      test('should restore subscriptions after reconnection', async () => {
        await wsManager.connect();
        
        const messages = [];
        const subscriptionId = wsManager.subscribe(
          'accountSubscribe',
          ['test-account', {}],
          (data) => messages.push(data)
        );
        
        // Verify subscription exists
        expect(wsManager.subscriptions.has(subscriptionId)).toBe(true);
        
        // Simulate disconnection and reconnection
        wsManager.ws.close(1006, 'Test disconnection');
        
        await new Promise(resolve => wsManager.on('connected', resolve));
        
        // Verify subscription was restored
        const subscription = wsManager.subscriptions.get(subscriptionId);
        expect(subscription.pending).toBe(true); // Should be re-subscribing
      });
    });
    ```
  </Tab>
</Tabs>

<Warning>
  **本番環境では重要**: 適切な再接続ロジックの実装は、本番アプリケーションにおいて必須です。WebSocket接続は切断されます - それに備え、テストし、本番環境で監視してください。
</Warning>

## トラブルシューティング

<AccordionGroup>
  <Accordion title="接続失敗">
    **症状**: WebSocketが最初に接続に失敗

    **解決策**:

    * APIキーが正しく、十分なクレジットを持っていることを確認する
    * エンドポイントURLの形式を確認する: `wss://mainnet.helius-rpc.com?api-key=YOUR_KEY`
    * WebSocket接続がポート443で許可されていることをファイアウォールで確認する
    * 基本的な接続性を確認するために、まずシンプルなpingを試す
  </Accordion>

  <Accordion title="頻繁な切断">
    **症状**: 数分ごとに接続が切れる

    **解決策**:

    * WebSocketは**10分の非アクティブタイマー**を持っています。接続を維持するために少なくとも1分ごとにpingを送信する（上記の再接続例と[WebSocket FAQ](/ja/faqs/websockets#why-are-my-enhanced-websockets-connections-disconnecting)を参照）
    * 適切なping/pongハートビートを実装する（再接続例で示されています）
    * ネットワークの安定性と企業ファイアウォールの設定を確認する
    * サブスクリプションの数を監視する - 多すぎると不安定になる可能性がある
    * 接続ライフサイクルを適切に処理していることを確認する
  </Accordion>

  <Accordion title="メッセージが欠落する">
    **症状**: 予想されるサブスクリプション更新が受け取れない

    **解決策**:

    * サブスクリプションが確認されていることを確認する（応答を確認）
    * 監視しているアカウント/プログラムに実際の活動があることを確認する
    * 接続状態を監視する - 欠落したメッセージは通常切断を示す
  </Accordion>

  <Accordion title="高いレイテンシー">
    **症状**: メッセージの配信が遅く、更新に遅延がある

    **解決策**:

    * "finalized"ではなく"confirmed"コミットメントを使用
    * アクティブなサブスクリプションの数を減らす
    * メッセージ処理ロジックを最適化する
    * 複数の接続を使用して負荷を分散することを検討する
    * ネットワーク接続品質を確認する
  </Accordion>

  <Accordion title="メモリリーク">
    **症状**: アプリケーションのメモリ使用量が時間と共に増加する

    **解決策**:

    * 適切なサブスクリプションクリーニングを実装する
    * コンポーネントがアンマウントされたときにイベントリスナーを削除する
    * 定期的にメッセージログをクリアする
    * サブスクリプション数を監視し、制限を設ける
    * 可能な場合はコールバック関数に弱参照を使用する
  </Accordion>
</AccordionGroup>

## 標準RPCからの移行

HTTPポーリングを現在使用している場合、WebSocketへの移行方法は以下の通りです：

```javascript [expandable] theme={"system"}
// Old approach - HTTP polling
class HTTPAccountMonitor {
  constructor(connection, accountAddress) {
    this.connection = connection;
    this.accountAddress = accountAddress;
    this.interval = null;
    this.lastKnownBalance = null;
  }

  start() {
    this.interval = setInterval(async () => {
      try {
        const accountInfo = await this.connection.getAccountInfo(
          new PublicKey(this.accountAddress)
        );
        
        const currentBalance = accountInfo?.lamports || 0;
        
        if (this.lastKnownBalance !== currentBalance) {
          console.log(`Balance changed: ${currentBalance}`);
          this.lastKnownBalance = currentBalance;
        }
      } catch (error) {
        console.error('Failed to fetch account info:', error);
      }
    }, 2000); // Poll every 2 seconds
  }

  stop() {
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
  }
}

// New approach - WebSocket subscription
class WebSocketAccountMonitor {
  constructor(wsManager, accountAddress) {
    this.wsManager = wsManager;
    this.accountAddress = accountAddress;
    this.subscriptionId = null;
  }

  start() {
    this.subscriptionId = this.wsManager.subscribe(
      'accountSubscribe',
      [
        this.accountAddress,
        { encoding: 'jsonParsed', commitment: 'confirmed' }
      ],
      (data) => {
        const currentBalance = data.value.lamports;
        console.log(`Balance changed: ${currentBalance}`);
        
        // Handle the change immediately - no polling delay!
      }
    );
  }

  stop() {
    if (this.subscriptionId) {
      this.wsManager.unsubscribe(this.subscriptionId);
      this.subscriptionId = null;
    }
  }
}
```

## 拡張機能

さらに高度な機能を必要とするアプリの場合は、[LaserStream gRPC](/ja/laserstream)をご検討ください：

<CardGroup cols={2}>
  <Card title="24時間の履歴再生" icon="clock-rotate-left">
    アプリがオフライン中に逃したデータをキャッチアップ
  </Card>

  <Card title="マルチノード集約" icon="network-wired">
    複数のバリデーターからのデータでより高い信頼性
  </Card>

  <Card title="高スループット" icon="gauge-high">
    より多くのサブスクリプションと高いメッセージレートを処理する
  </Card>

  <Card title="エンタープライズ機能" icon="building">
    高度なモニタリング、分析、データパイプライン
  </Card>
</CardGroup>

## 始める

始める準備はできましたか？

[WebSocketクイックスタートガイド](/ja/rpc/websocket/quickstart)をチェックして、実用的な例とステップバイステップの実装を確認してください。
