> ## 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

## Installation

<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>

## Quick Start

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

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

## REST API Example

Query token information:

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

const ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN';

async function main() {
  // Initialize SDK client
  const client = new ChainStreamClient(ACCESS_TOKEN);

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

  console.log(`Querying Token: ${chain}/${tokenAddress}`);

  try {
    // Call API via SDK
    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 Example

Subscribe to real-time token candle data:

```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');

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

  // Keep the process alive
  process.on('SIGINT', () => {
    console.log('\nClosing connection...');
    process.exit(0);
  });

  // Keep running
  await new Promise(() => {});
}

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

## More Examples

### Search Tokens

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

See [Token - Search](/en/api-reference/endpoint/data/token/v2/token-search-get) for full parameters.

### Get Trade List

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

See [Trade - List](/en/api-reference/endpoint/data/trade/v2/trade-chain-get) for full parameters.

### Get Wallet PnL

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

See [Wallet - PnL](/en/api-reference/endpoint/data/wallet/v2/wallet-chain-walletaddress-pnl-get) for full parameters.

### Get Token Candles (K-line)

```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}`);
}
```

See [Token - Candles](/en/api-reference/endpoint/data/token/v2/token-chain-tokenaddress-candles-get) for full parameters.

### Get New Tokens (Ranking)

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

See [Ranking - New Tokens](/en/api-reference/endpoint/data/ranking/v2/ranking-chain-newtokens-get) for full parameters.

***

## Error Handling

```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}`);
  }
}
```

### Retry with Exponential Backoff

For rate-limited requests (HTTP 429), implement retry logic:

```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'));
```

***

## Resources

<CardGroup cols={2}>
  <Card title="GitHub" icon="github" href="https://github.com/chainstream-io/chainstream-sdk/tree/main/typescript">
    View source code
  </Card>

  <Card title="npm" icon="npm" href="https://www.npmjs.com/package/@chainstream-io/sdk">
    Package registry
  </Card>
</CardGroup>
