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

avantis-trader-sdk

v1.0.0

Published

TypeScript SDK for interacting with Avantis decentralized leveraged trading platform

Readme

Avantis Trader SDK - TypeScript

A comprehensive TypeScript SDK for interacting with the Avantis decentralized leveraged trading platform. This SDK enables developers to access real-time price feeds, retrieve asset parameters, integrate price updates into trading systems, and execute trades on the Avantis platform.

Features

  • Complete Trading Lifecycle: Open, close, modify, and manage perpetual positions
  • Real-time Price Feeds: WebSocket integration with Pyth Network for live price updates
  • Market Data: Access open interest, utilization, skew, fees, and liquidity depth
  • Flexible Signing: Support for local private keys and AWS KMS for secure transaction signing
  • Type-Safe: Full TypeScript support with Zod validation
  • Modular Architecture: Clean separation of concerns with RPC modules

Installation

npm install avantis-trader-sdk

Or with yarn:

yarn add avantis-trader-sdk

Quick Start

import { TraderClient, TradeInput, TradeInputOrderType } from 'avantis-trader-sdk';

// Initialize client
const client = new TraderClient('https://your-rpc-endpoint.com');

// Set up signer
client.setLocalSigner('your-private-key');

// Get market snapshot
const snapshot = await client.snapshotRPC.getSnapshot();

// Open a trade
const tradeInput: TradeInput = {
  pair: 'BTC/USD',
  isLong: true,
  collateralInTrade: 100,
  leverage: 10,
  openPrice: 0, // Market order
  tp: 0,
  sl: 0,
  orderType: TradeInputOrderType.MARKET,
  maxSlippageP: 1,
};

const tradeTx = await client.tradeRPC.buildTradeOpenTx(tradeInput);
const receipt = await client.signAndGetReceipt(tradeTx);
console.log('Trade executed:', receipt?.hash);

Architecture

Main Components

TraderClient

Main entry point for interacting with Avantis smart contracts. Provides access to all RPC modules and handles transaction signing.

const client = new TraderClient(
  providerUrl: string,
  signer?: BaseSigner,
  feedClient?: FeedClient
);

Signers

LocalSigner - Sign transactions with a private key:

client.setLocalSigner('0x...');

KMSSigner - Sign transactions with AWS KMS (private key never leaves HSM):

client.setAwsKmsSigner('kms-key-id', 'us-east-1');

Custom Signer - Implement BaseSigner for custom signing logic:

class CustomSigner extends BaseSigner {
  async signTransaction(tx: TransactionRequest): Promise<string> {
    // Your custom signing logic
  }
  async getAddress(): Promise<string> {
    // Return address
  }
}

FeedClient

WebSocket client for real-time price feeds from Pyth Network:

import { FeedClient } from 'avantis-trader-sdk';

const feedClient = new FeedClient();

feedClient.registerPriceFeedCallback(feedId, (priceData) => {
  console.log('Price update:', priceData);
});

await feedClient.listenForPriceUpdates();

RPC Modules

PairsCache

Manages trading pair information with caching:

// Get all pairs
const pairs = await client.pairsCache.getPairsInfo();

// Get pair by name
const pairIndex = await client.pairsCache.getPairIndex('BTC/USD');

// Get pairs in a category
const pairsInGroup = await client.pairsCache.getPairsInGroup(0);

AssetParametersRPC

Retrieve asset-level parameters:

// Get open interest
const oi = await client.assetParams.getOI();

// Get utilization
const utilization = await client.assetParams.getUtilization();

// Get asset skew
const skew = await client.assetParams.getAssetSkew();

// Get price impact
const impact = await client.assetParams.getPriceImpactSpread(
  positionSize,
  isLong,
  pairIndex
);

CategoryParametersRPC

Retrieve category-level parameters (grouped pairs):

// Get category OI
const categoryOI = await client.categoryParams.getOI();

// Get category utilization
const categoryUtil = await client.categoryParams.getUtilization();

// Get category skew
const categorySkew = await client.categoryParams.getCategorySkew();

FeeParametersRPC

Fee calculations:

// Get margin fees
const fees = await client.feeParams.getMarginFee();

// Get opening fee
const openingFee = await client.feeParams.getOpeningFee(
  positionSize,
  isLong,
  pairIndex
);

// Get fee with referral discount
const feeWithReferral = await client.feeParams.getNewTradeOpeningFee(
  tradeInput,
  referrerAddress
);

TradingParametersRPC

Trading-related parameters:

// Get loss protection info
const lossProtection = await client.tradingParams.getLossProtectionInfo(
  tradeInput,
  openingFee
);

BlendedRPC

Blended calculations (25% asset + 75% category):

// Get blended utilization
const blendedUtil = await client.blendedParams.getBlendedUtilization();

// Get blended skew
const blendedSkew = await client.blendedParams.getBlendedSkew();

TradeRPC

Trading operations:

// Open trade
const openTx = await client.tradeRPC.buildTradeOpenTx(tradeInput);

// Close trade
const closeTx = await client.tradeRPC.buildTradeCloseTx(pairIndex, tradeIndex);

// Update margin
const marginTx = await client.tradeRPC.buildTradeMarginUpdateTx(
  pairIndex,
  tradeIndex,
  marginDelta,
  MarginUpdateType.DEPOSIT
);

// Update TP/SL
const tpSlTx = await client.tradeRPC.buildTradeTpSlUpdateTx(
  pairIndex,
  tradeIndex,
  newTp,
  newSl
);

// Cancel order
const cancelTx = await client.tradeRPC.buildOrderCancelTx(pairIndex, orderIndex);

// Get all trades
const trades = await client.tradeRPC.getTrades(traderAddress);

SnapshotRPC

Aggregate all market data:

// Get complete market snapshot
const snapshot = await client.snapshotRPC.getSnapshot();

// Get group snapshot
const groupData = await client.snapshotRPC.getGroupSnapshot(groupIndex);

// Get pair snapshot
const pairData = await client.snapshotRPC.getPairSnapshot('BTC/USD');

Types

TradeInput

interface TradeInput {
  pair: string;              // e.g., "BTC/USD"
  isLong: boolean;           // true = long, false = short
  collateralInTrade: number; // USDC collateral
  leverage: number;          // Leverage multiplier
  openPrice: number;         // Entry price (0 for market)
  tp: number;                // Take profit (0 to disable)
  sl: number;                // Stop loss (0 to disable)
  referrer?: string;         // Referrer address
  orderType: TradeInputOrderType;
  maxSlippageP: number;      // Max slippage percentage
}

TradeInputOrderType

enum TradeInputOrderType {
  MARKET = 'market',
  STOP_LIMIT = 'stop_limit',
  LIMIT = 'limit',
  MARKET_ZERO_FEE = 'market_zero_fee',
}

Snapshot

Complete market state with all trading pairs, grouped by category, including OI, utilization, skew, fees, and depth.

Configuration

Update contract addresses for your network:

import { setContractAddresses } from 'avantis-trader-sdk';

setContractAddresses({
  TradingStorage: '0x...',
  PairStorage: '0x...',
  Trading: '0x...',
  USDC: '0x...',
  // ... other contracts
});

Examples

See the /examples directory for complete examples:

  • basic-usage.ts - Basic trading operations
  • price-feed.ts - Real-time price feed integration
  • kms-signer.ts - AWS KMS signing

Development

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

Requirements

  • Node.js 16+
  • TypeScript 5+

Dependencies

  • ethers - Ethereum interaction
  • zod - Data validation
  • ws - WebSocket client
  • @aws-sdk/client-kms - AWS KMS integration (optional)

Platform Information

Avantis is a leveraged trading platform supporting:

  • Perpetual contracts on cryptocurrencies, forex, and commodities
  • Up to 100x leverage
  • USDC liquidity pool
  • Decentralized architecture

Resources

License

MIT

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

Security

Warning: Never commit private keys or sensitive credentials. Use environment variables or secure key management systems like AWS KMS for production deployments.

Support

For issues and questions: