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

@xyra-trade/perps

v0.2.2

Published

TypeScript SDK for interacting with Xyra Perps on Aptos

Downloads

348

Readme

@xyra-trade/perps

TypeScript SDK for interacting with Xyra Perps on Aptos.

Installation

@xyra-trade/perps requires @aptos-labs/ts-sdk as a peer dependency:

npm install @xyra-trade/perps @aptos-labs/ts-sdk
# or
pnpm add @xyra-trade/perps @aptos-labs/ts-sdk

Requirements

  • Node.js >= 22
  • @aptos-labs/ts-sdk ^6.0.0 (peer dependency)
  • An Aptos account (private key required only for executing transactions)

Quick Start

import { XyraPerps } from "@xyra-trade/perps";

const sdk = new XyraPerps({
  contractAddress: "0xabc...",
  apiBaseUrl: "https://api.xyra.trade/api/v1",
  wsBaseUrl: "wss://api.xyra.trade/ws",
  network: "mainnet",           // "mainnet" | "testnet" (default: "testnet")
  tradingAccount: "0xdef...",   // optional — required for positions, orders, trade history
  privateKey: "0x...",          // optional — enables sdk.execute (requires tradingAccount)
});

// Always call initialize() before using the SDK.
// It fetches all markets and, if a privateKey is configured,
// verifies on-chain that the key is authorized to trade on behalf of tradingAccount.
await sdk.initialize();

// High-level human-readable order placement (requires privateKey):
const result = await sdk.placeLimitOrder("ETH-USD", 0.1, 2500.0, true);
console.log("tx:", result.txHash);

Read-only (market data only)

const sdk = new XyraPerps({
  contractAddress: "0xabc...",
  apiBaseUrl: "https://api.xyra.trade/api/v1",
  wsBaseUrl: "wss://api.xyra.trade/ws",
});
await sdk.initialize();

Read with account context (positions, orders, history)

const sdk = new XyraPerps({
  contractAddress: "0xabc...",
  apiBaseUrl: "https://api.xyra.trade/api/v1",
  wsBaseUrl: "wss://api.xyra.trade/ws",
  tradingAccount: "0xdef...",
});
await sdk.initialize();

Full execution (user wallet or agent wallet)

privateKey can be the user's own wallet key, or an agent wallet key created at xyra.trade/agent. In both cases the key must be authorized on-chain — initialize() verifies this and throws if it isn't.

const sdk = new XyraPerps({
  contractAddress: "0xabc...",
  apiBaseUrl: "https://api.xyra.trade/api/v1",
  wsBaseUrl: "wss://api.xyra.trade/ws",
  tradingAccount: "0xdef...", // the account being traded on behalf of
  privateKey: "0x...",        // user or agent wallet private key
});
await sdk.initialize(); // throws if key is not authorized

Bring your own Aptos client

By default the SDK creates an Aptos client internally. If your app already has one, pass it via aptosClient to share a single instance:

import { XyraPerps, Aptos, AptosConfig, Network } from "@xyra-trade/perps";

const aptos = new Aptos(new AptosConfig({ network: Network.MAINNET }));

const sdk = new XyraPerps({
  contractAddress: "0xabc...",
  apiBaseUrl: "https://api.xyra.trade/api/v1",
  wsBaseUrl: "wss://api.xyra.trade/ws",
  aptosClient: aptos, // SDK uses this instead of creating its own
});
await sdk.initialize();

// The same `aptos` instance can be used elsewhere in your app
const info = await aptos.getAccountInfo({ accountAddress: "0x..." });

Aptos, AptosConfig, and Network are re-exported from @xyra-trade/perps for convenience so you don't need a separate import.

Clients

| Property | Description | |----------------------|----------------------------------------------------------| | sdk.rest | HTTP REST client for market data and account queries | | sdk.ws | WebSocket client for real-time data streams | | sdk.contract | On-chain view function calls via Aptos | | sdk.payloads | Build unsigned transaction payloads | | sdk.execute | Sign and submit transactions (requires privateKey) | | sdk.markets | Cached MarketInfo[] — populated by initialize() | | sdk.tradingAccount | Trading account address from config (if set) |

Market lookup

After initialize(), markets are cached and accessible without additional network calls:

// Full list
console.log(sdk.markets);

// Lookup by on-chain address or name
const market = sdk.getMarket("ETH-USD");
console.log(market?.name, market?.tickSize, market?.maxLeverages);

// Lookup by name only
const ethMarket = sdk.getMarketByName("ETH-USD");

High-Level Order API

After initialize(), human-readable size/price values are automatically converted to lots/ticks. tradingAccount defaults to the value in config.

import { TimeInForce } from "@xyra-trade/perps";

// Limit order: buy 0.1 ETH at $2500
await sdk.placeLimitOrder("ETH-USD", 0.1, 2500.0, true);

// With options
await sdk.placeLimitOrder("ETH-USD", 0.1, 2500.0, true, {
  timeInForce: TimeInForce.POST_ONLY,
  clientOrderId: "my-order-001",
});

// Market order: sell 0.05 ETH
await sdk.placeMarketOrder("ETH-USD", 0.05, false);

// Stop-limit: sell 0.1 ETH with limit at $2400, trigger at $2450
await sdk.placeStopLimitOrder("ETH-USD", 0.1, 2400.0, false, 2450.0);

// Stop-market
await sdk.placeStopMarketOrder("ETH-USD", 0.1, false, 2450.0);

// Take-profit limit
await sdk.placeTakeLimitOrder("ETH-USD", 0.1, 2700.0, false, 2680.0);

// Take-profit market
await sdk.placeTakeMarketOrder("ETH-USD", 0.1, false, 2680.0);

Frontend Wallet Adapter (build payloads)

For frontend usage, use build* methods to get a TransactionPayload for the wallet adapter:

const payload = sdk.buildLimitOrder("ETH-USD", 0.1, 2500.0, true);
await wallet.signAndSubmitTransaction(payload.toDict());

const payload = sdk.buildMarketOrder("ETH-USD", 0.05, false);
await wallet.signAndSubmitTransaction(payload.toDict());

const payload = sdk.buildStopLimitOrder("ETH-USD", 0.1, 2400.0, false, 2450.0);
await wallet.signAndSubmitTransaction(payload.toDict());

Deposit and Withdraw

// Deposit 100 USDC (auto-resolves user address from signer)
await sdk.deposit(100_000_000n);  // 100 USDC = 100 * 10^6

// Withdraw 50 USDC
await sdk.withdraw(50_000_000n);

Account Summary

// Cross-margin summary from chain
const summary = await sdk.getAccountSummary();
console.log("Equity:", summary.positionEquity);       // signed bigint (can be negative)
console.log("Unrealized PnL:", summary.totalUnrealizedPnl);
console.log("Available margin:", summary.availableMargin);

// Per-market position info
const info = await sdk.getMarketPositionInfo("ETH-USD");

Bulk Orders (Market Making)

const seqNum = (
  await sdk.contract.getPreviousBulkOrderSequenceNumber("0xaccount", "0xmarket")
).toString();

// Prices and sizes in human-readable form
await sdk.placeBulkOrder("ETH-USD", seqNum, [
  { price: 2490.0, size: 0.1 },
  { price: 2480.0, size: 0.2 },
], [
  { price: 2510.0, size: 0.1 },
  { price: 2520.0, size: 0.2 },
]);

Order Options

All high-level order methods accept an optional OrderOptions:

interface OrderOptions {
  tradingAccount?: string;    // override default trading account
  timeInForce?: TimeInForce;
  reduceOnly?: boolean;
  tpTrigger?: bigint | null;
  slTrigger?: bigint | null;
  clientOrderId?: string | null;
  executeOptions?: ExecuteOptions;
}

REST Client (sdk.rest)

Market Data

await sdk.rest.getHealth();
const { markets } = await sdk.rest.getMarkets();
const { market } = await sdk.rest.getMarket("0xmarketAddress");
const { trades } = await sdk.rest.getTrades("0xmarketAddress", { limit: 50 });
const orderbook = await sdk.rest.getOrderbook("0xmarketAddress", { depth: 20 });
const { price } = await sdk.rest.getPrice("0xmarketAddress");
const { funding } = await sdk.rest.getFunding("0xmarketAddress");
const history = await sdk.rest.getFundingHistory("0xmarketAddress", { limit: 100 });
const stats = await sdk.rest.getStats();
const marketStats = await sdk.rest.getMarketStats("0xmarketAddress");

Account Data

const address = "0xtrader";
await sdk.rest.getAccount(address);
await sdk.rest.getPositions(address);
await sdk.rest.getOpenOrders(address);
await sdk.rest.getCollateral(address);
await sdk.rest.getOrderHistory(address, { limit: 50, status: "filled" });
await sdk.rest.getTradeHistory(address, { limit: 50, market: "0xmarket" });
await sdk.rest.getAccountFundingHistory(address, { limit: 50 });
await sdk.rest.getCollateralHistory(address, { limit: 50 });

WebSocket Client (sdk.ws)

The WebSocket client reconnects automatically and replays subscriptions after reconnect.

await sdk.ws.connect();

// Public channels
await sdk.ws.subscribeTrades("0xmarket", (data, type, txVersion) => console.log(data));
await sdk.ws.subscribeOrderbook("0xmarket", (data, type) => console.log(data), 20);
await sdk.ws.subscribeTicker("0xmarket", (data) => console.log(data));
await sdk.ws.subscribePrices("0xmarket", (data) => console.log(data));
await sdk.ws.subscribeFunding("0xmarket", (data) => console.log(data));

// Private channels (require account address)
await sdk.ws.subscribeOrders("0xtrader", (data, type) => console.log(data));
await sdk.ws.subscribePositions("0xtrader", (data, type) => console.log(data));
await sdk.ws.subscribeCollateral("0xtrader", (data) => console.log(data));

// History channels
await sdk.ws.subscribeOrderHistory("0xtrader", (data, type) => console.log(data));
await sdk.ws.subscribeTradeHistory("0xtrader", (data, type) => console.log(data));
await sdk.ws.subscribeFundingHistory("0xtrader", (data) => console.log(data));
await sdk.ws.subscribeCollateralHistory("0xtrader", (data) => console.log(data));

// Global positions feed
await sdk.ws.subscribeAllPositions((data, type) => console.log(data));

await sdk.ws.unsubscribe("trades", "0xmarket");
sdk.ws.disconnect();

Execute Client (sdk.execute)

Requires privateKey and tradingAccount. Each method submits a transaction and waits for confirmation.

if (!sdk.execute) throw new Error("privateKey required");

// Create a trading account
await sdk.execute.createTradingAccount();

// Prepare account for a market (set leverage and margin mode)
await sdk.execute.prepareAccount(tradingAccount, market, 10, false /* cross */);

// Deposit / withdraw collateral
await sdk.execute.deposit(userAddress, tradingAccount, 100_000_000n);
await sdk.execute.withdraw(tradingAccount, 50_000_000n);
await sdk.execute.depositIsolated(userAddress, tradingAccount, market, 50_000_000n);
await sdk.execute.withdrawIsolated(tradingAccount, market, 50_000_000n);

// Place orders (lot/tick values)
await sdk.execute.placeLimitOrder(tradingAccount, market, 1000n, 20000n, true);
await sdk.execute.placeMarketOrder(tradingAccount, market, 500n, false);
await sdk.execute.placeStopLimitOrder(tradingAccount, market, 1000n, 19500n, false, 19800n);
await sdk.execute.placeTakeLimitOrder(tradingAccount, market, 1000n, 21000n, false, 20800n);

// TP/SL on open position
await sdk.execute.placeTpOrder(tradingAccount, market, null, 21000n, 20900n);
await sdk.execute.placeSlOrder(tradingAccount, market, null, 18000n, 18100n);

// Cancel orders
await sdk.execute.cancelOrder(tradingAccount, market, 12345n);
await sdk.execute.cancelOrderWithClientId(tradingAccount, market, "my-order-1");

// Decrease a reduce-only order's size
await sdk.execute.decreaseOrderSize(tradingAccount, market, 12345n, 200n);

// Bulk orders (market making) — accepts structured objects
await sdk.execute.placeBulkOrder(tradingAccount, market, seqNum, [
  { price: 19900n, size: 100n },
], [
  { price: 20100n, size: 100n },
]);
await sdk.execute.cancelBulkOrder(tradingAccount, market);

// Leverage management
await sdk.execute.increaseLeverage(tradingAccount, market, 20);

// Agent management
await sdk.execute.addAgent(tradingAccount, agentAddress);
await sdk.execute.removeAgent(tradingAccount, agentAddress);
await sdk.execute.pauseAgent(tradingAccount, agentAddress);
await sdk.execute.resumeAgent(tradingAccount, agentAddress);

Execute options

await sdk.execute.placeLimitOrder(..., {
  simulate: true,       // dry-run, no broadcast
  maxGasAmount: 10000,
  gasUnitPrice: 100,
  timeoutSecs: 60,
});

Payloads Client (sdk.payloads)

Build unsigned TransactionPayload objects for wallet adapter submission:

const payload = sdk.payloads.placeLimitOrder(
  tradingAccount, market, 1000n, 20000n, true,
);
// payload.toDict() → { type, function, type_arguments, arguments }
await wallet.signAndSubmitTransaction(payload.toDict());

Contract Client (sdk.contract)

Direct on-chain view calls with typed return values:

// Boolean
const authorized = await sdk.contract.isAuthorized("0xaccount", "0xagent");
const active = await sdk.contract.isMarketActive("0xmarket");

// bigint (u64/u128)
const collateral = await sdk.contract.getCollateralCross("0xaccount");
const markPrice = await sdk.contract.getMarkPrice("0xmarket");

// Signed bigint (I64/I128 decoded)
const freeCollateral = await sdk.contract.getFreeCollateralCross("0xaccount");
const fundingIndex = await sdk.contract.getCumulativeFundingIndex("0xmarket");

// Typed structs
const info = await sdk.contract.getAccountInfo("0xaccount");
console.log(info.totalCollateral, info.totalUnrealizedPnl, info.availableMargin);

const view = await sdk.contract.getPositionView("0xaccount", "0xmarket");
console.log(view.size, view.isLong, view.leverage);

// String
const owner = await sdk.contract.getTradingAccountOwner("0xaccount");
const addr = await sdk.contract.getMarketAddressFromName("ETH-USD");

Agent / Delegation Pattern

Agents let a backend key trade on behalf of a user's trading account:

// Step 1: Grant agent access (from the account owner's wallet)
const payload = sdk.payloads.addAgent("0xtrading-account", "0xagent-address");
await wallet.signAndSubmitTransaction(payload.toDict());

// Step 2: The agent SDK instance
const agentSdk = new XyraPerps({
  contractAddress: "0x...",
  apiBaseUrl: "...",
  wsBaseUrl: "...",
  tradingAccount: "0xtrading-account",
  privateKey: "0x<agent-private-key>",
});
await agentSdk.initialize();
await agentSdk.placeLimitOrder("ETH-USD", 0.1, 2500.0, true);

Error Handling

All errors extend XyraError and preserve the original cause:

import {
  XyraApiError,
  XyraWsError,
  XyraContractError,
  XyraExecuteError,
} from "@xyra-trade/perps";

try {
  await sdk.placeLimitOrder("ETH-USD", 0.1, 2500.0, true);
} catch (err) {
  if (err instanceof XyraExecuteError) {
    console.error("Transaction failed:", err.message);
    console.error("TX hash (if submitted):", err.txHash); // available even if waitForTransaction timed out
    console.error("Original cause:", err.cause);
  } else if (err instanceof XyraContractError) {
    console.error("View function failed:", err.message, err.cause);
  } else if (err instanceof XyraApiError) {
    console.error("API error:", err.status, err.body);
  }
}

| Error class | Thrown by | |----------------------|----------------------------------------| | XyraApiError | REST client HTTP errors | | XyraWsError | WebSocket connection / protocol errors | | XyraContractError | On-chain view function failures | | XyraExecuteError | Transaction submission failures |


Backend API Usage Notes

Sequence Number Limitation

The Aptos network requires each transaction to have a monotonically-increasing sequence number. The SDK fetches the current sequence number when building each transaction. If multiple execute* calls run concurrently (e.g., Promise.all), they all read the same sequence number and only the first submission succeeds.

Recommended patterns for backend usage:

// GOOD: serial — await each before the next
await sdk.placeLimitOrder("ETH-USD", 0.1, 2500, true);
await sdk.placeLimitOrder("ETH-USD", 0.2, 2490, true);

// BAD: concurrent — sequence number conflicts
await Promise.all([
  sdk.placeLimitOrder("ETH-USD", 0.1, 2500, true),
  sdk.placeLimitOrder("ETH-USD", 0.2, 2490, true),
]);

// BEST for high-throughput: use bulk orders (one transaction)
await sdk.placeBulkOrder("ETH-USD", seqNum,
  [{ price: 2490, size: 0.1 }, { price: 2480, size: 0.2 }],
  [{ price: 2510, size: 0.1 }, { price: 2520, size: 0.2 }],
);

Market Utilities

import { Market, MarketConfig } from "@xyra-trade/perps";

// After initialize(), Market instances are used internally.
// For manual construction:
const config = new MarketConfig("ETH-USD", 10n, 10000n, 10n, 50n);
const market = new Market(config, "0xmarket");

// Human ↔ on-chain conversions (string-based — no float imprecision)
const lots = market.toLots(0.1);       // 0.1 ETH → 1000n lots
const ticks = market.toTicks(2500.0);  // $2500 → 25000n ticks
const eth = market.fromLots(1000n);    // 1000n lots → 0.1
const usd = market.fromTicks(25000n);  // 25000n ticks → 2500.0

// Position estimates
const liqPrice = market.estimateLiquidationPrice(2500, 10, true /* long */);
const margin = market.estimateRequiredMargin(0.1, 2500, 10);
const pnl = market.calculateUnrealizedPnl(2500, 0.1, true, 2600);

Signed Integer Decoding

The Move contract uses I64/I128 structs (two's complement). The SDK exposes fromRaw() to decode view function responses:

import { I64, I128 } from "@xyra-trade/perps";

// Decode from Aptos view response format { bits: "..." }
const signed = I64.fromRaw({ bits: "18446744073709551611" }).toInt(); // -5n

// Decode from raw string
const val = I128.fromRaw("340282366920938463463374607431768211455").toInt(); // -1n

LLM Documentation

For a token-efficient SDK reference optimized for LLMs and AI coding tools, see llms.txt.


Contributing

See CONTRIBUTING.md for build/test commands and release conventions.


License

MIT