# About MegaTAO

MegaTAO is a perpetual futures protocol on Bittensor EVM. Trade long or short on Alpha token prices with up to 3x leverage, using TAO as collateral.

The protocol vault provides instant liquidity for all trades. No order matching required.

{% hint style="info" %}
MegaTAO is in beta. Leverage and deposit caps are conservative and will be expanded as the protocol matures. Smart contracts are audited by BitSec and XORs Software.
{% endhint %}

## Overview

You deposit TAO as collateral, open a long or short position on any Alpha token, and your profit or loss is settled in TAO.

* **Perpetual futures:** Contracts never expire. Hold a position as long as you want.
* **TAO collateral:** All margin, fees, and settlement are in native TAO.
* **Hybrid liquidity:** Orders match against the order book first, with the protocol vault filling any remaining size.
* **On-chain oracle pricing:** Alpha token prices are derived from on-chain pool reserves.

## Quick Links

* **Trade**: [megatao.com](https://megatao.com)
* **Docs**: [docs.megatao.com](https://docs.megatao.com)
* **Security**: [Audits](/audits)
* **Discord**: [Join the community](https://discord.gg/megatao)


# MegaTAO 101

## What is MegaTAO?

MegaTAO is a perpetual futures DEX on Bittensor EVM. It allows leveraged trading on Bittensor Alpha token prices using TAO as collateral.

## How it works

1. Connect your wallet to [megatao.com](https://megatao.com)
2. Deposit TAO as margin
3. Open a position (long or short) on an Alpha token with your chosen leverage
4. The protocol vault fills your order instantly
5. Funding payments accrue based on market imbalance between longs and shorts
6. Close the position when ready and realize your P\&L in TAO

## Key Properties

| Property     | Detail                               |
| ------------ | ------------------------------------ |
| Collateral   | Native TAO                           |
| Max leverage | 3x                                   |
| Markets      | 12 Alpha tokens                      |
| Settlement   | All P\&L in TAO                      |
| Liquidity    | Order book matching + protocol vault |
| Pricing      | On-chain oracle from pool reserves   |
| Chain        | Bittensor EVM (Chain ID: 964)        |

## Architecture

{% @mermaid/diagram content="graph TD
A\[Trader] --> FUTURES
F\[Keeper] --> FUTURES

```
subgraph BP["<b>Bittensor Protocol</b>"]
    direction LR
    E[Alpha Token Pools] -->|reserve data| ORACLE

    subgraph EVM["<b>Bittensor EVM</b>"]
        direction TB
        ORACLE[Price Oracle] --> FUTURES[Futures Contract]
        C[Protocol Vault] <--> FUTURES
    end
end" %}
```

The protocol consists of the **Futures Contract** (core trading logic), a **Price Oracle** (on-chain price feeds from pool reserves), a **Protocol Vault** (counterparty liquidity), and a **Keeper** (automated liquidations). All contracts run on Bittensor EVM.

## Documentation

| Section                                                                      | Description                                    |
| ---------------------------------------------------------------------------- | ---------------------------------------------- |
| [Onboarding](/onboarding)                                                    | Connect your wallet and make your first trade  |
| [MegaTAO Core](/core)                                                        | Alpha tokens, vault, and protocol mechanics    |
| [Trading](/trading)                                                          | Perpetual futures, funding, liquidations, fees |
| [Security & Audits](/audits)                                                 | Audit reports and smart contract security      |
| [Support](https://github.com/mega-tao/docs/blob/feat/docs/support/README.md) | FAQ and contact information                    |


# Core Contributors

MegaTAO is built by an experienced team of web3 and financial professionals with experience from Axelar, JP Morgan Chase, and Chainalysis. The core contributors are Canh Trinh, Kiryl Yermakou, and Craig R.

## Get Involved

MegaTAO is actively developed and welcomes community participation. Join the [Discord](https://discord.gg/megatao) to follow development, ask questions, and contribute.


# Onboarding

Everything you need to start trading on MegaTAO.

* [How to Start Trading](/onboarding/how-to-start-trading): Connect your wallet, fund it, and open your first position


# How to Start Trading

## What do I need to trade on MegaTAO?

1. An EVM wallet (MetaMask, Coinbase Wallet, WalletConnect, Trust Wallet, or any EVM-compatible wallet)
2. TAO for trading collateral and gas fees

## How do I connect my wallet?

1. Go to [megatao.com](https://megatao.com)
2. Click **Connect Wallet** in the top right
3. Select your wallet from the list
4. Approve the connection in your wallet

The app will automatically switch your wallet to the Bittensor EVM network (Chain ID: 964). No manual network configuration is needed.

## How do I fund my wallet?

You need TAO on the Bittensor EVM network. There are two ways to get it:

### Option A: Send TAO to your Bittensor address

Send TAO to the Bittensor address associated with your connected wallet.

1. Click the **Bittensor Address** button in the top right corner of the app:

![Bittensor Address button](/files/33tvcNMCOkHJMpxN011T)

2. Copy your Bittensor address
3. Send TAO to that address from an exchange or another wallet

### Option B: Import your existing Bittensor wallet

If you already hold TAO on the Bittensor network:

1. Take the mnemonic (seed phrase) from your Bittensor wallet
2. Import it into your EVM wallet as a new account
3. Your TAO balance will be available automatically through the address mapping

## How do I deposit margin?

TAO in your wallet is not yet available for trading. You need to deposit it as margin:

1. Click **Deposit** in the account section
2. Enter the amount of TAO to deposit
3. Confirm the transaction in your wallet

Keep some TAO in your wallet (not deposited) for gas fees.

## How do I open a position?

1. Select a market from the market list (e.g., CHUTES, TARGON, VANTA)
2. Choose **Long** (price goes up = profit) or **Short** (price goes down = profit)
3. Enter your margin amount
4. Set your leverage (1x to 3x)
5. Review the position summary: notional value, entry price, liquidation price, fees
6. Click to open and confirm in your wallet

| Field             | Meaning                                     |
| ----------------- | ------------------------------------------- |
| Notional Value    | Total position size (margin x leverage)     |
| Entry Price       | Current oracle price at execution           |
| Liquidation Price | Price at which the position is force-closed |
| Trading Fee       | 0.25% of notional value                     |

## How do I close a position?

1. Go to your open positions
2. Click on the position to close
3. Click **Close Position**
4. Confirm the transaction in your wallet

You can also partially close by specifying a notional amount less than the full position size.

## How do I withdraw?

1. Ensure you have available margin (not locked in open positions)
2. Click **Withdraw** in the account section
3. Enter the amount and confirm

You cannot withdraw margin that is backing open positions. Close or reduce positions first.


# MegaTAO Core

MegaTAO is a perpetual futures DEX for Bittensor subnet Alpha tokens. You can deposit TAO as collateral and take leveraged positions on Alpha tokens.

## What is MegaTAO?

MegaTAO is a perpetual futures DEX on Bittensor EVM. You deposit TAO as collateral and take leveraged long or short positions on Alpha token prices. All profit and loss is settled in TAO.

Key properties:

* **Synthetic positions:** Positions track Alpha token price movements through perpetual contracts. All settlement is in TAO.
* **Perpetual futures:** Contracts never expire. Hold a position as long as you want, subject to funding costs and margin requirements.
* **TAO collateral:** All margin, fees, and settlement are in native TAO. A single-currency system simplifies operations and concentrates liquidity.
* **Hybrid liquidity:** Orders are first matched against the order book. The protocol vault fills any remaining size, providing instant execution.
* **On-chain oracle pricing:** Alpha token prices are derived directly from on-chain pool reserves, with no off-chain price feeds.

## How it works

### Vault model

Instead of matching buyers and sellers through an order book, MegaTAO uses a vault model. The protocol vault acts as the counterparty to every trade:

* **Instant execution:** Orders fill immediately. No waiting for a matching counterparty.
* **Guaranteed liquidity:** The vault is always available to take the other side of your trade.
* **Simplified trading:** One counterparty system eliminates complex order book interactions.

When order book liquidity is available, the protocol matches against it first. The vault fills any remaining size.

### Trading flow

1. Fund your wallet with TAO
2. Deposit TAO as margin
3. Open a position (long or short) on an Alpha token with your chosen leverage (up to 3x)
4. The protocol fills your order instantly via vault or order book matching
5. Funding payments accrue every 8 hours based on market imbalance between longs and shorts
6. Interest fees accrue based on vault utilization (charged to both sides)
7. Close the position when ready and realize your P\&L in TAO

### Margin and liquidation

The protocol continuously monitors your margin ratio. If it falls below the maintenance margin (currently 10%), the position is automatically liquidated to prevent negative balances and protect the system.

## Architecture

{% @mermaid/diagram content="graph LR
subgraph BP\["Bittensor Protocol"]
POOLS\[Alpha Token Pools] -->|reserve data| ORACLE

```
    subgraph EVM["Bittensor EVM"]
        ORACLE[Price Oracle] -->|price feed| FUTURES[Futures Contract]
        VAULT[Protocol Vault] <-->|liquidity| FUTURES
    end
end

KEEPER[Keeper] -->|liquidate| FUTURES
USER[Trader] -->|deposit / trade| FUTURES
FUTURES -->|P&L settlement| USER[Trader]
```

" %}

| Component        | Role                                                        |
| ---------------- | ----------------------------------------------------------- |
| Futures Contract | Core trading logic: positions, margin, orders, liquidations |
| Price Oracle     | Reads Alpha token prices from on-chain pool reserves        |
| Protocol Vault   | Provides liquidity and acts as counterparty                 |
| Keeper           | Monitors and executes liquidations of unhealthy positions   |

All contracts run on Bittensor EVM (Chain ID: 964) and are upgradeable to support future improvements without disrupting existing positions.

## Why Bittensor EVM?

MegaTAO is built on Bittensor's native EVM chain. This gives the protocol direct access to the Bittensor ecosystem:

* **Native TAO integration:** TAO is the chain's native currency, so collateral deposits and settlements require no token wrapping or bridging.
* **Alpha token precompile:** Bittensor EVM includes a precompile contract that exposes Alpha token pool reserves at the chain level. The oracle reads prices directly from this precompile, giving MegaTAO a trustless source of truth for pricing without relying on external oracle networks.
* **EVM compatibility:** Developers and traders can use standard Ethereum tooling (MetaMask, Viem, ethers.js) while operating within the Bittensor ecosystem.

## In this section

* [Alpha Tokens](/core/alpha-tokens): Supported markets and how Alpha tokens work
* [Oracle](/core/oracle): On-chain pricing via the Alpha precompile
* [Vault](/core/vault): How the protocol vault provides liquidity
* [Keepers](/core/keepers): Automated liquidation and protocol maintenance
* [Funding and Interest](/core/funding-and-interest): How the protocol stays balanced


# Alpha Tokens

Alpha tokens are the native tokens of Bittensor subnets. Each subnet on the Bittensor network has a tradeable token whose price fluctuates based on subnet demand, performance, and market sentiment.

MegaTAO enables perpetual futures trading on these tokens. You deposit TAO as collateral and take leveraged positions on Alpha token price movements.

## Supported Markets

MegaTAO supports perpetual futures on 12 Alpha tokens:

| Market    | Subnet |
| --------- | ------ |
| CHUTES    | SN64   |
| LIUM      | SN51   |
| RIDGES    | SN62   |
| TARGON    | SN4    |
| VANTA     | SN8    |
| AFFINE    | SN120  |
| TEMPLAR   | SN3    |
| SCORE     | SN44   |
| IOTA      | SN9    |
| GRADIENTS | SN56   |
| HIPPIUS   | SN75   |
| BITMIND   | SN34   |

All markets share the same parameters:

| Parameter          | Value      |
| ------------------ | ---------- |
| Max Leverage       | 5x         |
| Maintenance Margin | 10%        |
| Trading Fee        | 0.25%      |
| Collateral         | Native TAO |

## Pricing

Alpha token prices are derived from on-chain pool reserves using a dedicated price oracle contract. The oracle reads directly from Bittensor's Alpha token precompile, ensuring prices reflect actual on-chain liquidity. No off-chain price feeds are used.

## One position per market

Each trader can hold at most one position per market at a time. Position IDs are deterministically derived from the trader address and market address.


# Oracle

The oracle is MegaTAO's pricing engine. It provides real-time Alpha token prices to the protocol by reading directly from on-chain data, with no reliance on off-chain price feeds.

## How pricing works

Each Bittensor subnet has an Alpha token that trades in an on-chain liquidity pool against TAO. These pools hold reserves of both TAO and the Alpha token. The ratio of these reserves determines the token's price.

MegaTAO's price oracle reads these reserves through the **Alpha precompile contract** on Bittensor EVM. The precompile is a native contract built into the chain itself, giving the oracle a direct source of truth for pricing from the Alpha pools.

The price derivation:

1. The oracle calls `get_alpha_price(netUid)` for a given subnet
2. The precompile returns the current pool reserves (TAO and Alpha token amounts)
3. The price is calculated from the TAO/Alpha ratio in the pool
4. This price is used for position entry, exit, P\&L calculation, and liquidation checks

Because the precompile is part of the Bittensor EVM itself, the oracle accesses pool state at the block level. There is no delay, no relay, and no intermediary. The price you see is the price on-chain at that moment.

## Why on-chain pricing matters

Most derivatives protocols rely on external oracle networks (like Chainlink) to relay off-chain exchange prices on-chain. This introduces latency, trust assumptions, and potential manipulation vectors.

MegaTAO takes a different approach:

* **No off-chain feeds.** Prices come directly from on-chain pool reserves via the precompile. There is no external data provider to trust or wait for.
* **No relay delay.** The oracle reads pool state in the same block as the trade. Prices are always current.
* **Transparent and verifiable.** Anyone can independently verify prices by reading the same pool reserves on-chain.
* **Manipulation resistant.** Manipulating prices would require moving actual liquidity in the Alpha token pools, which has a real capital cost.

## Price validation

The oracle includes safeguards to reject invalid price data:

* Zero or negative prices are rejected
* Price impact is calculated dynamically based on position size relative to pool liquidity
* The protocol enforces a maximum slippage parameter on each trade, reverting the transaction if actual execution price deviates too far from the oracle price

## Role in the protocol

Oracle prices feed into every part of the trading system:

| Function           | How oracle price is used                                     |
| ------------------ | ------------------------------------------------------------ |
| Opening a position | Determines entry price and notional value                    |
| Closing a position | Determines exit price and realized P\&L                      |
| Margin ratio       | Calculates unrealized P\&L against current price             |
| Liquidation        | Triggers when margin ratio falls below maintenance threshold |
| Funding rates      | Combined with open interest to determine funding payments    |


# Vault

The protocol vault is MegaTAO's liquidity layer. It provides instant execution for all trades and acts as the counterparty when there is no orderbook match.

## How the vault works

When a trader opens a position:

1. The order is first sent to the orderbook for matching
2. If no match is found, the protocol vault fills the order directly
3. Execution is instant, no waiting for a counterparty

This hybrid model combines the price discovery of an orderbook with the guaranteed liquidity of a vault.

## Vault deposits

Liquidity providers can deposit TAO into the vault to earn yield from:

* Trading fees (0.25% of notional value on each trade)
* Funding payments when the vault holds net positions
* Liquidation fees (5% of remaining margin on liquidated positions)

The vault takes on the opposite side of trader positions. When traders profit, the vault's value decreases. When traders lose, the vault's value increases.

## Vault utilization

The protocol monitors vault utilization to manage risk:

* When utilization is high, the vault's capacity to take on new positions is reduced
* Maximum aggregate exposure is capped to prevent excessive risk
* Per-market limits ensure no single market can dominate vault exposure

## Insurance fund

A portion of fees is directed to an insurance fund that covers bad debt from positions that become insolvent before liquidation can execute. This protects vault depositors from losses due to extreme market moves.


# Keepers

Keepers are automated bots that maintain protocol health by monitoring positions and executing liquidations. They are a critical part of MegaTAO's infrastructure.

## What keepers do

When a trader's margin ratio falls below the maintenance threshold, the position becomes eligible for liquidation. Keepers detect these unhealthy positions and submit liquidation transactions to close them before they become insolvent.

Without keepers, undercollateralized positions could accumulate bad debt, meaning losses that exceed the trader's deposited margin. This would put vault depositors at risk. Keepers prevent this by ensuring liquidations happen promptly.

## How it works

1. Keepers continuously monitor all open positions across all markets
2. For each position, they calculate the current margin ratio using the latest oracle price
3. When a position's margin ratio drops below the maintenance margin (currently 10%), the keeper submits a liquidation transaction
4. The protocol verifies the position is indeed liquidatable and executes the liquidation on-chain
5. The keeper receives a portion of the liquidation fee as incentive

## Incentives

Keepers are incentivized through the liquidation fee. When a position is liquidated, a 5% fee is charged on the remaining margin. A portion of this fee goes to the keeper that executed the liquidation, compensating them for monitoring costs and gas.

This incentive structure ensures liquidations happen quickly even during volatile markets when gas costs may be elevated.

## Keeper roles

Keepers also perform other protocol maintenance tasks:

* **Funding rate updates:** Keepers trigger funding rate recalculations to keep rates current with market conditions
* **Interest fee updates:** Keepers update interest accruals based on vault utilization

## Decentralization

The keeper role is permissioned at the contract level. The protocol team currently operates the primary keeper infrastructure to ensure reliable liquidation execution. As the protocol matures, the keeper system may be opened to additional participants.


# Funding and Interest

MegaTAO uses two fee mechanisms to keep the protocol balanced and compensate liquidity providers. Both accrue continuously while a position is open.

## Funding rates

Perpetual futures have no expiry date, so there is no natural convergence between the futures price and the spot price. Funding rates solve this by creating periodic payments between longs and shorts based on which side is more crowded.

**When there are more longs than shorts**, longs pay shorts. This makes it more expensive to be long and cheaper to be short, encouraging traders to take the other side and rebalance the market.

**When there are more shorts than longs**, shorts pay longs. The same rebalancing effect works in reverse.

**When the market is balanced**, the funding rate is zero and no payments are made.

Funding is a peer-to-peer payment. The protocol does not collect funding fees. They flow directly between position holders. The rate is recalculated based on the ratio of long to short open interest and is capped at 0.75% per 8-hour interval.

## Interest fees

Separate from funding, an interest fee is charged to all position holders (both longs and shorts). This fee compensates vault depositors for the capital the vault puts at risk when acting as counterparty.

The interest rate scales with vault utilization:

* **Low utilization:** When the vault has plenty of available reserves relative to its exposure, the interest rate is minimal.
* **High utilization:** When the vault's capital is heavily committed, the rate increases to compensate depositors for the higher risk and to discourage further position opening.

This creates a self-regulating system: as the vault becomes more utilized, it becomes more expensive to hold positions, which naturally limits protocol exposure.

## Impact on traders

Both funding and interest reduce your margin over time. For short-duration trades, these costs are typically small. For longer-held positions, they can become meaningful.

Before opening a position, check the current funding rate and vault utilization on the market page. Your net P\&L includes:

* Price movement (unrealized P\&L)
* Funding paid or received (directional, based on market skew)
* Interest paid (always a cost, based on utilization)
* Trading fees (0.25% on open and close)

For detailed formulas and parameters, see [Funding](/trading/funding) in the Trading section.


# Trading

Technical details on how trading works on MegaTAO.

* [Perpetual Futures](/trading/perpetual-futures): Positions, leverage, margin
* [Funding](/trading/funding): Funding rate mechanics and schedule
* [Liquidations](/trading/liquidations): Maintenance margin, liquidation price, process
* [Fees](/trading/fees): Trading fees, liquidation fees, gas
* [Contract Specifications](/trading/contract-specifications): Addresses, parameters, limits
* [Glossary](/trading/glossary): Key terms
* [Risk Warnings](/trading/risk-warnings): Risk disclosure


# Perpetual Futures

MegaTAO perpetual futures are derivative contracts that track Alpha token prices. They never expire, allowing you to hold a position indefinitely (subject to funding costs, interest fees, and margin requirements).

## Positions

A position is an open trade representing exposure to an Alpha token price.

**Long position**: Profits when the Alpha token price goes up. You are buying exposure.

**Short position**: Profits when the Alpha token price goes down. You are selling exposure.

Each trader can hold one position per market. Position IDs are deterministically derived from the trader address and market address. A trader can hold up to 50 positions across different markets.

## Leverage

Leverage multiplies your position size relative to your margin.

| Leverage | Margin | Notional Value | Approx. Liquidation Move (at 10% maintenance) |
| -------- | ------ | -------------- | --------------------------------------------- |
| 1x       | 10 TAO | 10 TAO         | \~90% against you                             |
| 2x       | 10 TAO | 20 TAO         | \~40% against you                             |
| 3x       | 10 TAO | 30 TAO         | \~23% against you                             |
| 5x       | 10 TAO | 50 TAO         | \~10% against you                             |

Maximum leverage is 5x on all markets.

### How leverage affects P\&L

With 5x leverage:

* Price moves +10% --> your margin gains +50%
* Price moves -10% --> your margin loses -50%
* Price moves -10% --> liquidation (at 10% maintenance margin)

Leverage amplifies both gains and losses equally.

## Margin

Margin is the TAO collateral that backs your position.

### Initial margin

The margin required to open a position:

```
Initial Margin = Notional Value / Leverage
```

### Maintenance margin

The minimum margin ratio required to keep a position open. This is configured per-market (currently 10% on all markets, configurable from 1% to 50%).

If your margin ratio falls below the maintenance margin, the position is liquidated. See [Liquidations](/trading/liquidations).

### Margin ratio

```
Margin Ratio = (Margin + Unrealized P&L) / Notional Value
```

## Order execution

All positions are opened and closed via market orders. The order is first routed to the orderbook for matching. If no match is found, the protocol vault fills it.

Execution includes dynamic slippage based on position size and vault utilization:

| Vault Utilization | Base Slippage |
| ----------------- | ------------- |
| Normal            | 0.1%          |
| Medium            | 0.15%         |
| High              | 0.25%         |

Maximum slippage is capped at 20%. You set a `maxSlippage` parameter when opening a position, and the transaction reverts if actual slippage exceeds it.

A 0.25% trading fee is charged on the notional value of each trade (both open and close). See [Fees](/trading/fees).

## Closing positions

You can close a position at any time:

* **Full close:** Close the entire position
* **Partial close:** Close a portion of the position by specifying a notional amount

A position cannot be opened and closed in the same block (flash loan protection).


# Funding

Funding rates are periodic payments between long and short position holders. They keep perpetual futures prices aligned with the underlying spot price by incentivizing the less popular side.

## Overview

* **Positive funding rate**: Longs pay shorts. This happens when there is more long open interest than short (market is skewed long).
* **Negative funding rate**: Shorts pay longs. This happens when there is more short open interest than long (market is skewed short).
* **Zero rate**: No payment. Open interest is balanced.

Funding is peer-to-peer. The protocol does not collect funding payments.

## Funding rate calculation

The funding rate is based on the imbalance between long and short open interest:

```
Funding Rate = (Long OI - Short OI) / Total OI x Max Funding Rate
```

Where:

* `Long OI` and `Short OI` are the total long and short open interest in the market
* `Total OI = Long OI + Short OI`
* `Max Funding Rate = 0.75%` per 8-hour interval

The rate is capped at 0.75% per 8-hour interval in either direction.

### Example

* Long OI: 100 TAO, Short OI: 60 TAO, Total OI: 160 TAO
* Skew: (100 - 60) / 160 = 0.25
* Funding Rate: 0.25 x 0.75% = 0.1875% per 8 hours
* Longs pay shorts at this rate

## Payment timing

Funding accrues continuously while a position is open. The accumulated funding is applied when the position is modified or closed.

The rate displayed is the 8-hour rate. The actual cost depends on how long you hold:

```
Funding Payment = Position Notional x Oracle Price x Funding Rate x (Time Held / 8 hours)
```

Maximum accumulation is capped at 32 hours (4 funding intervals). If funding hasn't been updated for longer than that, only the last 32 hours count.

## Interest fee

Separate from the directional funding rate, an interest fee is charged to **both** long and short positions based on vault utilization. This compensates vault depositors for capital at risk.

```
Interest Rate = 20% x utilization^2 + 0.01%
```

Where `utilization = total mark-to-market exposure / available reserves`. The interest rate is capped at 80%.

Unlike funding, interest is always a cost to the position holder regardless of direction.

## Impact on P\&L

Both funding and interest reduce your margin over time:

```
Net P&L = Price P&L - Funding Paid + Funding Received - Interest Paid - Trading Fees
```

For long-held positions, funding and interest can become significant costs. Check the current rates on each market before opening a position.


# Liquidations

A liquidation occurs when a position's margin ratio falls below the maintenance margin. The position is automatically closed and a liquidation fee is charged.

## When does liquidation happen?

Liquidation is triggered when:

```
Margin Ratio = (Margin + Unrealized P&L) / Notional Value < Maintenance Margin
```

The maintenance margin is configured per-market (currently 10% on all markets, configurable from 1% to 50%).

The system monitors all positions continuously. When a position becomes undercollateralized, a keeper bot executes the liquidation.

## Partial vs full liquidation

The protocol supports two liquidation modes:

| Margin Ratio                                                                  | Action                      |
| ----------------------------------------------------------------------------- | --------------------------- |
| Below maintenance margin (e.g., < 10%)                                        | Full liquidation            |
| Between maintenance margin and maintenance margin + 5% buffer (e.g., 10%-15%) | Partial liquidation allowed |
| Above maintenance margin + 5% buffer (e.g., > 15%)                            | Not liquidatable            |

Partial liquidation closes enough of the position to bring the margin ratio back above the maintenance threshold, preserving the rest.

## Liquidation price

### Long position

```
Liquidation Price = Entry Price x (1 + Maintenance Margin - 1 / Leverage)
```

Example with 3x leverage and 10% maintenance margin:

```
Liquidation Price = 0.019 x (1 + 0.10 - 1/3) = 0.019 x 0.767 = 0.01457
```

A \~23% price drop triggers liquidation.

### Short position

```
Liquidation Price = Entry Price x (1 - Maintenance Margin + 1 / Leverage)
```

Example with 3x leverage and 10% maintenance margin:

```
Liquidation Price = 0.019 x (1 - 0.10 + 1/3) = 0.019 x 1.233 = 0.02343
```

A \~23% price increase triggers liquidation.

## Liquidation process

1. Keeper detects margin ratio below maintenance margin
2. Position is closed at current market price
3. Liquidation fee is deducted from remaining margin
4. Keeper receives the liquidation fee as reward
5. Remaining margin (if any) is returned to the trader

If the position's losses exceed its margin (bad debt), the insurance fund covers the shortfall.

## Liquidation fee

```
Liquidation Fee = Remaining Margin x Liquidation Fee Rate
```

The liquidation fee rate is per-market configurable (up to 10%). Currently set to 5% on all markets.

This fee incentivizes keepers to execute liquidations promptly.

## Avoiding liquidation

* Close the position manually before the margin ratio reaches the maintenance level. This avoids the liquidation fee entirely.
* Use lower leverage. At 1x leverage with 10% maintenance margin, the price must move \~90% against you. At 3x, \~23%. At 5x, only \~10%.

The liquidation price is shown when you open a position and on your open positions panel.


# Fees

## Trading fees

MegaTAO uses a maker/taker fee model based on how your order is filled.

| Order type                                                     | Fee                   |
| -------------------------------------------------------------- | --------------------- |
| **Taker** (market order, or limit order that crosses the book) | **0.25%** of notional |
| **Maker** (resting limit order filled by another trader)       | **0%** of notional    |

Fees are charged on the notional value of the trade and deducted from your margin balance at execution.

### Round-trip cost

| Scenario    | Open  | Close | Total |
| ----------- | ----- | ----- | ----- |
| Taker/Taker | 0.25% | 0.25% | 0.50% |
| Maker/Taker | 0%    | 0.25% | 0.25% |
| Maker/Maker | 0%    | 0%    | 0%    |

### Example

* Margin: 5 TAO, Leverage: 2x, Notional: 10 TAO
* Open as taker: 10 × 0.0025 = 0.025 TAO
* Close as taker: 10 × 0.0025 = 0.025 TAO
* Total fees: 0.05 TAO

## Funding costs

Funding accrues continuously while a position is open. The cost depends on the current funding rate and how long you hold. See [Funding](/trading/funding) for the full formula.

Funding is peer-to-peer and direction-dependent: if the rate is positive, longs pay shorts (and vice versa).

## Interest fee

In addition to funding, an interest fee is charged to both long and short positions based on vault utilization. This compensates vault depositors for the capital used by open positions.

The interest rate follows a quadratic curve:

```
Interest Rate = 20% x utilization^2 + 0.01%
```

Where `utilization = total mark-to-market exposure / available reserves`. The interest rate is capped at 80% annualized.

Unlike funding (which is directional), the interest fee is always a cost. Both longs and shorts pay it.

## Liquidation fee

If your position is liquidated, a 5% penalty is applied to remaining margin. See [Liquidations](/trading/liquidations).

```
Liquidation Fee = Remaining Margin x 5%
```

You can avoid this fee entirely by closing your position before the margin ratio reaches the maintenance margin.

## Gas costs

Every transaction on Bittensor EVM requires gas, paid in TAO. This includes opening, closing, depositing, and withdrawing. Gas costs on Bittensor EVM are low — a typical trade costs a fraction of a TAO in gas.

## Total cost of a trade

```
Total Cost = Open Fee + Close Fee + Funding Cost + Interest Cost + Gas
```

For short-duration trades, funding and interest are negligible. Total cost is approximately 0–0.50% of notional plus gas, depending on whether you use limit or market orders.


# Contract Specifications

## Network

| Parameter      | Value                                      |
| -------------- | ------------------------------------------ |
| Network        | Bittensor EVM                              |
| Chain ID       | `964`                                      |
| Currency       | TAO (18 decimals)                          |
| Block Explorer | [evm.taostats.io](https://evm.taostats.io) |

## Contracts

| Contract        | Address                                      |
| --------------- | -------------------------------------------- |
| MegaTAO (Proxy) | `0xdA50070976Da21A0E7afaB1BB0c81CD51926AE64` |
| Price Oracle    | `0x446A342221ed83b56fc17eA3e046dd19153beA85` |

## Trading Parameters

| Parameter                     | Value                               |
| ----------------------------- | ----------------------------------- |
| Taker Fee                     | 0.25% of notional                   |
| Maker Fee                     | 0% of notional                      |
| Max Leverage                  | 5x                                  |
| Default Leverage              | 3x                                  |
| Maintenance Margin            | 10%                                 |
| Liquidation Fee               | 5%                                  |
| Liquidation Threshold         | 10% margin ratio                    |
| Partial Liquidation Threshold | 15% margin ratio                    |
| Min Position Size             | 0.0001 TAO notional                 |
| Max Positions Per User        | 50                                  |
| Same-Block Close              | Not allowed (flash loan protection) |
| Collateral                    | Native TAO (18 decimals)            |

## Funding Parameters

| Parameter           | Value                        |
| ------------------- | ---------------------------- |
| Funding Interval    | 8 hours                      |
| Max Funding Rate    | 0.75% per 8h interval        |
| Max Funding Elapsed | 32 hours (4 intervals)       |
| Funding Formula     | `(skew / totalOI) x maxRate` |

## Interest Fee Parameters

| Parameter                 | Value                   |
| ------------------------- | ----------------------- |
| Quadratic Coefficient (A) | 20%                     |
| Base Rate (C)             | 0.01%                   |
| Formula                   | `A x utilization^2 + C` |
| Charged To                | Both longs and shorts   |

## Slippage Parameters

| Parameter                   | Value          |
| --------------------------- | -------------- |
| Default Base Slippage       | 0.1% (10 bps)  |
| Medium Utilization Slippage | 0.15% (15 bps) |
| High Utilization Slippage   | 0.25% (25 bps) |

## Vault Parameters

| Parameter                              | Value                        |
| -------------------------------------- | ---------------------------- |
| Max Exposure Per Asset                 | 50% of total reserves        |
| Max Total Utilization                  | 80%                          |
| Critical Utilization (circuit breaker) | 90%                          |
| Min Withdrawal Reserve                 | 60%                          |
| Default Max Bad Debt                   | 10% of reserves (auto-pause) |

## Supported Markets

| Market    | Subnet | Token Address                                |
| --------- | ------ | -------------------------------------------- |
| CHUTES    | SN64   | `0x0000...0040`                              |
| LIUM      | SN51   | `0x0000...0033`                              |
| RIDGES    | SN62   | `0x0000...003e`                              |
| TARGON    | SN4    | `0x0000...0004`                              |
| VANTA     | SN8    | `0x0000...0008`                              |
| AFFINE    | SN120  | `0x0000...0078`                              |
| TEMPLAR   | SN3    | `0x0000...0003`                              |
| SCORE     | SN44   | `0x0000...002c`                              |
| IOTA      | SN9    | `0x0000...0009`                              |
| GRADIENTS | SN56   | `0x0000...0038`                              |
| HIPPIUS   | SN75   | `0x0000...004b`                              |
| BITMIND   | SN34   | `0x0000...0022`                              |
| MTSOS     | Index  | `0x000000000000000000000000000000000000FFFE` |

## Indexer

| Parameter        | Value                                        |
| ---------------- | -------------------------------------------- |
| GraphQL Endpoint | `https://indexer.futures.bitmind.ai/graphql` |


# Glossary

| Term               | Definition                                                                                                                     |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| Alpha Token        | Native token of a Bittensor subnet. The underlying asset for MegaTAO perpetual futures.                                        |
| Bittensor EVM      | Ethereum-compatible execution layer on the Bittensor network (Chain ID: 964).                                                  |
| Collateral         | TAO deposited as security for leveraged positions.                                                                             |
| Entry Price        | The oracle price when a position is opened.                                                                                    |
| Funding Rate       | Periodic payment between longs and shorts that keeps futures prices aligned with spot. Positive rate means longs pay shorts.   |
| Initial Margin     | Collateral required to open a position. Equal to notional value divided by leverage.                                           |
| Interest Fee       | Utilization-based fee charged to both longs and shorts. Compensates vault depositors for capital at risk.                      |
| Keeper             | Automated bot that monitors and executes liquidations of unhealthy positions.                                                  |
| Leverage           | Multiplier of position size relative to margin. 3x leverage means 10 TAO margin controls 30 TAO notional.                      |
| Liquidation        | Automatic closure of a position when margin ratio falls below the maintenance margin. Incurs a liquidation fee (currently 5%). |
| Liquidation Price  | The price at which a position's margin ratio hits 10% and liquidation triggers.                                                |
| Long Position      | A position that profits when the Alpha token price increases.                                                                  |
| Maintenance Margin | Minimum margin ratio required to keep a position open. Per-market configurable (currently 10%).                                |
| Margin             | TAO deposited to open and maintain positions.                                                                                  |
| Margin Ratio       | Health indicator of a position: `(Margin + Unrealized P&L) / Notional Value`.                                                  |
| Market Order       | An order that executes immediately at the current price.                                                                       |
| Notional Value     | Total position exposure: `Margin x Leverage`.                                                                                  |
| Oracle             | On-chain contract that provides Alpha token prices derived from pool reserves.                                                 |
| Open Interest      | Total notional value of all open positions in a market.                                                                        |
| Perpetual Futures  | Derivative contracts that track an asset's price without an expiration date.                                                   |
| P\&L               | Profit and Loss. Unrealized P\&L is on open positions; realized P\&L is from closed positions.                                 |
| Short Position     | A position that profits when the Alpha token price decreases.                                                                  |
| Slippage           | Difference between expected and actual execution price.                                                                        |
| TAO                | Native token of the Bittensor network. Used as collateral and for gas fees on MegaTAO.                                         |
| Vault              | Protocol-owned liquidity pool that acts as counterparty to trades when no orderbook match exists.                              |


# Risk Warnings

Trading perpetual futures on MegaTAO involves substantial risk. Read this before trading.

## Leverage risk

Leverage amplifies both gains and losses. At 3x leverage, a \~23% adverse price move results in liquidation and near-total loss of your margin. At 2x leverage, this threshold is approximately 40%.

You can lose your entire deposited margin on a single trade.

## Liquidation risk

Positions are automatically liquidated when the margin ratio falls below 10%. Liquidation incurs a 5% penalty on remaining margin. Liquidation is irreversible.

In volatile markets, prices can move rapidly past the liquidation threshold. You may not have time to add margin or close the position manually.

## Market risk

Alpha token prices can be highly volatile. Prices can move significantly in short timeframes due to:

* Changes in subnet demand and performance
* Broader crypto market conditions
* Low liquidity in underlying Alpha token pools
* Large trades affecting pool reserves

Past price performance does not predict future results.

## Smart contract risk

MegaTAO's smart contracts have been audited by BitSec and XORs Software, but no audit eliminates all risk. Smart contracts may contain undiscovered vulnerabilities that could result in loss of funds.

The protocol is in beta and contracts are upgradeable via the UUPS proxy pattern.

## Oracle risk

Prices are derived from on-chain pool reserves. If the underlying pool is manipulated or experiences abnormal conditions, the oracle price may not reflect fair market value. The protocol includes safeguards, but no protection is absolute.

## Protocol risk

MegaTAO is in beta. The protocol is actively being developed and upgraded. Parameters such as leverage limits, deposit caps, and fee structures may change.

The protocol vault acts as counterparty to trades. In extreme scenarios, vault insolvency could affect withdrawals.

## Network risk

Bittensor EVM is a relatively new network. Network outages, congestion, or RPC failures could prevent you from closing positions or adding margin during critical moments.

## Your responsibility

* Only trade with funds you can afford to lose completely
* Understand how leverage, margin, and liquidation work before trading
* Monitor your positions and margin ratios
* Do not rely on being able to close a position at a specific price


# API & SDK

MegaTAO exposes a public REST API and two official SDKs for building trading bots, analytics tools, and integrations.

|                    |                                                               |
| ------------------ | ------------------------------------------------------------- |
| **REST API**       | `https://api.megatao.com` — read-only market and account data |
| **Python SDK**     | `pip install megatao-sdk` — REST reads + on-chain writes      |
| **TypeScript SDK** | `@megatao/sdk` — on-chain reads and writes via viem           |

## Pages

* [REST API](/api-sdk/rest-api) — endpoint reference
* [Python SDK](/api-sdk/python-sdk) — installation, info client, chain client
* [TypeScript SDK](/api-sdk/typescript-sdk) — on-chain reads and writes


# REST API

**Base URL:** `https://api.megatao.com`

The REST API is read-only and requires no authentication. All amounts are returned as strings in wei (18 decimals). Divide by `10^18` to get TAO-denominated values.

Interactive documentation is available at <https://api.megatao.com/swagger>.

***

## Markets

### `GET /v1/info/markets`

Returns all active markets.

**Response**

```json
[
  {
    "market": "0x0000000000000000000000000000000000000040",
    "symbol": "CHUTES",
    "price": "87707801000000000",
    "fundingRate": "20",
    "longOpenInterest": "9003500000000000000",
    "shortOpenInterest": "911995857793391469",
    "maxLeverage": "500",
    "isActive": true
  }
]
```

### `GET /v1/info/markets/:address`

Returns detailed info for a single market by contract address.

### `GET /v1/info/prices`

Returns the latest oracle price for every market, keyed by market address.

```json
{
  "0x0000000000000000000000000000000000000040": {
    "symbol": "CHUTES",
    "price": "87707850000000000"
  }
}
```

### `GET /v1/info/candles`

Returns OHLCV candle data.

| Parameter    | Type    | Description                              |
| ------------ | ------- | ---------------------------------------- |
| `market`     | string  | Market contract address                  |
| `resolution` | string  | `1m`, `5m`, `15m`, `1h`, `4h`, `1d`      |
| `from`       | integer | Start timestamp (Unix seconds, optional) |
| `to`         | integer | End timestamp (Unix seconds, optional)   |

### `GET /v1/info/orderbook`

Returns the order book for a market.

| Parameter | Type    | Description                                    |
| --------- | ------- | ---------------------------------------------- |
| `market`  | string  | Market contract address                        |
| `levels`  | integer | Number of price levels each side (default: 10) |

```json
{
  "market": "0x...",
  "bids": [{ "price": "87500000000000000", "notional": "5000000000000000000", "orderCount": 3 }],
  "asks": [{ "price": "88000000000000000", "notional": "3000000000000000000", "orderCount": 2 }]
}
```

### `GET /v1/info/funding`

Returns current funding rates for all markets.

```json
[
  {
    "market": "0x...",
    "symbol": "CHUTES",
    "currentRate": "20",
    "lastUpdate": "1774565748"
  }
]
```

Funding rates are in basis points per 8-hour interval. See [Funding](/trading/funding) for the full rate mechanics.

***

## Account

### `GET /v1/info/margin/:address`

Returns margin balances for a trader address.

```json
{
  "depositedBalance": "10000000000000000000",
  "accountEquity": "10500000000000000000",
  "unrealizedPnl": "500000000000000000",
  "lockedMargin": "5000000000000000000",
  "availableMargin": "5500000000000000000"
}
```

### `GET /v1/info/positions/:address`

Returns open positions for a trader.

```json
[
  {
    "positionId": "0x984aa620aba1ac7ae2d1edbb8ba9c3ff",
    "market": "0x...",
    "symbol": "CHUTES",
    "isLong": true,
    "notionalValue": "238000000000000000",
    "margin": "114000000000000000",
    "entryPrice": "100651205495176469",
    "markPrice": "87707850000000000",
    "pricePnl": "-30605878913190245",
    "fundingPayment": "-15472261000158660",
    "liquidationPrice": "62326323402782351",
    "liquidatable": false
  }
]
```

### `GET /v1/info/orders/:address`

Returns open limit orders for a trader.

### `GET /v1/info/trades/:address`

Returns trade history for a trader. Response is split into `opens` and `closes`:

```json
{
  "opens": [...],
  "closes": [...]
}
```

***

## Platform

### `GET /v1/info/vault`

Returns the current vault state.

```json
{
  "totalReserves": "508113125671638784802",
  "availableReserves": "431255395240438378217",
  "insuranceFund": "51166942313050694271",
  "utilizationRate": "1512"
}
```

`utilizationRate` is in basis points (1512 = 15.12%).

***

## 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) for the full list.


# Python SDK

The MegaTAO Python SDK provides a REST-based info client for reading market and account data, and an on-chain write client for executing trades directly from Python.

## Installation

```bash
pip install megatao-sdk
```

For on-chain write operations (deposit, open/close positions, orders):

```bash
pip install "megatao-sdk[chain]"
```

## Quick start

```python
from megatao_sdk import MegaTAO

with MegaTAO() as client:
    markets = client.info.markets()
    for m in markets:
        print(f"{m.symbol}: {m.price}")
```

***

## Info client

`client.info` exposes all REST API endpoints. No private key required.

### Markets

```python
# All markets
markets = client.info.markets()
market.symbol       # "CHUTES"
market.price        # "87707801000000000"
market.funding_rate # "20"
market.long_oi      # "9003500000000000000"

# Single market
info = client.info.market("0x000...0040")

# Current prices (keyed by address)
prices = client.info.prices()
prices["0x000...0040"].price  # "87707850000000000"

# Candle data
candles = client.info.candles("0x000...0040", resolution="1h")

# Order book
ob = client.info.orderbook("0x000...0040", levels=10)
ob.bids[0].price    # best bid
ob.asks[0].price    # best ask

# Funding rates
rates = client.info.funding()
rates[0].rate       # current rate in bps
```

### Account

```python
# Margin balances
margin = client.info.margin("0xYourAddress")
margin.available_margin   # available to trade
margin.account_equity     # deposited + unrealized PnL
margin.unrealized_pnl

# Open positions
positions = client.info.positions("0xYourAddress")
pos.is_long           # True / False
pos.notional_value    # size in wei
pos.entry_price
pos.price_pnl         # unrealized PnL from price movement
pos.liquidation_price

# Open orders
orders = client.info.orders("0xYourAddress")

# Trade history
trades = client.info.trades("0xYourAddress")
```

### Platform

```python
vault = client.info.vault()
vault.total_reserves      # total TAO in vault
vault.available_reserves  # available for fills
vault.insurance_fund
vault.utilization_rate    # in bps (1512 = 15.12%)
```

### Async

Every method has an async equivalent via `AsyncMegaTAO`:

```python
import asyncio
from megatao_sdk import AsyncMegaTAO

async def main():
    async with AsyncMegaTAO() as client:
        markets = await client.info.markets()
        margin = await client.info.margin("0xYourAddress")

asyncio.run(main())
```

***

## Chain client

`client.chain` enables on-chain writes. Requires `pip install "megatao-sdk[chain]"` and a funded wallet with an RPC URL.

```python
from megatao_sdk import MegaTAO
from megatao_sdk.chain import TAO

client = MegaTAO(
    private_key="0xYourPrivateKey",
    rpc_url="https://your-bittensor-rpc-url",
)
```

`TAO = 10**18` — all amounts are in wei (18 decimals).

All methods accept `wait_for_receipt=True` to block until the transaction is mined and return a full `TxReceipt`.

### Collateral

```python
# Deposit 1 TAO
tx = client.chain.deposit(1 * TAO)

# Withdraw 0.5 TAO
tx = client.chain.withdraw(int(0.5 * TAO))
```

### Positions

```python
# Open a 5x long with 1 TAO margin, 0.5% max slippage
tx = client.chain.open_market_position(
    market="0x000...0040",
    is_long=True,
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    max_slippage_bps=50,
)

# Close a position fully (size_to_close_wei=0 means full close)
tx = client.chain.close_position(position_id=bytes.fromhex("..."))
```

### Orders

```python
# Limit order
tx = client.chain.place_limit_order(
    market="0x000...0040",
    is_buy=True,
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    price_wei=int(85e15),
)

# Take-profit (reduce-only, triggers on favorable price)
tx = client.chain.place_take_profit(
    market="0x000...0040",
    is_buy=False,   # close a long
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    price_wei=int(95e15),
)

# Stop-loss (reduce-only, triggers on adverse price)
tx = client.chain.place_stop_loss(
    market="0x000...0040",
    is_buy=False,   # close a long
    margin_wei=1 * TAO,
    leverage_wei=5 * TAO,
    price_wei=int(75e15),
)

# Cancel
tx = client.chain.cancel_order(market="0x...", order_id=b"...")
tx = client.chain.cancel_all_orders(market="0x...")
```

***

## Error handling

```python
from megatao_sdk import MegaTAO, APIError, MegaTAOError

with MegaTAO() as client:
    try:
        info = client.info.market("0xInvalidAddress")
    except APIError as e:
        print(f"HTTP {e.status_code}: {e.message}")
    except MegaTAOError as e:
        print(f"SDK error: {e}")
```


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


# Security & Audits

MegaTAO's smart contracts have been independently audited. We maintain an ongoing security partnership to ensure continued safety as the protocol evolves.

* **Independent audits** from multiple firms before launch
* **Ongoing review** of all contract upgrades through our BitSec partnership
* **Defense-in-depth** architecture with multiple layers of protection
* **Transparent disclosure** of audit findings and remediation

## In this section

* [Audit Reports](/audits/audit-reports): Details on completed audits by BitSec and XORs Software
* [Smart Contract Security](/audits/smart-contract-security): Technical security architecture and design patterns
* [Bug Bounty](/audits/bug-bounty): Responsible disclosure program

## Beta notice

MegaTAO is in beta. The protocol is actively being upgraded. We are working with BitSec on an ongoing basis to audit each update, and will publish a comprehensive final audit report once the protocol reaches its final form.


# Audit Reports

MegaTAO's smart contracts have been audited by two independent security firms. As the protocol is in beta and actively upgrading, we maintain an ongoing audit relationship to cover all changes.

## BitSec

**Status**: Ongoing partnership

BitSec has audited the MegaTAO Alpha Futures smart contracts and continues to review all protocol updates as they are developed. This ongoing partnership ensures that every contract upgrade is reviewed for security vulnerabilities before deployment.

**Scope**:

* Core trading contracts (position management, order execution, liquidation)
* Margin and vault systems
* Funding rate mechanics
* Proxy upgradeability and storage layout
* Access control and role management

[View BitSec February 2026 Audit Report](https://github.com/mega-tao/docs/blob/feat/docs/MegaTao-Final-Audit-Report.pdf)

## XORs Software

**Status**: Completed

XORs Software conducted an independent audit of the MegaTAO protocol, providing a separate assessment of the smart contract security.

**Scope**:

* Full protocol review
* Smart contract vulnerability analysis
* Business logic verification

## Comprehensive Final Audit

The MegaTAO protocol is currently in beta and undergoing active development. Once the protocol reaches its final form, we will work with BitSec to produce a comprehensive audit report covering the complete, production-ready codebase. This report will be published here.

## Audit Methodology

Both audits covered:

* **Access control:** Verification that privileged functions are properly restricted
* **Reentrancy:** Protection against reentrant calls in all state-changing functions
* **Arithmetic:** Correct handling of fixed-point math, overflow, and precision loss
* **Oracle manipulation:** Resistance to price oracle attacks
* **Liquidation logic:** Correctness of margin calculations and liquidation thresholds
* **Upgrade safety:** UUPS proxy pattern correctness and storage layout compatibility
* **Economic attacks:** Flash loan vectors, sandwich attacks, and MEV considerations

## Reporting Vulnerabilities

If you discover a security vulnerability, please report it responsibly through our [Bug Bounty](/audits/bug-bounty) program rather than disclosing it publicly.

***

*We believe in transparency. All future audit reports will be published in full on this page.*


# Smart Contract Security

MegaTAO employs multiple layers of security in its smart contract architecture. This page details the technical design patterns and safeguards built into the protocol.

## Upgradeability

### UUPS Proxy Pattern

The protocol uses the UUPS (Universal Upgradeable Proxy Standard) proxy pattern, allowing the core logic to be upgraded while preserving all user state and balances.

* **Proxy contract** holds all storage and receives all calls
* **Implementation contract** contains the business logic
* Only addresses with the `UPGRADER_ROLE` can trigger upgrades
* Upgrades go through a governance review process before deployment

### ERC-7201 Namespaced Storage

All contract storage uses the ERC-7201 namespaced storage pattern. This prevents storage collisions between different modules and ensures safe upgradeability.

* Each module (Margin, Position, Market, Order, Funding, Vault, Fee) has its own isolated storage namespace
* Storage slots are deterministically computed, eliminating collision risk across upgrades

## Position Security

### Flash Loan Protection

Positions cannot be opened and closed within the same block. This prevents flash loan attacks where an attacker could manipulate prices within a single transaction to extract value from the protocol.

### Simulate-Before-Execute

All write operations are simulated before execution. If the simulation fails (e.g., due to insufficient margin, invalid parameters, or contract reverts), the transaction is not submitted to the network. This protects users from wasting gas on transactions that would fail.

### One Position Per Market

Each trader can hold at most one position per market. This is enforced at the contract level through deterministic position IDs derived from the trader's address and the market address.

## Oracle Security

### Reserve-Based Pricing

Alpha token prices are derived from on-chain pool reserves using a dedicated price oracle contract. The oracle reads directly from Bittensor's Alpha token precompile, ensuring prices reflect actual on-chain liquidity.

### Multi-Oracle Design

The oracle architecture supports multi-source consensus to protect against price manipulation. This includes:

* Primary reserve-based pricing from on-chain data
* Support for additional oracle sources as fallbacks
* Price validation to reject anomalous values

## Risk Controls

### Circuit Breakers

The protocol includes circuit breakers that automatically activate when risk thresholds are exceeded:

* **Vault utilization limits:** Trading is restricted when vault exposure reaches critical levels
* **Maximum aggregate exposure:** Caps total protocol exposure across all markets
* **Per-market position limits:** Configurable maximum position size per trader per market

### Liquidation Safeguards

* **Maintenance margin** of 10% ensures positions are closed well before insolvency
* **Keeper incentives** (5% liquidation fee) ensure timely liquidation of unhealthy positions
* **Partial liquidation** support for large positions to minimize market impact
* **Emergency deleverage** capability for extreme market conditions

### Market Pause

Individual markets can be paused independently in response to anomalous conditions, without affecting trading on other markets.

## Insurance Fund

The protocol maintains an insurance fund to cover bad debt from positions that become insolvent before liquidation. This protects vault depositors from losses due to extreme market moves.

***

*For details on specific audit findings and remediations, see* [*Audit Reports*](/audits/audit-reports)*.*


# Bug Bounty

MegaTAO takes the security of user funds seriously. We encourage responsible disclosure of any vulnerabilities discovered in the protocol.

## Scope

The following are in scope for the bug bounty program:

* **Smart contracts:** All deployed MegaTAO contracts on Bittensor EVM
* **Oracle contracts:** Price oracle and related infrastructure
* **Economic vulnerabilities:** Attacks that could drain funds, manipulate prices, or cause incorrect liquidations

## Out of Scope

* Frontend/UI issues that do not affect funds
* Social engineering attacks
* Denial-of-service attacks on RPC infrastructure
* Issues in third-party dependencies outside our control
* Known issues already documented in audit reports

## How to Report

If you discover a vulnerability:

1. **Do not** disclose it publicly
2. **Do not** exploit it on mainnet
3. Email details to **<info@megatao.com>** with the subject line "Security Vulnerability Report"
4. Include a clear description, reproduction steps, and potential impact
5. Allow reasonable time for the team to investigate and remediate

## Response Timeline

* **Acknowledgment**: Within 48 hours of report
* **Initial assessment**: Within 5 business days
* **Remediation**: Depends on severity; critical issues are prioritized immediately

## Rewards

Rewards are determined on a case-by-case basis depending on the severity and impact of the vulnerability. Critical vulnerabilities that could result in loss of user funds receive the highest rewards.

| Severity | Description                                            | Reward Range |
| -------- | ------------------------------------------------------ | ------------ |
| Critical | Direct loss of user funds or protocol insolvency       | Case-by-case |
| High     | Significant economic impact or privilege escalation    | Case-by-case |
| Medium   | Limited economic impact or incorrect state transitions | Case-by-case |
| Low      | Minor issues with no direct financial impact           | Case-by-case |

## Responsible Disclosure

We ask all researchers to follow responsible disclosure practices. We will not take legal action against researchers who report vulnerabilities in good faith and follow the guidelines above.

***

*Thank you for helping keep MegaTAO secure. Reach out to <info@megatao.com> with any questions about this program.*


# Support

* [FAQ](/support/faq): Frequently asked questions


# FAQ

## General

### Is MegaTAO a Bittensor subnet?

No. MegaTAO is not a subnet. It is an independent protocol deployed on the Bittensor EVM that enables leveraged trading on Alpha token prices.

### Has MegaTAO been audited?

Yes. Smart contracts have been audited by BitSec (ongoing partnership) and XORs Software (independent audit). See [Audit Reports](/audits/audit-reports).

## Getting Started

### What do I need to trade on MegaTAO?

An EVM-compatible wallet (MetaMask, Coinbase Wallet, etc.) and TAO for margin and gas fees. See [How to Start Trading](/onboarding/how-to-start-trading).

### How do I get TAO into my wallet?

Two ways:

1. Click the Bittensor address button in the top right of the app, copy the address, and send TAO to it from an exchange or another wallet.
2. Import your existing Bittensor wallet mnemonic into an EVM wallet. Your TAO is available automatically through the address mapping.

### Do I need to add the Bittensor EVM network manually?

No. The app automatically prompts your wallet to switch to Bittensor EVM (Chain ID: 964) when you connect.

### What wallets are supported?

MetaMask, WalletConnect, Coinbase Wallet, Trust Wallet, and any EVM-compatible wallet.

## Trading

### What are perpetual futures?

Derivative contracts that track an asset's price without an expiration date. You can hold a position as long as you want (subject to funding costs, interest fees, and margin requirements).

### What is the trading fee?

0.25% of the notional value, charged on both opening and closing a position. A round-trip trade costs 0.5% total.

### What is the maximum leverage?

Currently 3x on all markets.

### What tokens can I trade?

MegaTAO supports perpetual futures on 12 Bittensor subnet Alpha tokens: CHUTES, LIUM, RIDGES, TARGON, VANTA, AFFINE, TEMPLAR, SCORE, IOTA, GRADIENTS, HIPPIUS, and BITMIND.

### Can I hold multiple positions?

One position per market. Up to 50 positions across different markets.

### What is slippage?

The difference between the expected execution price and the actual price. MegaTAO has dynamic slippage based on position size and vault utilization (0.1% to 20%). You set a `maxSlippage` parameter when opening a position. The transaction reverts if actual slippage exceeds it.

## Funding & Interest

### What is the funding rate?

A periodic payment between longs and shorts based on the imbalance in open interest. If there are more longs than shorts, longs pay shorts (and vice versa). This keeps futures prices aligned with spot prices.

### How is the funding rate calculated?

```
Funding Rate = (Long OI - Short OI) / Total OI x 0.75%
```

The rate is per 8-hour interval, capped at 0.75% in either direction. Funding accrues continuously and is settled when the position is modified or closed.

### What is the interest fee?

A separate fee charged to both longs and shorts based on vault utilization. It compensates vault depositors for capital at risk. The formula is `20% x utilization^2 + 0.01%`, capped at 80%.

### Do I pay funding and interest even on short trades?

Yes. Both accrue continuously based on time held. For short-duration trades (minutes to hours), the amounts are negligible.

## Margin & Liquidation

### What is the maintenance margin?

The minimum margin ratio required to keep a position open. Currently 10% on all markets (per-market configurable from 1% to 50%).

### What happens when I get liquidated?

Your position is closed at market price and a liquidation fee (currently 5%) is deducted from your remaining margin. Any leftover margin is returned to you. If losses exceed your margin, the insurance fund covers the shortfall.

### What is partial liquidation?

If your margin ratio is between the maintenance margin (10%) and maintenance margin + 5% buffer (15%), only part of your position may be closed, enough to bring the margin ratio back above the threshold.

### How do I avoid liquidation?

Close the position manually before the margin ratio reaches the maintenance level (avoids the liquidation fee entirely), or use lower leverage. At 3x leverage with 10% maintenance margin, a \~23% adverse price move triggers liquidation. At 5x leverage, only \~10%.

### Can I add margin to an open position?

You can deposit more TAO to your margin account. This improves your account equity and margin ratio across all cross-margin positions.

## Vault

### What is the protocol vault?

The vault provides liquidity for trades when there is no orderbook match. It acts as counterparty, filling orders instantly.

### Can I deposit into the vault?

Vault depositors earn yield from trading fees, funding, interest, and liquidation fees. The vault takes the opposite side of trader positions. It profits when traders lose and vice versa.

### Is there a deposit limit?

There is currently a per-user deposit cap and a global deposit cap. These limits will be expanded as the protocol matures.

## Security

### Is MegaTAO in beta?

Yes. The protocol is actively being developed and upgraded. Leverage limits and deposit caps are conservative and will expand over time. A comprehensive final audit will be published with BitSec once the protocol reaches its final form.

### How do I report a vulnerability?

Email <info@megatao.com> with the subject "Security Vulnerability Report". Do not disclose publicly. See [Bug Bounty](/audits/bug-bounty).

## Contact

* **Security issues**: <info@megatao.com>
* **Community**: Join our community channels for general questions and support
* **Twitter**: [@mega\_tao](https://twitter.com/mega_tao)


