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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@shogun-sdk/swap

v0.0.2-test.30

Published

Shogun Network Swap utilities and helpers

Readme

@shogun-sdk/swap

A comprehensive swap SDK for the Shogun Network that provides unified quote fetching across multiple chains and protocols with intelligent fallback mechanisms.

Features

  • 🔄 Unified Quote Interface - Single API for quotes across all supported chains
  • 🎯 Intelligent Fallback - Automatically falls back from intents-sdk to one-shot API
  • ⛓️ Multi-Chain Support - Ethereum, Arbitrum, Polygon, Solana, Sui, Hyperliquid, and more
  • 🛡️ Type Safety - Full TypeScript support with comprehensive type definitions
  • Performance Optimized - Built for both frontend and backend applications
  • 🔧 Flexible Configuration - Customizable timeouts, slippage, and routing options

Installation

npm install @shogun-sdk/swap
pnpm install @shogun-sdk/swap
yarn add @shogun-sdk/swap

Quick Start

Basic Usage

import { SwapClient, ChainID } from "@shogun-sdk/swap";

// Initialize the client
const swapClient = new SwapClient({
  apiKey: 'your-api-key',
  apiUrl: 'https://api.shogun.network',
  timeout: 30000
});

// Get a cross-chain quote
const quote = await swapClient.getQuote({
  sourceChainId: ChainID.Ethereum,
  destChainId: ChainID.Arbitrum,
  tokenIn: '0xA0b86a33E6441b8c4C8C0C4C0C4C0C4C0C4C0C4C', // USDC
  tokenOut: '0x1234567890123456789012345678901234567890', // Target token
  amount: BigInt('1000000'), // 1 USDC (6 decimals)
  senderAddress: '0x...',
  destinationAddress: '0x...',
  slippageBps: 50 // 0.5% slippage
});

console.log('Expected output:', quote.amountOut.toString());
console.log('Quote source:', quote.source); // 'intents-sdk' or 'one-shot'

Single-Chain Swaps

// Get a quote for same-chain swap
const singleChainQuote = await swapClient.getSingleChainQuote(
  ChainID.Ethereum,
  '0xA0b86a33E6441b8c4C8C0C4C0C4C0C4C0C4C0C4C', // USDC
  '0x1234567890123456789012345678901234567890', // Target token
  BigInt('1000000'), // 1 USDC
  50 // 0.5% slippage
);

Solana Swaps with Jito Tips

const solanaQuote = await swapClient.getQuote({
  sourceChainId: ChainID.Solana,
  destChainId: ChainID.Solana,
  tokenIn: 'So11111111111111111111111111111111111111112', // SOL
  tokenOut: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
  amount: BigInt('1000000000'), // 1 SOL
  jitoTip: 1000000, // 0.001 SOL tip
  slippageBps: 100 // 1% slippage
});

Advanced Usage

Error Handling and Fallback

try {
  const quote = await swapClient.getQuote(params);
  
  if (quote.error) {
    console.warn('Quote error:', quote.error);
    // Handle error case
  }
  
  if (quote.amountOut > 0n) {
    console.log('Valid quote from:', quote.source);
    // Proceed with swap
  }
} catch (error) {
  console.error('Failed to get quote:', error);
}

Request Timeout Control

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout

try {
  const quote = await swapClient.getQuote(params, controller.signal);
  clearTimeout(timeoutId);
} catch (error) {
  clearTimeout(timeoutId);
  if (error.name === 'AbortError') {
    console.error('Request timed out');
  }
}

Utility Functions

import { 
  validateSwapParams, 
  calculatePriceImpact, 
  formatTokenAmount,
  type SwapParams 
} from "@shogun-sdk/swap";

// Validate swap parameters
const swapParams: SwapParams = {
  tokenIn: '0x...',
  tokenOut: '0x...',
  amountIn: BigInt(1000000),
  amountOutMin: BigInt(900000),
  to: '0x...',
  deadline: Math.floor(Date.now() / 1000) + 3600
};

validateSwapParams(swapParams);

// Calculate price impact
const priceImpact = calculatePriceImpact(
  BigInt(1000000), // amountIn
  BigInt(990000),  // amountOut
  1.0,             // tokenInPrice
  1.0              // tokenOutPrice
);

// Format token amounts
const formattedAmount = formatTokenAmount(BigInt(1000000), 6); // "1.0"

API Reference

SwapClient

The main client class for fetching quotes.

Constructor

new SwapClient(config: SwapClientConfig)

Config Options:

  • apiKey: string - API key for one-shot service
  • apiUrl: string - API URL for one-shot service
  • timeout?: number - Request timeout in milliseconds (optional)

Methods

getQuote(params, signal?)

Fetches a quote with intelligent fallback logic.

Parameters:

  • params: UnifiedQuoteParams - Quote parameters
  • signal?: AbortSignal - Optional abort signal for cancellation

Returns: Promise<UnifiedQuoteResponse>

getSingleChainQuote(chainId, tokenIn, tokenOut, amount, slippageBps?, signal?)

Gets a quote for same-chain swaps.

Parameters:

  • chainId: ChainID - Chain identifier
  • tokenIn: string - Input token address
  • tokenOut: string - Output token address
  • amount: bigint - Amount to swap
  • slippageBps?: number - Slippage in basis points (optional)
  • signal?: AbortSignal - Optional abort signal (optional)

Returns: Promise<UnifiedQuoteResponse>

Types

UnifiedQuoteParams

interface UnifiedQuoteParams {
  sourceChainId: ChainID;
  destChainId: ChainID;
  tokenIn: string;
  tokenOut: string;
  amount: bigint;
  senderAddress?: string;
  destinationAddress?: string;
  slippageBps?: number;
  affiliateWallet?: string;
  affiliateFee?: string;
  jitoTip?: number;
  gasRefuel?: number;
  dynamicSlippage?: boolean;
  externalCall?: string;
}

UnifiedQuoteResponse

interface UnifiedQuoteResponse {
  amountOut: bigint;
  amountInUsd: number;
  amountOutUsd: number;
  amountOutReduced?: bigint;
  amountOutUsdReduced?: number;
  estimatedAmountInAsMinStablecoinAmount?: bigint;
  priceImpact: number;
  slippage: number;
  provider: string;
  rawQuote: any;
  source: 'intents-sdk' | 'one-shot';
  error?: string;
}

Utility Functions

  • validateSwapParams(params: SwapParams): void - Validate swap parameters
  • calculatePriceImpact(amountIn, amountOut, tokenInPrice, tokenOutPrice): number - Calculate price impact percentage
  • formatTokenAmount(amount: bigint, decimals: number): string - Format token amounts for display

Supported Chains

  • Ethereum
  • Arbitrum
  • Polygon
  • Solana
  • Sui
  • Hyperliquid
  • Base
  • BSC

Quote Sources

The SDK uses a two-tier approach for quote fetching:

  1. Primary: Intents SDK - Fast, local quote calculation using integrated DEX aggregators
  2. Fallback: One-Shot API - Comprehensive quote service with additional routing options

This ensures maximum reliability and the best possible quotes for your swaps.

Error Handling

The SDK provides comprehensive error handling:

  • Network Errors - Automatic retry with fallback
  • Invalid Parameters - Clear validation error messages
  • Timeout Handling - Configurable request timeouts
  • Quote Errors - Detailed error information in response

License

ISC