跳轉到主要內容

安裝

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

套件管理器