@megatao/sdk
v1.2.0
Published
TypeScript SDK for MegaTAO perpetual futures protocol
Readme
@megatao/sdk
TypeScript SDK for the Alpha Futures perpetual futures protocol on Bittensor EVM.
Installation
npm install @megatao/sdkPeer dependency: requires viem ^2.0.0
Quick Start
import { MegaTAOClient, parseEther } from '@megatao/sdk';
const client = new MegaTAOClient('localhost', {
rpcUrl: 'http://localhost:8545',
privateKey: '0x...',
});
const alpha = client.getAlpha();
await alpha.deposit(parseEther('100'));
await alpha.openMarketPosition(
'0xMarketAddress',
true, // isLong
parseEther('10'), // margin
3000000000000000000n, // 3x leverage (1e18 format)
100n, // maxSlippage (bps)
);Architecture
MegaTAOClient creates viem clients internally and exposes two contract wrappers:
client.getAlpha()→AlphaViem— all trading, margin, positions, orders, vault, and market operationsclient.oracle→PriceOracleViem— price feeds from the on-chain oracle
All value parameters use native bigint. Prices, leverage, and margin use 1e18 precision. Slippage is in basis points.
API Reference
Trading
| Method | Params | Description |
|--------|--------|-------------|
| openMarketPosition | market, isLong, margin, leverage, maxSlippage | Open a market position with slippage protection |
| openMarketPositionWithStruct | MarketPositionParams | Open position using a params struct |
| closePosition | positionId, sizeToClose | Close (or partially close) a position |
| closeAllPositions | positionIds[] | Batch-close multiple positions via multicall |
| multicall | {functionName, args}[] | Batch arbitrary contract calls in one tx |
| placeLimitOrder | market, isBuy, margin, leverage, price, reduceOnlyType? | Place a limit order on the orderbook |
| placeLimitOrderWithStruct | LimitOrderParams | Place limit order using a params struct |
| cancelOrder | orderId | Cancel a specific limit order |
| cancelAllOrders | market | Cancel all orders in a market |
Margin
| Method | Params | Description |
|--------|--------|-------------|
| deposit | amount | Deposit collateral (sends native value for native token) |
| withdraw | amount | Withdraw available margin |
| getMarginBalance | trader | Raw deposited balance (excludes unrealized PnL) |
| getAccountSummary | trader | Balance, equity, unrealized PnL, locked and available margin |
| getLockedMargin | trader | Margin locked in open positions |
| getAvailableMargin | trader | Free margin available for new trades |
| getMaxUserDeposit | — | Per-user deposit cap |
| getMaxGlobalDeposits | — | Protocol-wide deposit cap |
| getTotalDeposits | — | Total deposits across all users |
Positions
| Method | Params | Description |
|--------|--------|-------------|
| getPosition | positionId | Full position data (margin, notional, entry price, etc.) |
| getPositionDetails | positionId | Extended position details struct |
| getPositionId | trader, market | Derive position ID from trader + market |
| hasPosition | trader, market | Check if a position exists |
| getUserPositions | trader | All position IDs for a trader |
| getUserPositionsSummary | trader | Aggregate stats across all positions |
| calculateUnrealizedPnl | positionId | Current unrealized PnL |
| getMarginRatio | positionId | Current margin ratio |
| isLiquidatable | positionId | Whether position can be liquidated |
| getLiquidationStatus | positionId | Liquidatable flag, margin ratio, required margin, liq price |
Orders
| Method | Params | Description |
|--------|--------|-------------|
| getBestBid | market | Best bid order ID |
| getBestAsk | market | Best ask order ID |
| getUserOrders | trader, market | All open order IDs for a trader in a market |
| getOrderDetails | orderId | Order info (trader, direction, notional, price, reduceOnly) |
Markets
| Method | Params | Description |
|--------|--------|-------------|
| getMarketInfo | market | OI, funding rate, active status, leverage/margin params |
| getMarketOpenInterest | market | Long and short open interest |
| getFundingRate | market | Current funding rate |
| getFundingState | market | Rate, cumulative index, last update, next funding time |
| getMaxPositionSize | market | Maximum allowed position size |
| getMarketDepth | market, isBuy, levels | Orderbook depth levels and total liquidity |
| getBidAskSpread | market | Current bid-ask spread info |
| getVWAP | market, size, isBuy | Volume-weighted average price for a given size |
| estimateMarketImpact | market, size, isBuy | Price impact estimate (avg/worst price, slippage) |
| getMarketLiquidityAnalysis | market | Comprehensive liquidity analysis struct |
Oracle (client.oracle)
| Method | Params | Description |
|--------|--------|-------------|
| getPrice | asset | Current price from on-chain reserves |
| getLatestPriceData | asset | Price + timestamp |
| getPriceData | asset | Price, timestamp, and confidence |
| getMultiplePrices | assets[] | Batch price fetch for multiple assets |
| subscribeToPriceUpdates | callback, asset? | Watch for PriceUpdated events |
Vault
| Method | Params | Description |
|--------|--------|-------------|
| getVaultStats | — | Total reserves, available reserves, exposure, unrealized PnL |
| getVaultBalance | — | Raw vault balance |
| getVaultState | — | Full vault state struct |
| getVaultExposure | market | Long/short/net exposure and utilization rate |
Execution
| Method | Params | Description |
|--------|--------|-------------|
| calculateVaultSlippage | market, size, isBuy | Estimated slippage from vault fill |
| getOptimalExecutionPlan | market, size, isLong, maxSlippage | Optimal split between orderbook and vault |
| getExecutionStrategyAnalysis | market, size, isLong, maxSlippage | Detailed execution strategy breakdown |
Keeper / Liquidation
| Method | Params | Description |
|--------|--------|-------------|
| liquidatePosition | positionId | Liquidate an under-margined position |
| claimKeeperRewards | — | Claim accumulated keeper rewards |
| updateFundingRates | markets[] | Trigger funding rate update for markets |
Events
| Method | Description |
|--------|-------------|
| parsePositionOpenedEvent(receipt) | Extract PositionOpened from tx receipt |
| parsePositionClosedEvent(receipt) | Extract PositionClosed from tx receipt |
| parseOrderPlacedEvent(receipt) | Extract OrderPlaced from tx receipt |
| parseHybridOrderExecutedEvent(receipt) | Extract HybridOrderExecuted from tx receipt |
| watchPositionOpenedEvent(callback) | Subscribe to PositionOpened events |
| watchMarginDepositedEvent(callback) | Subscribe to MarginDeposited events |
| watchMarginWithdrawnEvent(callback) | Subscribe to MarginWithdrawn events |
| getPositionOpenedEvents(from?, to?, trader?) | Query past PositionOpened events |
| getMarginDepositedEvents(from?, to?, trader?) | Query past MarginDeposited events |
| getMarginWithdrawnEvents(from?, to?, trader?) | Query past MarginWithdrawn events |
Helpers
| Method | Description |
|--------|-------------|
| waitForTransaction(hash) | Wait for tx confirmation and return receipt |
| getContractAddress() | Alpha contract address |
| getConstants() | All protocol constants (precision, max leverage, fees, etc.) |
| readContract({functionName, args}) | Generic read for unlisted view functions |
| estimateGas(functionName, args) | Estimate gas for any contract call |
Error Handling
import { ContractError } from '@megatao/sdk';
try {
await alpha.openMarketPosition(market, true, margin, leverage, slippage);
} catch (err) {
if (err instanceof ContractError) {
console.error(err.contractName, err.method, err.message);
}
}CLI
The SDK ships a CLI binary called alf:
npx alf --help
npx alf account balance
npx alf position listLicense
MIT
