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

# Solana Pump AMMデータをストリームする方法

> LaserStream WebSocketを使用してライブのSolana Pump AMMデータをストリームする方法を学びます。自動再接続を含むログベースのモニタリングがすべてのプランで利用可能です。

## LaserStream WebSocketを使用する

<p>
  [LaserStream WebSocket](/ja/rpc/websocket)は、シンプルなWebSocket統合を提供し、すべてのHeliusプランで利用できるため、開発者にとって便利な選択肢です。この例ではSolanaの`logsSubscribe`メソッドを使用しているため、ログメッセージのみを受信します。
</p>

<Tip>
  LaserStream WebSocketは標準のAgave RPCベースのWebSocket実装より200 msまで高速です。
</Tip>

### 仕組み

[LaserStream WebSocketエンドポイント](https://www.helius.dev/docs/api-reference/endpoints)に接続し、[Pump AMMプログラム](https://orbmarkets.io/address/pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA/history)に言及するログを購読し、受信したログデータを処理します。

以下の例には指数バックオフを伴う自動再接続ロジックが含まれています。

## 要件

<Card>
  <ul>
    <li><strong>Node.js ≥ 18</strong>（v20でテスト済み）</li>
    <li>サンプルを<code>ts‑node</code>で実行する場合は<strong>TypeScript ≥ 5</strong></li>
    <li>任意の<strong>Heliusプラン</strong> – すべてのプラン階層で機能します</li>
    <li>APIキーを保存する<code>HELIUS\_API\_KEY</code>という名前の<strong>環境変数</strong></li>
  </ul>

  <Tip>
    依存関係をグローバルにインストール：<code>npm i -g typescript ts‑node</code>
  </Tip>
</Card>

## 実装

<Steps>
  <Step title="依存関係をインストール">
    ```bash theme={"system"}
    npm install ws
    ```
  </Step>

  <Step title="WebSocketクライアントを作成">
    次のコードを含む`standard-ws-pump.ts`という名前のファイルを作成します。

    ```ts theme={"system"}
    // standard-ws-pump.ts
    import WebSocket from 'ws';

    // Configuration
    const MAX_RETRIES = 5;
    const INITIAL_RETRY_DELAY = 1000; // 1 second
    let retryCount = 0;
    let retryTimeout: NodeJS.Timeout | null = null;
    let subscriptionId: number | null = null;

    // Create a WebSocket connection
    let ws: WebSocket;

    function connect() {
      ws = new WebSocket(`wss://mainnet.helius-rpc.com/?api-key=${process.env.HELIUS_API_KEY}`);

      // Function to send a request to the WebSocket server
      function sendRequest(ws: WebSocket): void {
        const request = {
          "jsonrpc": "2.0",
          "id": 1,
          "method": "logsSubscribe",
          "params": [
            {
              "mentions": ["pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"]
            }
          ]
        };
        console.log('Sending subscription request:', JSON.stringify(request, null, 2));
        ws.send(JSON.stringify(request));
      }

      // Function to send a ping to the WebSocket server
      function startPing(ws: WebSocket): void {
        setInterval(() => {
          if (ws.readyState === WebSocket.OPEN) {
            ws.ping();
            console.log('Ping sent');
          }
        }, 30000); // Ping every 30 seconds
      }

      // Define WebSocket event handlers
      ws.on('open', function open() {
        console.log('WebSocket is open');
        retryCount = 0; // Reset retry count on successful connection
        sendRequest(ws); // Send a request once the WebSocket is open
        startPing(ws); // Start sending pings
      });

      ws.on('message', function incoming(data: WebSocket.Data) {
        const messageStr = data.toString('utf8');
        try {
          const messageObj = JSON.parse(messageStr);

          // Handle subscription confirmation
          if (messageObj.result && typeof messageObj.result === 'number') {
            subscriptionId = messageObj.result;
            console.log('Successfully subscribed with ID:', subscriptionId);
            return;
          }

          // Handle actual log data
          if (messageObj.params && messageObj.params.result) {
            const logData = messageObj.params.result;
            console.log('Received log data:', JSON.stringify(logData, null, 2));
            
            // Extract the transaction signature if available
            if (logData.signature) {
              console.log('Transaction signature:', logData.signature);
              // You can call getTransaction with this signature to get the full transaction details
            }
          } else {
            console.log('Received message:', JSON.stringify(messageObj, null, 2));
          }
        } catch (e) {
          console.error('Failed to parse JSON:', e);
        }
      });

      ws.on('error', function error(err: Error) {
        console.error('WebSocket error:', err);
      });

      ws.on('close', function close() {
        console.log('WebSocket is closed');
        if (subscriptionId) {
          console.log('Last subscription ID was:', subscriptionId);
        }
        reconnect();
      });
    }

    function reconnect() {
      if (retryCount >= MAX_RETRIES) {
        console.error('Max retry attempts reached. Please check your connection and try again.');
        return;
      }

      const delay = INITIAL_RETRY_DELAY * Math.pow(2, retryCount);
      console.log(`Attempting to reconnect in ${delay/1000} seconds... (Attempt ${retryCount + 1}/${MAX_RETRIES})`);

      retryTimeout = setTimeout(() => {
        retryCount++;
        connect();
      }, delay);
    }

    // Start the initial connection
    connect();

    // Cleanup function
    process.on('SIGINT', () => {
      if (retryTimeout) {
        clearTimeout(retryTimeout);
      }
      if (ws) {
        ws.close();
      }
      process.exit();
    });
    ```
  </Step>

  <Step title="環境変数を設定">
    Helius APIキーを環境変数として追加します：

    ```bash theme={"system"}
    export HELIUS_API_KEY=your-helius-api-key
    ```

    `your-helius-api-key`をダッシュボードからの実際のHelius APIキーに置き換えます。

    APIキーがない場合は、[サインアップ](https://dashboard.helius.dev/signup)するか、エージェントに[Helius CLI](https://www.helius.dev/docs/api-reference/helius-cli)でプログラム的に作成させてください。
  </Step>

  <Step title="アプリケーションを実行">
    Pump AMMデータのストリームを開始するスクリプトを実行します：

    ```bash theme={"system"}
    npx ts-node standard-ws-pump.ts
    ```

    Pump AMMプログラムに言及するログメッセージを受け取ります。完全なトランザクションを取得するには、ログエントリからの署名で[`getTransaction`](/ja/api-reference/rpc/http/gettransaction)を呼び出します。
  </Step>
</Steps>

## 主な利点

* **ユニバーサルアクセス** - 無料プランを含むすべてのHeliusプランで利用可能
* **軽量** - 完全なトランザクションではなくログのみがストリームされるためデータ転送が最小限
* **実装が簡単** - 標準のSolana RPC WebSocketプロトコルを使用
* **低い参入障壁** - プロトタイピングと初期モニタリングに最適

## 完全なトランザクション詳細の取得

標準WebSocketはログメッセージのみを提供するため、完全なトランザクションデータを取得するには追加のステップが必要です：

```ts theme={"system"}
// Example of how to fetch a full transaction from a log entry
async function fetchFullTransaction(signature: string) {
  const response = await fetch(`https://mainnet.helius-rpc.com/?api-key=${process.env.HELIUS_API_KEY}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 'my-id',
      method: 'getTransaction',
      params: [
        signature,
        {
          encoding: 'jsonParsed',
          maxSupportedTransactionVersion: 0
        }
      ]
    })
  });
  
  const data = await response.json();
  return data.result;
}
```

## 一般的な問題と解決策

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    HELIUS\_API\_KEYが正しいことを確認してください。
  </Accordion>

  <Accordion title="ログが受信されない">
    Pump AMMプログラムアドレスが正しいことを確認し、プログラムにアクティビティがあることを確認してください。
  </Accordion>

  <Accordion title="接続が切れる">
    より堅牢な再接続ロジックを実装するか、ネットワークの安定性を確認してください。
  </Accordion>
</AccordionGroup>
