# NodeJS SDK

tanX Connector includes utility/connector functions which can be used to interact with the tanX API. It uses axios internally to handle all requests. It includes interceptors for handling setting JWT and re-login on token expiry.

Please check out the full implementation [here](https://www.npmjs.com/package/@tanx-libs/tanx-connector) to find all the rest api methods, web-socket methods and examples.

## Installation

First go to the [tanX website](https://tanx.fi) and create an account with your wallet.

Install from npm

```bash
npm i @tanx-libs/tanx-connector
```

## Usage

Check out the [example](https://github.com/brine-finance/brine-connector-nodejs/tree/main/example) files to see the complete workflow.

## Quick examples:

### REST API Example

```ts
// rest_api.ts
import { AxiosError } from 'axios';
import * as dotenv from 'dotenv';
import {
  Client,
  isAuthenticationError,
  CreateOrderNonceBody,
  Response,
} from '@tanx-libs/tanx-connector';

dotenv.config();

const main = async () => {
  // load your privateKey and walletAddress
  const privateKey = process.env.PRIVATE_KEY;
  const ethAddress = process.env.ETH_ADDRESS;

  if (privateKey && ethAddress) {
    // handle in try catch block
    try {
      // create a rest client instance (you can pass baseUrl if it has changed)
      const client = new Client();

      //you can use public endpoints right away
      const test = await client.testConnection();
      const candleStick = await client.getCandlestick({
        market: 'ethusdc',
        period: 120,
      });

      // login to use private endpoints
      const loginRes = await client.completeLogin(ethAddress, privateKey);

      // create an order nonce
      const nonceBody: CreateOrderNonceBody = {
        market: 'btcusdt',
        ord_type: 'market',
        price: 29580.51,
        side: 'buy',
        volume: 0.0001,
      };

      // create order (private)
      const order = await client.createCompleteOrder(nonceBody, privateKey);
      const orders = await client.listOrders();
      console.log(orders.payload[0]);

      // get profile info (private)
      const profile = await client.getProfileInfo();
      console.log(profile.payload.username);
    } catch (e) {
      // Error: AuthenticationError | AxiosError
      if (isAuthenticationError(e)) {
        console.log(e);
      } else {
        console.log(e as AxiosError<Response<string>>);
      }
    }
  }
};

main();
```

### Websocket Example

```ts
// websocket.ts
import { Client, WsClient } from '../src';
import * as dotenv from 'dotenv';
import { isAuthenticationError } from '@tanx-libs/tanx-connector';
dotenv.config();

const main = async () => {
  try {
    const privateKey = process.env.PRIVATE_KEY;
    const ethAddress = process.env.ETH_ADDRESS;
    // create a rest client instance if you need to create a private websocket
    const client = new Client();
    if (privateKey && ethAddress) {
      // create a public websocket instance
      const wsClient = new WsClient('public');
      // check to see if connected
      await wsClient.connect();
      // subscribe to streams
      await wsClient.subscribe([
        'btcusdc.trades',
        'btcusdc.ob-inc',
        'btcusdc.kline-5m',
      ]);
      // unsubscribe to streams
      await wsClient.unsubscribe(['btcusdc.trades']);
      // operate on ws member
      wsClient.ws.on('message', (data) => {
        console.log(data.toString());
      });
      await wsClient.disconnect();

      // login to get jwt access token
      const loginRes = await client.completeLogin(ethAddress, privateKey);
      // create a private websocket instance
      const wsClientPrivate = new WsClient('private', loginRes.token.access);
      // check if connected
      await wsClientPrivate.connect();
      // subscribe to streams
      await wsClientPrivate.subscribe(['trade', 'order']);
      // operate on ws member
      wsClientPrivate.ws.on('message', (data) => {
        console.log(data.toString());
      });
    }
  } catch (e) {
    if (isAuthenticationError(e)) {
      console.log(e);
    } else {
      console.log(e);
    }
  }
};
main();
```

## Github repo

> Please check out the full implementation [here](https://github.com/brine-finance/brine-connector-nodejs/) to find all the rest api methods, websocket methods and examples.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.tanx.fi/tech/api-documentation/sdk-reference/nodejs-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
