> ## Documentation Index
> Fetch the complete documentation index at: https://docs.solanatracker.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 快速入门指南

> 几分钟内开始使用 Yellowstone gRPC 流——安装客户端、完成身份验证并订阅 Solana 上实时的 slot、区块与交易数据。

## 什么是 Yellowstone gRPC?

Yellowstone gRPC 通过高性能流式传输提供对 Solana 区块链数据的直接访问。与传统 RPC 轮询不同,gRPC 以最小延迟提供实时更新,非常适合:

* **交易机器人** - 通过实时数据更快执行交易
* **DeFi 应用** - 即时监控流动性池和代币兑换
* **分析平台** - 即时追踪链上活动
* **套利系统** - 以毫秒级精度检测机会

## 快速开始

<Steps>
  <Step title="订阅 Yellowstone gRPC">
    独立 gRPC 方案 **€200/月**，或与 RPC Business、Professional 方案免费捆绑。详见 [定价与限制](/cn/pricing)。

    [订阅 Yellowstone gRPC](https://www.solanatracker.io/account/rpc)

    **您将获得:**

    * **两个区域端点:**
      * 欧盟区: `https://grpc.solanatracker.io`
      * 美国区: `https://grpc-us.solanatracker.io`
    * **Jito Shreds** - 数据交付快 50-100 毫秒
    * **无带宽费用** - 无限数据流
    * **24/7 正常运行** - 自动故障切换和监控

    <Note>
      选择离您基础设施最近的端点以获得最佳性能。在同一数据中心同址部署以获得亚毫秒级延迟。
    </Note>
  </Step>

  <Step title="获取您的 API 凭据">
    订阅后,检索您的身份验证凭据:

    [获取您的 API 令牌](https://www.solanatracker.io/account/rpc)

    您将收到:

    * **x-token** - 您用于 gRPC 请求的身份验证令牌
    * **端点 URL** - 欧盟和美国区域
    * **配置指南** - 推荐设置

    <Warning>
      **请妥善保管您的令牌!**

      * 切勿将令牌提交到版本控制
      * 使用环境变量
      * 定期轮换令牌
    </Warning>
  </Step>

  <Step title="安装依赖">
    安装 Yellowstone gRPC 客户端:

    ```bash theme={null}
    npm install @triton-one/yellowstone-grpc
    ```
  </Step>
</Steps>

## 完整工作示例

下面是一个完整的、生产可用的示例,用于监控交易:

```javascript theme={null}
const Client = require("@triton-one/yellowstone-grpc").default;
const { CommitmentLevel } = require("@triton-one/yellowstone-grpc");

// Initialize and connect to Yellowstone gRPC
const getClient = async () => {
  let client = false;
  try {
    client = new Client(
      "https://grpc.solanatracker.io",
      "your-api-key-here",
      {
        "grpc.max_receive_message_length": 100 * 1024 * 1024,
      }
    );
    const version = await client.getVersion();
    if (version) {
      console.log("Connected! Version:", version);
      return client;
    }
  } catch (e) {
    console.error("Failed to connect:", e);
  }
  if (!client) {
    throw new Error("Failed to connect!");
  }
};

(async () => {
  const client = await getClient();
  const stream = await client.subscribe();

  // Handle stream lifecycle
  const streamClosed = new Promise((resolve, reject) => {
    stream.on("error", (error) => {
      console.error("Stream error:", error);
      reject(error);
    });
    stream.on("end", () => {
      console.log("Stream ended");
      resolve();
    });
    stream.on("close", () => {
      console.log("Stream closed");
      resolve();
    });
  });

  // Handle incoming data
  stream.on("data", (data) => {
    if (data?.transaction) {
      const tx = data.transaction.transaction;
      console.log("\n[Transaction]");
      console.log("  Signature:", tx.signature);
      console.log("  Slot:", data.transaction.slot);
      console.log("  Success:", !tx.meta?.err);
      if (tx.meta?.fee) {
        console.log("  Fee:", (tx.meta.fee / 1e9).toFixed(6), "SOL");
      }
    }
  });

  // Subscribe to Token Program transactions
  const request = {
    accounts: {},
    slots: {},
    transactions: {
      tokenTransactions: {
        vote: false,
        failed: false,
        signature: undefined,
        accountInclude: ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"],
        accountExclude: [],
        accountRequired: [],
      },
    },
    transactionsStatus: {},
    entry: {},
    blocks: {},
    blocksMeta: {},
    accountsDataSlice: [],
    ping: undefined,
    commitment: CommitmentLevel.CONFIRMED,
  };

  // Send subscribe request
  await new Promise((resolve, reject) => {
    stream.write(request, (err) => {
      if (err === null || err === undefined) {
        console.log("Subscribed to Token Program transactions");
        resolve();
      } else {
        reject(err);
      }
    });
  }).catch((reason) => {
    console.error("Subscribe failed:", reason);
    throw reason;
  });

  await streamClosed;
})();
```

## 此示例的功能

1. **连接到 Yellowstone gRPC**,带有适当的错误处理
2. **创建流**,带有生命周期事件处理程序
3. **订阅交易**,涉及代币程序
4. **处理每笔交易**并记录关键详情
5. **优雅地处理错误**,具有适当的清理

## 监控不同的数据类型

<Tabs>
  <Tab title="账户更新">
    **监控账户变化:**

    ```javascript theme={null}
    const request = {
      accounts: {
        myAccounts: {
          account: ["YourAccountAddress"],
          owner: [],
          filters: []
        }
      },
      slots: {},
      transactions: {},
      transactionsStatus: {},
      entry: {},
      blocks: {},
      blocksMeta: {},
      accountsDataSlice: [],
      ping: undefined,
      commitment: CommitmentLevel.CONFIRMED,
    };

    stream.on("data", (data) => {
      if (data?.account) {
        const account = data.account.account;
        console.log("Account Update:", account.pubkey);
        console.log("Lamports:", account.lamports);
      }
    });
    ```
  </Tab>

  <Tab title="Slot 更新">
    **监控网络 slot:**

    ```javascript theme={null}
    const request = {
      accounts: {},
      slots: {
        slotSubscribe: {}
      },
      transactions: {},
      transactionsStatus: {},
      entry: {},
      blocks: {},
      blocksMeta: {},
      accountsDataSlice: [],
      ping: undefined,
      commitment: CommitmentLevel.CONFIRMED,
    };

    stream.on("data", (data) => {
      if (data?.slot) {
        console.log("Slot:", data.slot.slot);
        console.log("Parent:", data.slot.parentSlot);
        console.log("Status:", data.slot.status);
      }
    });
    ```
  </Tab>

  <Tab title="区块数据">
    **监控区块:**

    ```javascript theme={null}
    const request = {
      accounts: {},
      slots: {},
      transactions: {},
      transactionsStatus: {},
      entry: {},
      blocks: {},
      blocksMeta: {
        blockMetaSubscribe: {}
      },
      accountsDataSlice: [],
      ping: undefined,
      commitment: CommitmentLevel.CONFIRMED,
    };

    stream.on("data", (data) => {
      if (data?.blockMeta) {
        console.log("Block:", data.blockMeta.slot);
        console.log("Transactions:", data.blockMeta.transactionCount);
        console.log("Block Hash:", data.blockMeta.blockhash);
      }
    });
    ```
  </Tab>
</Tabs>

## 环境变量

安全地存储您的凭据:

```bash theme={null}
# .env file
GRPC_ENDPOINT=https://grpc.solanatracker.io
GRPC_API_KEY=your-api-key-here
```

```javascript theme={null}
require('dotenv').config();

const client = new Client(
  process.env.GRPC_ENDPOINT,
  process.env.GRPC_API_KEY,
  {
    "grpc.max_receive_message_length": 100 * 1024 * 1024,
  }
);
```

## 接下来做什么?

<CardGroup cols={2}>
  <Card title="交易监控" icon="receipt" iconType="duotone" href="/cn/yellowstone-grpc/transaction-monitoring">
    监控 DEX 交易和程序活动
  </Card>

  <Card title="账户监控" icon="user" iconType="duotone" href="/cn/yellowstone-grpc/account-monitoring">
    追踪代币持有者和账户变化
  </Card>

  <Card title="Pump.fun 示例" icon="chart-line" iconType="duotone" href="/cn/yellowstone-grpc/examples/pumpfun-transactions">
    构建 Pump.fun 交易机器人
  </Card>

  <Card title="最佳实践" icon="star" iconType="duotone" href="/cn/yellowstone-grpc/best-practices">
    生产环境优化
  </Card>
</CardGroup>

## 常见问题

### 我应该使用哪个端点?

**根据您的位置选择:**

* **欧洲/全球:** `https://grpc.solanatracker.io`
* **北美:** `https://grpc-us.solanatracker.io`

测试两个端点并使用从您部署区域延迟较低的那个。通过在同一数据中心同址部署达到约 1 毫秒延迟。

### 如何处理重新连接?

将您的连接逻辑包装在重试函数中:

```javascript theme={null}
async function connectWithRetry(maxRetries = 5) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await getClient();
    } catch (e) {
      console.log(`Retry ${i + 1}/${maxRetries}...`);
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
    }
  }
  throw new Error("Max retries exceeded");
}
```

### 我应该使用什么确认级别?

**确认级别:**

* **PROCESSED** - 最快,但可能被回滚
* **CONFIRMED** - 平衡速度和最终性(推荐)
* **FINALIZED** - 最慢,但保证最终化

对于大多数应用程序,`CONFIRMED` 是最佳选择。

### 如何过滤交易?

在您的订阅请求中使用过滤字段:

```javascript theme={null}
transactions: {
  myTransactions: {
    vote: false,                    // Exclude vote transactions
    failed: false,                  // Exclude failed transactions
    accountInclude: ["Address1"],   // Must include any of these (OR)
    accountRequired: ["Address2"],  // Must include all of these (AND)
    accountExclude: ["Address3"],   // Must not include any of these
  }
}
```

## 支持与资源

<CardGroup cols={2}>
  <Card title="支持" icon="headset" iconType="duotone">
    获取实施帮助

    [support@solanatracker.io](mailto:support@solanatracker.io)
  </Card>

  <Card title="Yellowstone gRPC 源代码" icon="github" iconType="brands">
    完整 protobuf 定义和协议规格

    [查看仓库](https://github.com/rpcpool/yellowstone-grpc)
  </Card>
</CardGroup>
