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

# TypeScript

> ChainStream TypeScript/JavaScript SDK

## 설치

<CodeGroup>
  ```bash npm theme={null}
  npm install @chainstream-io/sdk
  ```

  ```bash yarn theme={null}
  yarn add @chainstream-io/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @chainstream-io/sdk
  ```
</CodeGroup>

## 빠른 시작

```typescript theme={null}
import { ChainStreamClient } from '@chainstream-io/sdk';

const client = new ChainStreamClient('YOUR_ACCESS_TOKEN');
```

## REST API 예제

토큰 정보 조회:

```typescript theme={null}
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(`Querying Token: ${chain}/${tokenAddress}`);

  try {
    // SDK를 통해 API 호출
    const result = await client.token.getToken(chain, tokenAddress);
    
    console.log('Result:');
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    console.error('API call failed:', error);
  }
}

main();
```

## WebSocket 예제

실시간 토큰 캔들 데이터 구독:

```typescript theme={null}
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(`Subscribing to Token Candles: ${chain}/${tokenAddress}`);
  console.log('Listening... (Press Ctrl+C to stop)\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('\nClosing connection...');
    process.exit(0);
  });

  // 계속 실행
  await new Promise(() => {});
}

main().catch(error => {
  console.error('Test failed:', error.message);
  process.exit(1);
});
```

## 추가 예제

### 토큰 검색

```typescript theme={null}
const results = await client.token.searchToken('bonk');
console.log(results);
```

전체 파라미터는 [Token - Search](/ko/api-reference/endpoint/data/token/v2/token-search-get)를 참조하세요.

### 거래 목록 조회

```typescript theme={null}
const trades = await client.trade.getTrades('sol', {
  tokenAddress: 'TOKEN_ADDRESS',
  limit: 20,
});
console.log(trades);
```

전체 파라미터는 [Trade - List](/ko/api-reference/endpoint/data/trade/v2/trade-chain-get)를 참조하세요.

### 지갑 손익(PnL) 조회

```typescript theme={null}
const pnl = await client.wallet.getPnl('sol', 'WALLET_ADDRESS');
console.log(`Total PnL: ${pnl.totalPnlUsd}`);
```

전체 파라미터는 [Wallet - PnL](/ko/api-reference/endpoint/data/wallet/v2/wallet-chain-walletaddress-pnl-get)를 참조하세요.

### 토큰 캔들(K선) 조회

```typescript theme={null}
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](/ko/api-reference/endpoint/data/token/v2/token-chain-tokenaddress-candles-get)를 참조하세요.

### 신규 토큰 랭킹 조회

```typescript theme={null}
const newTokens = await client.ranking.getNewTokens('sol');
for (const token of newTokens) {
  console.log(`${token.symbol}: ${token.address}`);
}
```

전체 파라미터는 [Ranking - New Tokens](/ko/api-reference/endpoint/data/ranking/v2/ranking-chain-newtokens-get)를 참조하세요.

***

## 오류 처리

```typescript theme={null}
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) 발생 시 재시도 로직:

```typescript theme={null}
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'));
```

***

## 리소스

<CardGroup cols={2}>
  <Card title="GitHub" icon="github" href="https://github.com/chainstream-io/chainstream-sdk/tree/main/typescript">
    소스 코드 보기
  </Card>

  <Card title="npm" icon="npm" href="https://www.npmjs.com/package/@chainstream-io/sdk">
    패키지 레지스트리
  </Card>
</CardGroup>
