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

# Cách truyền phát dữ liệu Solana Pump AMM

> Tìm hiểu cách truyền phát trực tiếp dữ liệu Solana Pump AMM bằng LaserStream WebSocket. Tính năng giám sát dựa trên nhật ký có trên tất cả các gói, kèm khả năng tự động kết nối lại.

## Sử dụng LaserStream WebSocket

<p>
  [LaserStream WebSocket](/docs/vi/rpc/websocket) cung cấp khả năng tích hợp WebSocket đơn giản và có trên tất cả các gói Helius, nên đây là lựa chọn thuận tiện cho nhà phát triển. Ví dụ này sử dụng phương thức `logsSubscribe` của Solana, vì vậy bạn chỉ nhận được thông báo nhật ký.
</p>

<Tip>
  LaserStream WebSocket nhanh hơn tới 200 ms so với cách triển khai WebSocket tiêu chuẩn dựa trên Agave RPC.
</Tip>

### Cách hoạt động

Kết nối với [điểm cuối LaserStream WebSocket](https://www.helius.dev/docs/api-reference/endpoints), đăng ký nhận nhật ký đề cập đến [chương trình Pump AMM](https://orbmarkets.io/address/pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA/history) và xử lý dữ liệu nhật ký đến.

Ví dụ dưới đây có logic tự động kết nối lại với khoảng chờ tăng theo cấp số nhân.

## Yêu cầu

<Card>
  <ul>
    <li><strong>Node.js ≥ 18</strong> (đã kiểm thử với v20)</li>
    <li><strong>TypeScript ≥ 5</strong> nếu bạn định chạy các mẫu <code>.ts</code> bằng <code>ts‑node</code></li>
    <li>Bất kỳ <strong>gói Helius</strong> nào – hoạt động với mọi cấp gói</li>
    <li>Một <strong>biến môi trường</strong> có tên <code>HELIUS\_API\_KEY</code> để lưu khóa API của bạn</li>
  </ul>

  <Tip>
    Cài đặt các phần phụ thuộc trên toàn hệ thống: <code>npm i -g typescript ts‑node</code>
  </Tip>
</Card>

## Triển khai

<Steps>
  <Step title="Install Dependencies">
    ```bash theme={"system"}
    npm install ws
    ```
  </Step>

  <Step title="Create the WebSocket Client">
    Tạo tệp có tên `standard-ws-pump.ts` với mã sau:

    ```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="Set Environment Variables">
    Thêm khóa API Helius của bạn dưới dạng biến môi trường:

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

    Thay `your-helius-api-key` bằng khóa API Helius thực tế của bạn từ bảng điều khiển.

    Nếu chưa có khóa API, hãy [đăng ký](https://dashboard.helius.dev/signup) hoặc yêu cầu tác nhân của bạn tạo khóa theo cách lập trình bằng [Helius CLI](/docs/vi/agents/cli).
  </Step>

  <Step title="Run the Application">
    Thực thi tập lệnh để bắt đầu truyền phát dữ liệu Pump AMM:

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

    Bạn sẽ nhận được các thông báo nhật ký đề cập đến chương trình Pump AMM. Để truy xuất toàn bộ giao dịch, hãy gọi [`getTransaction`](/docs/vi/api-reference/rpc/http/gettransaction) bằng chữ ký từ mục nhật ký.
  </Step>
</Steps>

## Lợi ích chính

* **Truy cập phổ quát** - Có trên tất cả các gói Helius, bao gồm cả gói miễn phí
* **Gọn nhẹ** - Giảm thiểu lượng dữ liệu truyền vì chỉ truyền phát nhật ký, không truyền toàn bộ giao dịch
* **Dễ triển khai** - Sử dụng giao thức Solana RPC WebSocket tiêu chuẩn
* **Rào cản gia nhập thấp** - Hoàn hảo để tạo nguyên mẫu và giám sát ban đầu

## Lấy đầy đủ thông tin chi tiết về giao dịch

Vì WebSocket tiêu chuẩn chỉ cung cấp thông báo nhật ký, bạn cần thực hiện thêm một bước để lấy toàn bộ dữ liệu giao dịch:

```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: 1
        }
      ]
    })
  });
  
  const data = await response.json();
  return data.result;
}
```

## Các vấn đề thường gặp và giải pháp

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    Xác minh HELIUS\_API\_KEY của bạn là chính xác.
  </Accordion>

  <Accordion title="No logs received">
    Đảm bảo địa chỉ chương trình Pump AMM là chính xác và chương trình đang có hoạt động.
  </Accordion>

  <Accordion title="Connection dropping">
    Triển khai logic kết nối lại mạnh mẽ hơn hoặc kiểm tra độ ổn định của mạng.
  </Accordion>
</AccordionGroup>
