链路数据流类型SDK
TypeScript SDK 用于通过实时流回和历史数据检索访问链链路数据流.
目录
特征
- 实时流线 通过 WebSocket 连接
- 高可用性模式 有多个连接和自动失效
- 历史数据访问 通过 REST API
- 自动报告解码 所有支持格式(V2、V3、V4、V5、V6、V7、V8、V9、V10、V11、V12、V13)
- 计量 监测和可观察性
- 类型安全 完整类型脚本支持
- 事件驱动的架构 用于完整的开发者控制
安装
npm install @chainlink/data-streams-sdk
所需经费:
- 节点.js >= 20.0.0
- 类型脚本QQ 5.3.x
- 有效的链路链接数据流权限
快速启动
设定您的证书 :
备选1-环境变量:
export API_KEY="your_api_key_here"
export USER_SECRET="your_user_secret_here"
备选案文2 - .env 文件 :
# 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"
基本流线 :
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();
配置
配置接口
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
}
基本用途
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"
});
高可用性示例
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,
});
说明: 高可提供性模式只存在于主网,而非测试网.
实例
快速命令 :
# 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 详细使用说明、设置和所有可用实例,包括:
- 流线 : 基本流线、HA模式、度量衡监测
- 瑞斯・阿普: 最近的报告、历史数据、散装作业、饲料管理
- 配置 : 日志设置、 调试、 监控集成
API 参考
流线
// 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();
流出选项
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
// 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);
报表格式
快速解码器使用
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(最佳投标/索取)
共同领域
所有报告都包括标准元数据:
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- 连续商品期货
完整字段定义见 文档。 。 。 .
高可用性模式
HA 模式为零下限操作建立多个同步连接 :
- 自动失效 连接之间
- 报告重复 跨连接
- 自动查找来源 查找可用的端点
- 连接监测 统计
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 以完整实施为例.
重要内容: 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 |
用法实例
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
}
});
全部抓取错误处理 :
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诊断,启用连接调试.
快速启动
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):
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,
},
});
输出漂亮的命令行 :
PINO_LEVEL=info npx ts-node examples/metrics-monitoring.ts | npx pino-pretty
日志级别
| 错误 | 战争 | • INFO | 迪布格语 |
|---|---|---|---|
| 只有重大故障 | 错误中的一切 + | 在WARN + 中的一切 | INFO + 中的所有内容 |
|
- 认证失败 - 网络连接出错 - 报告解码失败 - API 请求失败 - 意外撞车 |
- 部分重联 - 回归静态起源 - 重试尝试 - 连接超时 - 无效的数据警告 |
- 客户初始化 - API电话成功 - 串流连接 - 报告检索 - 连接状态变化 - 连接模式的确定 |
- 种子ID验证 - 报告解码步骤 - 认证头生成 - 请求/答复详情 - 网球乒乓球 - 起源发现过程 - 配置验证 - 来源跟踪(HA模式) |
| 示例使用: 生产警报和监测 |
示例使用: 生产环境 |
示例使用: 开发和实施 |
示例使用: 只调试开发( D) |
日志配置选项
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为仪表板和提示提供了完整的快照:
const m = stream.getMetrics();
// m.accepted, m.deduplicated, m.totalReceived
// m.partialReconnects, m.fullReconnects
// m.activeConnections, m.configuredConnections
// m.originStatus: { [origin]: ConnectionStatus }
简单周期打印( 例如 ) :
setInterval(() => {
const m = stream.getMetrics();
console.log(`accepted=${m.accepted} dedup=${m.deduplicated} active=${m.activeConnections}/${m.configuredConnections}`);
}, 30000);
参见 examples/metrics-monitoring.ts 以完整度量仪表板为例.
测试
npm test # All tests
npm run test:unit # Unit tests only
npm run test:integration # Integration tests only
种子标识
关于可用的种子标识,见 正式文件。 。 。 .