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

@swiv-sdk/perpetual-swap-sdk

v0.2.15

Published

SDK for Swiv Perpetual Swap Protocol

Downloads

24

Readme

PerpetualSwap SDK

A TypeScript SDK for interacting with the PerpetualSwap protocol on multiple networks.

Features

  • Support for multiple networks (Sonic Testnet, Solana Devnet, Localnet)
  • Admin operations (market initialization, oracle management)
  • User operations (position management, collateral operations)
  • Transaction building for client-side signing
  • Type-safe interactions with the protocol

Network Support

The SDK supports the following networks:

| Network | RPC URL | Contracts Program ID | Mock Oracle Program ID | |---------|---------|---------------------|----------------------| | Sonic Testnet | https://api.testnet.sonic.game/ | 9wdJq5R7VUuXDrAZBnXfDqc1vW6nwAW5aYneMKiryppz | F7r5C99gqsAXgsFJjKQD2KuEGVXgsXaYJgG9nn43cdfk | | Solana Devnet | https://api.devnet.solana.com | 9wdJq5R7VUuXDrAZBnXfDqc1vW6nwAW5aYneMKiryppz | F7r5C99gqsAXgsFJjKQD2KuEGVXgsXaYJgG9nn43cdfk | | Localnet | http://localhost:8899 | 2nga8op3u3j7Df7wsQv2n5hkRqjEFLjkWGGAfn4cHsfy | G2EDsqC3igU7f1PgvZgTSLdAMTn9qmwEq7y8Z92hFTCH |

Installation

npm install @perpetualswap/sdk

Basic Usage

1. Initialize SDK for a specific network

import { PerpetualSwapSDK, Network } from '@perpetualswap/sdk';

// For Sonic Testnet
const sdk = PerpetualSwapSDK.createForNetwork(Network.SONIC_TESTNET);

// For Solana Devnet
const sdk = PerpetualSwapSDK.createForNetwork(Network.SOLANA_DEVNET);

// For Localnet
const sdk = PerpetualSwapSDK.createForNetwork(Network.LOCALNET);

2. Initialize SDK with wallet for admin operations

import { PerpetualSwapSDK, Network } from '@perpetualswap/sdk';
import { Connection, Keypair } from '@solana/web3.js';

const keypair = Keypair.generate();
const connection = new Connection('https://api.testnet.sonic.game/', 'confirmed');

const sdk = new PerpetualSwapSDK(connection, wallet, keypair, Network.SONIC_TESTNET);

3. Get network information

console.log('Network:', sdk.getNetwork());
console.log('RPC URL:', sdk.getNetworkConfig().rpcUrl);
console.log('Contracts Program ID:', sdk.getContractsProgramId().toBase58());
console.log('Mock Oracle Program ID:', sdk.getMockOracleProgramId().toBase58());

Admin Operations

Initialize Market

const market = await sdk.initializeMarket({
  marketSymbol: "SOL-PERP",
  initialFundingRate: 0,
  fundingInterval: 3600,
  maintenanceMarginRatio: 500, // 5%
  initialMarginRatio: 1000, // 10%
  maxLeverage: 10,
  oracleAccount: new PublicKey('your-oracle-account'),
  mint: new PublicKey('your-token-mint')
});

// The market object now contains all market details
console.log('Market Symbol:', market.marketSymbol);
console.log('Market Authority:', market.authority.toString());
console.log('Market Oracle:', market.oracleAccount.toString());
console.log('Market Vault:', market.vault.toString());
console.log('Market Bump:', market.bump);
console.log('Is Active:', market.isActive);

// Get market details (if needed)
const marketDetails = await sdk.getMarket(market.authority);

// Get all markets
const allMarkets = await sdk.getAllMarkets();
console.log('Available markets:', allMarkets.map(m => m.marketSymbol));

// Create a margin account
const marginAccount = await sdk.createMarginAccount({
  market: market.authority,
  bump: 0 // This will be calculated
});

// Deposit collateral
await sdk.depositCollateral({
  marginAccount: marginAccount,
  market: market.authority,
  amount: new BN(1000000) // 1 token with 6 decimals
});

// Withdraw collateral
await sdk.withdrawCollateral({
  marginAccount: marginAccount,
  market: market.authority,
  amount: new BN(500000) // 0.5 token with 6 decimals
});

// Place orders using the global margin account
const orderTx = await sdk.buildPlaceMarketOrderTransaction({
  market: market.authority,
  marginAccount: marginAccount,
  side: 'long',
  size: new BN(1000), // 1000 tokens
  leverage: new BN(5), // 5x leverage
  oracleAccount: new PublicKey('your-oracle-account')
}, wallet.publicKey);

// Close positions
const closeTx = await sdk.buildCloseMarketOrderTransaction({
  market: market.authority,
  position: positionPda,
  marginAccount: marginAccount,
  oracleAccount: new PublicKey('your-oracle-account')
}, wallet.publicKey);

Key Changes in Global Margin Account Architecture

What Changed

The SDK now uses a global margin account system instead of market-specific margin accounts:

  • Before: Each market had its own margin account (market + user PDA)
  • Now: Single global margin account per user (user PDA only)

Benefits

  1. Better Capital Efficiency: Collateral can be shared across all markets
  2. Simplified UX: Users don't need to create separate margin accounts for each market
  3. Cross-Market Trading: Users can trade on multiple markets with the same collateral
  4. Reduced Account Creation: Only one margin account needed per user

Migration Guide

If you're upgrading from the previous version:

// OLD: Market-specific margin account
const [oldMarginAccountPda] = await sdk.findMarginAccountPda(userKey, marketKey);

// NEW: Global margin account
const [newMarginAccountPda] = await sdk.findMarginAccountPda(userKey);

// OLD: Create margin account for specific market
await sdk.createMarginAccount({ market: marketKey, marginType: { isolated: {} } });

// NEW: Create global margin account
await sdk.createMarginAccount({ marginType: { isolated: {} } });

User Operations

Build Transaction to Create Margin Account

const tx = await sdk.buildCreateMarginAccountTransaction({
  market: marketPda,
  marginType: { isolated: {} }
}, userPublicKey);

// Send transaction
await provider.sendAndConfirm(tx);

Build Transaction to Deposit Collateral

const tx = await sdk.buildDepositCollateralTransaction({
  marginAccount: marginAccountPda,
  market: marketPda,
  userTokenAccount,
  vault: marketVaultPda,
  mint: tokenMint,
  amount: new BN(50_000_000) // 50 tokens
}, userPublicKey);

await provider.sendAndConfirm(tx);

Build Transaction to Place Market Order

const tx = await sdk.buildPlaceMarketOrderTransaction({
  market: marketPda,
  marginAccount: marginAccountPda,
  side: 'long',
  size: new BN(100_000), // 0.1 tokens
  leverage: new BN(5),
  oracleAccount: mockOraclePda
}, userPublicKey);

await provider.sendAndConfirm(tx);

Read Operations

Get Market Details

const market = await sdk.getMarket(marketPda);
console.log('Market Symbol:', market.marketSymbol);
console.log('Max Leverage:', market.maxLeverage.toNumber());

Get Margin Account

constructor(connection: Connection, wallet: Wallet)

Methods

  • initializeMarket(params: InitializeMarketParams): Promise<Market> - Returns the complete market object
  • getMarket(marketAddress: PublicKey): Promise<Market>
  • getAllMarkets(): Promise<Market[]> - Returns all markets in the program
  • createMarginAccount(params: CreateMarginAccountParams): Promise<PublicKey>
  • getMarginAccount(marginAccountAddress: PublicKey): Promise<MarginAccount>
  • depositCollateral(params: DepositCollateralParams): Promise<void>
  • withdrawCollateral(params: WithdrawCollateralParams): Promise<void>

Market Object

The Market object contains the following properties:

interface Market {
  authority: PublicKey;
  marketSymbol: string;
  initialFundingRate: BN;
  fundingInterval: BN;
  maintenanceMarginRatio: BN;
  initialMarginRatio: BN;
  maxLeverage: BN;
  oracleAccount: PublicKey;
  bump: number;
  isActive: boolean;
  vault: PublicKey;
}

License

MIT