跳转到主要内容

安装

npm install @chainstream-io/sdk

快速开始

import { ChainStreamClient } from '@chainstream-io/sdk';

const client = new ChainStreamClient('YOUR_ACCESS_TOKEN');

REST API 示例

查询代币信息:
import { ChainStreamClient } from '@chainstream-io/sdk';

const ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN';

async function main() {
  // 初始化 SDK 客户端
  const client = new ChainStreamClient(ACCESS_TOKEN);

  const chain = 'sol';
  const tokenAddress = 'So11111111111111111111111111111111111111112'; // SOL

  console.log(`查询代币: ${chain}/${tokenAddress}`);

  try {
    // 通过 SDK 调用 API
    const result = await client.token.getToken(chain, tokenAddress);
    
    console.log('结果:');
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    console.error('API 调用失败:', error);
  }
}

main();

WebSocket 示例

订阅实时代币 K 线数据:
import { ChainStreamClient, Resolution } from '@chainstream-io/sdk';

const ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN';

async function main() {
  const client = new ChainStreamClient(ACCESS_TOKEN, {
    autoConnectWebSocket: true,
  });

  const chain = 'sol';
  const tokenAddress = 'So11111111111111111111111111111111111111112'; // SOL

  console.log(`订阅代币 K 线: ${chain}/${tokenAddress}`);
  console.log('监听中... (按 Ctrl+C 停止)\n');

  // 通过 SDK 订阅 WebSocket
  client.stream.subscribeTokenCandles({
    chain,
    tokenAddress,
    resolution: Resolution['1s'],
    callback: data => {
      console.log(new Date().toISOString(), JSON.stringify(data));
    },
  });

  // 保持进程运行
  process.on('SIGINT', () => {
    console.log('\n关闭连接...');
    process.exit(0);
  });

  // 持续运行
  await new Promise(() => {});
}

main().catch(error => {
  console.error('测试失败:', error.message);
  process.exit(1);
});

更多示例

搜索代币

const results = await client.token.searchToken('bonk');
console.log(results);
完整参数说明见 Token - Search

获取交易列表

const trades = await client.trade.getTrades('sol', {
  tokenAddress: 'TOKEN_ADDRESS',
  limit: 20,
});
console.log(trades);
完整参数说明见 Trade - List

获取钱包盈亏(PnL)

const pnl = await client.wallet.getPnl('sol', 'WALLET_ADDRESS');
console.log(`Total PnL: ${pnl.totalPnlUsd}`);
完整参数说明见 Wallet - PnL

获取代币 K 线

const candles = await client.token.getCandles('sol', 'TOKEN_ADDRESS', {
  resolution: '1h',
  limit: 24,
});
for (const c of candles) {
  console.log(`${c.time}: O=${c.open} H=${c.high} L=${c.low} C=${c.close}`);
}
完整参数说明见 Token - Candles

获取新币排行

const newTokens = await client.ranking.getNewTokens('sol');
for (const token of newTokens) {
  console.log(`${token.symbol}: ${token.address}`);
}
完整参数说明见 Ranking - New Tokens

错误处理

import { ChainStreamClient, ChainStreamError } from '@chainstream-io/sdk';

try {
  const token = await client.token.getToken('sol', 'INVALID_ADDRESS');
} catch (error) {
  if (error instanceof ChainStreamError) {
    console.error(`Error code: ${error.code}`);
    console.error(`Error message: ${error.message}`);
  }
}

指数退避重试

遇到限流(HTTP 429)时,可实现重试逻辑:
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (error instanceof ChainStreamError && error.code === 429 && attempt < maxRetries) {
        const delay = Math.pow(2, attempt) * 1000;
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
  throw new Error('Max retries exceeded');
}

const token = await withRetry(() => client.token.getToken('sol', 'TOKEN_ADDRESS'));

相关资源

GitHub

查看源代码

npm

包管理器