@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/swapQuick 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 serviceapiUrl: string- API URL for one-shot servicetimeout?: number- Request timeout in milliseconds (optional)
Methods
getQuote(params, signal?)
Fetches a quote with intelligent fallback logic.
Parameters:
params: UnifiedQuoteParams- Quote parameterssignal?: 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 identifiertokenIn: string- Input token addresstokenOut: string- Output token addressamount: bigint- Amount to swapslippageBps?: 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 parameterscalculatePriceImpact(amountIn, amountOut, tokenInPrice, tokenOutPrice): number- Calculate price impact percentageformatTokenAmount(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:
- Primary: Intents SDK - Fast, local quote calculation using integrated DEX aggregators
- 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
