> ## 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](/docs/ko/rpc/websocket)은 간단한 WebSocket 통합을 제공하며 모든 Helius 플랜에서 사용할 수 있어 개발자들에게 편리한 선택입니다. 이 예제는 Solana의 `logsSubscribe` 메서드를 사용하므로 로그 메시지만 받게 됩니다.
</p>

<Tip>
  LaserStream WebSocket은 표준 Agave RPC 기반 WebSocket 구현보다 최대 200ms 빠릅니다.
</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><strong>TypeScript ≥ 5</strong> <code>ts‑node</code>로 <code>.ts</code> 샘플을 실행하려면 필요합니다.</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`](/docs/ko/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>
