# TypeScript SDK

The MegaTAO TypeScript SDK (`@megatao/sdk`) provides direct on-chain reads and writes via [viem](https://viem.sh). It is the same SDK used by the MegaTAO frontend.

{% hint style="info" %}
The TypeScript SDK reads directly from the contract over RPC — no REST API required. For a REST-based approach, use the [Python SDK](https://docs.megatao.com/api-sdk/python-sdk) or call the [REST API](https://docs.megatao.com/api-sdk/rest-api) directly.
{% endhint %}

## Installation

```bash
npm install @megatao/sdk
```

## Setup

```typescript
import { MegaTAOClient } from '@megatao/sdk';

const sdk = new MegaTAOClient('prod', {
  rpcUrl: 'https://your-bittensor-rpc-url',
  privateKey: '0xYourPrivateKey',
});

const alpha = sdk.getAlpha();
```

`MegaTAOClient` is the top-level client. All trading reads and writes are accessed via `sdk.getAlpha()`, which returns the `AlphaViem` contract client.

***

## Writes

### Collateral

```typescript
// Deposit 1 TAO (1e18 wei)
const hash = await alpha.deposit(1n * 10n**18n);

// Withdraw
const hash = await alpha.withdraw(500000000000000000n); // 0.5 TAO
```

### Positions

```typescript
// Open a 5x long with 1 TAO margin
const hash = await alpha.openMarketPosition({
  market: '0x0000000000000000000000000000000000000040',
  isLong: true,
  margin: 1n * 10n**18n,
  leverage: 5n * 10n**18n,  // 5x in 1e18 format
  maxSlippage: 50n,          // 50 bps = 0.5%
});

// Close a position
const hash = await alpha.closePosition(positionId, 0n); // 0 = full close
```

### Orders

```typescript
// Limit order
const hash = await alpha.placeLimitOrder({
  market: '0x...',
  isBuy: true,
  margin: 1n * 10n**18n,
  leverage: 5n * 10n**18n,
  price: 85000000000000000n,
  reduceOnlyType: 0,  // 0 = normal, 1 = take-profit, 2 = stop-loss
});

await alpha.cancelOrder(market, orderId);
await alpha.cancelAllOrders(market);
```

***

## Reads

The TypeScript SDK reads state directly from the contract, enabling lower-latency data not available through the REST API.

### Account & positions

```typescript
// Account summary
const summary = await alpha.getAccountSummary(traderAddress);
summary.depositedBalance   // bigint
summary.accountEquity
summary.availableMargin

// Open positions
const positionIds = await alpha.getUserPositions(traderAddress);
const details = await alpha.getPositionDetails(positionIds[0]);
details.isLong
details.notionalValue
details.pricePnl
details.liquidationPrice
details.liquidatable

// Liquidation
const liqStatus = await alpha.getAccountLiquidationStatus(traderAddress);
const liqPrice  = await alpha.getAccountLiquidationPrice(positionId);
const isLiq     = await alpha.isLiquidatable(positionId);
```

### Market data

```typescript
const info    = await alpha.getMarketInfo(marketAddress);
const rate    = await alpha.getFundingRate(marketAddress);
const depth   = await alpha.getOrderbookDepth(marketAddress, 10);

// Pre-trade estimates
const slippage = await alpha.calculateVaultSlippage(market, size, isBuy);
const plan     = await alpha.getOptimalExecutionPlan(market, size, isLong, maxSlippage);
const vwap     = await alpha.getVWAP(market, size, isBuy);
const spread   = await alpha.getBidAskSpread(market);
```

### Vault

```typescript
const vault = await alpha.getVaultState();
vault.totalReserves
vault.availableReserves
```

***

## Leverage format

Leverage is passed in `1e18` format — multiply the multiplier by `10n**18n`:

```typescript
const leverage3x  = 3n  * 10n**18n;
const leverage10x = 10n * 10n**18n;
```

***

## Market addresses

| Market | Address                                      | Subnet |
| ------ | -------------------------------------------- | ------ |
| CHUTES | `0x0000000000000000000000000000000000000040` | SN64   |
| LIUM   | `0x0000000000000000000000000000000000000033` | SN51   |
| RIDGES | `0x000000000000000000000000000000000000003e` | SN62   |
| TARGON | `0x0000000000000000000000000000000000000004` | SN4    |
| MTSOS  | `0x000000000000000000000000000000000000FFFE` | Index  |

See [Contract Specifications](https://docs.megatao.com/trading/contract-specifications) for the full list and contract addresses.
