npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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/sdk

Peer 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 operations
  • client.oraclePriceOracleViem — 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 list

License

MIT