# @chainlink/data-streams-sdk 中文文档

规范地址：https://npmcn.com/package/%40chainlink/data-streams-sdk/

版本：2\.0\.0
npm 元数据更新时间：2026-10-15T15:20:08.904Z
中文译文更新时间：2026-11-09T09:30:40.559Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40chainlink/data-streams-sdk
原文对照：https://npmcn.com/package/%40chainlink/data-streams-sdk/?lang=original
项目主页：https://github.com/smartcontractkit/data-streams-sdk/tree/main/typescript#readme
源码仓库：https://github.com/smartcontractkit/data-streams-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.2 MB，192 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.0\.0
- 运行依赖：2 个
- peer 依赖：dotenv ^16\.6\.1
- 首次发布：2025-09-18T07:42:15.930Z
- 最新版本发布：2026-10-15T15:20:07.377Z
- 近 30 天下载量：15986（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 4 个）

## 中文简介

链路链路数据流的脚本 SDK 类型

## 安装

```sh
npm install @chainlink/data-streams-sdk
```

也可以使用：`pnpm add @chainlink/data-streams-sdk`、`yarn add @chainlink/data-streams-sdk`、`bun add @chainlink/data-streams-sdk`

## README

# 链路数据流类型SDK

TypeScript SDK 用于通过实时流回和历史数据检索访问链链路数据流.

## 目录

-   [特征](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-features)
-   [安装](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-installation)
-   [快速启动](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-quick-start)
-   [配置](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-configuration)
-   [实例](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-examples)
-   [API 参考](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-api-reference)
    -   [流线](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-streaming)
    -   [流出选项](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-stream-options)
    -   [(原始内容存档于2013-10-12) (英语). REST API](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-rest-api)
-   [报表格式](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-report-format)
-   [高可用性模式](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-high-availability-mode)
-   [处理错误](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-error-handling)
-   [可观察性(Logs & Metrics)](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-observability-logs--metrics)
    -   [伐木(皮诺/温斯顿/指挥所)](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-logging-pinowinstonconsole)
    -   [量子( 流. get metrics ())](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-metrics-streamgetmetrics)
-   [测试](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-testing)
-   [种子标识](https://npmcn.com/package/%40chainlink/data-streams-sdk/#readme-feed-ids)

## 特征

-   **实时流线** 通过 WebSocket 连接
-   **高可用性模式** 有多个连接和自动失效
-   **历史数据访问** 通过 REST API
-   **自动报告解码** 所有支持格式(V2、V3、V4、V5、V6、V7、V8、V9、V10、V11、V12、V13)
-   **计量** 监测和可观察性
-   **类型安全** 完整类型脚本支持
-   **事件驱动的架构** 用于完整的开发者控制

## 安装

```bash
npm install @chainlink/data-streams-sdk
```

**所需经费:**

-   节点.js >= 20.0.0
-   类型脚本QQ 5.3.x
-   有效的链路链接数据流权限

## 快速启动

**设定您的证书 :**

备选1-环境变量:

```bash
export API_KEY="your_api_key_here"
export USER_SECRET="your_user_secret_here"
```

备选案文2 - `.env` 文件 :

```bash
# Create .env file from template
cp .env.example .env

# Edit .env with your credentials
API_KEY="your_api_key_here"
USER_SECRET="your_user_secret_here"
```

**基本流线 :**

```typescript
import { createClient, LogLevel } from '@chainlink/data-streams-sdk';

const client = createClient({
  apiKey: process.env.API_KEY,
  userSecret: process.env.USER_SECRET,
  endpoint: "https://api.dataengine.chain.link",
  wsEndpoint: "wss://ws.dataengine.chain.link",
  // Comment to disable SDK logging for debugging:
  logging: {
    logger: console,
    logLevel: LogLevel.INFO
  }
});

const feedID = '0x000359843a543ee2fe414dc14c7e7920ef10f4372990b79d6361cdc0dd1ba782';
const stream = client.createStream([feedID]);

stream.on('report', (report) => {
  console.log('New report:', report);
});

stream.on('error', (error) => {
  console.error('Stream error:', error);
});

await stream.connect();
```

## 配置

### 配置接口

```typescript
interface Config {
  // Required
  apiKey: string;                  // API key for authentication
  userSecret: string;              // User secret for authentication
  endpoint: string;                // REST API URL
  wsEndpoint: string;              // WebSocket URL

  // Optional - Request & Retry
  timeout?: number;                // Request timeout (default: 30000ms)
  retryAttempts?: number;          // Retry attempts (default: 3)
  retryDelay?: number;             // Retry delay (default: 1000ms)

  // Optional - High Availability
  haMode?: boolean;                // Enable HA mode (default: false)
  haConnectionTimeout?: number;    // HA connection timeout (default: 10000ms)
  connectionStatusCallback?: (isConnected: boolean, host: string, origin: string) => void;

  // Optional - Logging
  logging?: LoggingConfig;         // See Logging Configuration section
}
```

### 基本用途

```typescript
const client = createClient({
  apiKey: process.env.API_KEY,
  userSecret: process.env.USER_SECRET,
  endpoint: "https://api.dataengine.chain.link",
  wsEndpoint: "wss://ws.dataengine.chain.link"
});
```

### 高可用性示例

```typescript
const haClient = createClient({
  apiKey: process.env.API_KEY,
  userSecret: process.env.USER_SECRET,
  endpoint: "https://api.dataengine.chain.link",          // Mainnet only
  wsEndpoint: "wss://ws.dataengine.chain.link",           // Single endpoint with origin discovery
  haMode: true,
});
```

**说明:** 高可提供性模式只存在于主网,而非测试网.

## 实例

**快速命令 :**

```bash
# Real-time streaming
npx ts-node examples/stream-reports.ts 0x000359843a543ee2fe414dc14c7e7920ef10f4372990b79d6361cdc0dd1ba782

# High Availability streaming  
npx ts-node examples/stream-reports.ts 0x000359843a543ee2fe414dc14c7e7920ef10f4372990b79d6361cdc0dd1ba782 --ha

# Get latest report
npx ts-node examples/get-latest-report.ts 0x000359843a543ee2fe414dc14c7e7920ef10f4372990b79d6361cdc0dd1ba782

# List all available feeds
npx ts-node examples/list-feeds.ts
```

**完整实例 :**  
见 [`examples/README.md`](https://npmcn.com/package/%40chainlink/data-streams-sdk/examples/README.md) 详细使用说明、设置和所有可用实例,包括:

-   **流线 :** 基本流线、HA模式、度量衡监测
-   **瑞斯・阿普:** 最近的报告、历史数据、散装作业、饲料管理
-   **配置 :** 日志设置、 调试、 监控集成

## API 参考

### 流线

```typescript
// Create stream
const stream = client.createStream(feedIds, options?);

// Events
stream.on('report', (report) => { ... });
stream.on('error', (error) => { ... });
stream.on('disconnected', () => { ... });
stream.on('reconnecting', (info) => { ... });

// Control
await stream.connect();
await stream.close();

// Metrics
const metrics = stream.getMetrics();
```

### 流出选项

```typescript
interface StreamOptions {
  maxReconnectAttempts?: number;  // Default: 5
  // Base delay (in ms) for exponential backoff.
  // Actual delay grows as: base * 2^(attempt-1) with jitter, capped at 10000ms.
  // Default: 1000ms; user-provided values are clamped to the safe range [200ms, 10000ms].
  reconnectInterval?: number;
}
```

### (原始内容存档于2013-10-12) (英语). REST API

```typescript
// Get feeds
const feeds = await client.listFeeds();

// Get latest report
const report = await client.getLatestReport(feedId);

// Get historical report
const report = await client.getReportByTimestamp(feedId, timestamp);

// Get report page
const reports = await client.getReportsPage(feedId, startTime, limit?);

// Get bulk reports
const reports = await client.getReportsBulk(feedIds, timestamp);
```

## 报表格式

### 快速解码器使用

```typescript
import { decodeReport } from '@chainlink/data-streams-sdk';
const decoded = decodeReport(report.fullReport, report.feedID);
```

### Schema 自动检测

SDK根据Feed ID模式自动检测并解码所有报告版本:

-   **五. 2级**: 种子标识从 `0x0002`
-   **五.3**: 种子标识从 `0x0003` (Crypto流) (英语)
-   **五. 四级**: 种子标识从 `0x0004` (实际世界资产)
-   **五. 区域5**: 种子标识从 `0x0005`
-   **五进制6**: 种子标识从 `0x0006` (多价格价值)
-   **V7 数据**: 种子标识从 `0x0007`
-   **V8 请检查URL=值 (帮助)**: 种子标识从 `0x0008` (无OTC RWA)
-   **五、九类**: 种子标识从 `0x0009` (NAV基金数据)
-   **V10型**: 种子标识从 `0x000a` (股权)
-   **V11 数据**: 种子标识从 `0x000b` (德国布尔斯)
-   **V12 数据**: 种子标识从 `0x000c` (Nav基金数据+下一个)
-   **V13型**: 种子标识从 `0x000d` (最佳投标/索取)

### 共同领域

所有报告都包括标准元数据:

```typescript
interface BaseFields {
  version: "V2" | "V3" | "V4" | "V5" | "V6" | "V7" | "V8" | "V9" | "V10" | "V11" | "V12" | "V13";
  nativeFee: bigint;
  linkFee: bigint;
  expiresAt: number;
  feedID: string;
  validFromTimestamp: number;
  observationsTimestamp: number;
}
```

### Schema 特定字段

-   **V2/V3/V4号机**数字 : `price: bigint` - 标准价格数据
-   **五.3**数字 : `bid: bigint, ask: bigint` - 加密出价/任务分配
-   **五. 四级**数字 : `marketStatus: MarketStatus` - 真实世界资产市场状况
-   **五. 区域5**数字 : `rate: bigint, timestamp: number, duration: number` - 有观察时间戳和持续时间的利率数据
-   **五进制6**数字 : `price: bigint, price2: bigint, price3: bigint, price4: bigint, price5: bigint` - 单一有效载荷的多价值
-   **V7 数据**数字 : `exchangeRate: bigint` - 汇率数据
-   **V8 请检查URL=值 (帮助)**数字 : `midPrice: bigint, lastUpdateTimestamp: bigint, marketStatus: MarketStatus` - 非OTC RWA数据(`lastUpdateTimestamp` 是准确的纳秒 `uint64`(中文(简体) )
-   **五、九类**数字 : `navPerShare: bigint, navDate: number, aum: bigint, ripcord: number` - NAV基金数据
-   **V10型**数字 : `price: bigint, lastUpdateTimestamp: bigint, marketStatus: MarketStatus, currentMultiplier: bigint, newMultiplier: bigint, activationDateTime: number, tokenizedPrice: bigint` - 股权化数据(`lastUpdateTimestamp` 是准确的纳秒 `uint64`(中文(简体) )
-   **V11 数据**数字 : `mid: bigint, LastSeenTimestampNs: number, bid: bigint, vidVolume: number, ask: bigint, askVolume: number, lastTradedPrice: bigint, marketStatus: MarketStatus` - 德国布尔斯
-   **V12 数据**数字 : `navPerShare: bigint, nextNavPerShare: bigint, navDate: number, ripcord: number` - NAV基金数据+下一个
-   **V13型**数字 : `bestAsk: bigint, bestBid: bigint, askVolume: number, bidVolume: number, lastTradedPrice: bigint` - 最佳投标/索取
-   **五十四国**数字 : `midPrice: bigint, bidPrice: bigint, askPrice: bigint, expiryTime: bigint, firstDayOfNotice: bigint, lastSeenTimestampNs: bigint, marketStatus: MarketStatus, contractMonth: number, goldmanRollPrice: bigint, currentBusinessDay: number, interpolatedGoldmanRollPrice: bigint` - 连续商品期货

完整字段定义见 [文档](https://docs.chain.link/data-streams/reference/report-schema-v3)。 。 。 .

## 高可用性模式

HA 模式为零下限操作建立多个同步连接 :

-   **自动失效** 连接之间
-   **报告重复** 跨连接
-   **自动查找来源** 查找可用的端点
-   **连接监测** 统计

```typescript
const client = createClient({
  // ...config
  haMode: true,
  wsEndpoint: "wss://ws.dataengine.chain.link",  // Single endpoint (mainnet only)
});
```

**如何运作:** 何时 `haMode` 实值 `true`,SDK会自动在单个URL后发现多个起源端点,并与每个起源建立单独的连接.

**连接监视 :** 可选 `connectionStatusCallback` 可用于与外部监测系统相融合。 SDK已经提供了全面的连接日志,因此这种回调主要用于自定义提醒或度量衡集合. 见 [`examples/metrics-monitoring.ts`](https://npmcn.com/package/%40chainlink/data-streams-sdk/examples/metrics-monitoring.ts) 以完整实施为例.

**重要内容:** HA模式只在主网端点上可用.

## 处理错误

### 错误类型概览

| **错误类型** | **当抛出时** | **密钥属性** |
| --- | --- | --- |
| `ValidationError` | 无效的种子ID、 时间戳、 参数 | `message` |
| `AuthenticationError` | 无效的证书, HMAC 失败 | `message` |
| `APIError` | HTTP 4xxx/5xxx,网络超时,限速 | `statusCode`, (中文(简体) ), `message` |
| `ReportDecodingError` | 已损坏的报告数据, 不支持的版本 | `message` |
| `WebSocketError` | 连接失败, 协议错误 | `message` |
| `OriginDiscoveryError` | HA 发现失败 | `cause`, (中文(简体) ), `message` |
| `MultiConnectionError` | 所有 HA 连接失败 | `message` |
| `PartialConnectionFailureError` | 一些 HA 连接失败 | `failedConnections`, (中文(简体) ), `totalConnections` |
| `InsufficientConnectionsError` | HA 退化的性能 | `availableConnections`, (中文(简体) ), `requiredConnections` |

### 用法实例

```typescript
import {
  ValidationError,
  AuthenticationError,
  APIError,
  ReportDecodingError,
  WebSocketError,
  OriginDiscoveryError,
  MultiConnectionError
} from './src';

// REST API error handling
try {
  const report = await client.getLatestReport(feedId);
} catch (error) {
  if (error instanceof ValidationError) {
    // Invalid feed ID or parameters
  } else if (error instanceof AuthenticationError) {
    // Check API credentials
  } else if (error instanceof APIError) {
    // Server error - check error.statusCode (429, 500, etc.)
  } else if (error instanceof ReportDecodingError) {
    // Corrupted or unsupported report format
  }
}

// Streaming error handling
stream.on('error', (error) => {
  if (error instanceof WebSocketError) {
    // Connection issues - retry or fallback
  } else if (error instanceof OriginDiscoveryError) {
    // HA discovery failed - falls back to static config
  } else if (error instanceof MultiConnectionError) {
    // All HA connections failed - critical
  }
});
```

**全部抓取错误处理 :**

```typescript
import { DataStreamsError } from './src';

try {
  // Any SDK operation
} catch (error) {
  if (error instanceof DataStreamsError) {
    // Handles ANY SDK error (base class for all error types above)
    console.log('SDK error:', error.message);
  } else {
    // Non-SDK error (network, system, etc.)
    console.log('System error:', error);
  }
}
```

## 可观察性(Logs & Metrics)

SDK是用来插入你现有的可观察堆栈的.

### 伐木(皮诺/温斯顿/指挥所)

将您的日志传递给 SDK 并选择一个动词级别 。 对于深WS诊断,启用连接调试.

### 快速启动

```typescript
import { createClient, LogLevel } from '@chainlink/data-streams-sdk';

// Silent mode (default) - Zero overhead
const client = createClient({ /* ... config without logging */ });

// Basic console logging
const client = createClient({
  // ... other config
  logging: {
    logger: {
      info: console.log,
      warn: console.warn,
      error: console.error
    }
  }
});
```

使用皮诺(结构为JSON):

```typescript
import pino from 'pino';
import { createClient, LogLevel } from '@chainlink/data-streams-sdk';

const root = pino({ level: process.env.PINO_LEVEL || 'info' });
const sdk = root.child({ component: 'sdk' });

const client = createClient({
  // ...config
  logging: {
    logger: {
      info: sdk.info.bind(sdk),
      warn: sdk.warn.bind(sdk),
      error: sdk.error.bind(sdk),
      debug: sdk.debug.bind(sdk),
    },
    logLevel: LogLevel.INFO,
    // For very verbose WS diagnostics, set DEBUG + enableConnectionDebug
    // logLevel: LogLevel.DEBUG,
    // enableConnectionDebug: true,
  },
});
```

输出漂亮的命令行 :

```bash
PINO_LEVEL=info npx ts-node examples/metrics-monitoring.ts | npx pino-pretty
```

### 日志级别

| 错误 | 战争 | • INFO | 迪布格语 |
| --- | --- | --- | --- |
| **只有重大故障** | **错误中的一切 +** | **在WARN + 中的一切** | **INFO + 中的所有内容** |
| \- 认证失败  
\- 网络连接出错  
\- 报告解码失败  
\- API 请求失败  
\- 意外撞车 | \- 部分重联  
\- 回归静态起源  
\- 重试尝试  
\- 连接超时  
\- 无效的数据警告 | \- 客户初始化  
\- API电话成功  
\- 串流连接  
\- 报告检索  
\- 连接状态变化  
\- 连接模式的确定 | \- 种子ID验证  
\- 报告解码步骤  
\- 认证头生成  
\- 请求/答复详情  
\- 网球乒乓球  
\- 起源发现过程  
\- 配置验证  
\- 来源跟踪(HA模式) |
| **示例使用:**  
生产警报和监测 | **示例使用:**  
生产环境 | **示例使用:**  
开发和实施 | **示例使用:**  
只调试开发( D) |

### 日志配置选项

```typescript
interface LoggingConfig {
  /** External logger functions (console, winston, pino, etc.) */
  logger?: {
    debug?: (message: string, ...args: any[]) => void;
    info?: (message: string, ...args: any[]) => void;
    warn?: (message: string, ...args: any[]) => void;
    error?: (message: string, ...args: any[]) => void;
  };

  /** Minimum logging level - filters out lower priority logs */
  logLevel?: LogLevel; // DEBUG (0) | INFO (1) | WARN (2) | ERROR (3)

  /** Enable WebSocket ping/pong and connection state debugging logs */
  enableConnectionDebug?: boolean;
}
```

**与 :** 控制台 温顿 皮诺 和任何与 `debug/info/warn/error` 方法。 。 。 见 `examples/logging-basic.ts` 为完整的整合实例.

**调试时 :** 使用 `LogLevel.DEBUG` 全面诊断 `enableConnectionDebug: true` 以查看 WebSocket 乒乓球信息和连接状态过渡.

**来源跟踪** 以 HA 模式显示每个报告的具体端点.

### 计量(`stream.getMetrics()`(中文(简体) )

这个 `stream.getMetrics()` API为仪表板和提示提供了完整的快照:

```typescript
const m = stream.getMetrics();
// m.accepted, m.deduplicated, m.totalReceived
// m.partialReconnects, m.fullReconnects
// m.activeConnections, m.configuredConnections
// m.originStatus: { [origin]: ConnectionStatus }
```

简单周期打印( 例如 ) :

```typescript
setInterval(() => {
  const m = stream.getMetrics();
  console.log(`accepted=${m.accepted} dedup=${m.deduplicated} active=${m.activeConnections}/${m.configuredConnections}`);
}, 30000);
```

参见 `examples/metrics-monitoring.ts` 以完整度量仪表板为例.

## 测试

```bash
npm test                 # All tests
npm run test:unit        # Unit tests only
npm run test:integration # Integration tests only
```

## 种子标识

关于可用的种子标识,见 [正式文件](https://docs.chain.link/data-streams/crypto-streams)。 。 。 .

## 常见问题

### @chainlink/data-streams-sdk 是什么？

链路链路数据流的脚本 SDK 类型

### 如何安装 @chainlink/data-streams-sdk？

在项目目录运行 npm install @chainlink/data-streams-sdk，或使用 pnpm add / yarn add / bun add。

### @chainlink/data-streams-sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @chainlink/data-streams-sdk 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @chainlink/data-streams-sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @chainlink/data-streams-sdk 可以商用吗？

@chainlink/data-streams-sdk 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @chainlink/data-streams-sdk 的下载量有多少？

根据 npm 官方下载统计，@chainlink/data-streams-sdk 在 2026/10/10 – 2026/11/08 这 30 天内被下载 15,986 次，日均约 533 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @chainlink/data-streams-sdk 还在维护吗？

最新版本 2\.0\.0 发布于 2026/10/15（24 天前）；至今共发布 10 个版本，其中过去 12 个月发布了 4 个；首次发布于 2025/09/18。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

