> For the complete documentation index, see [llms.txt](https://docs.megatao.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.megatao.com/api-sdk/typescript-sdk.md).

# 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](/api-sdk/python-sdk.md) or call the [REST API](/api-sdk/rest-api.md) 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](/trading/contract-specifications.md) for the full list and contract addresses.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.megatao.com/api-sdk/typescript-sdk.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
