UNPKG

@gala-chain/launchpad-mcp-server

Version:

MCP server for Gala Launchpad - 102 tools (pool management, event watchers, GSwap DEX trading, price history, token creation, wallet management, DEX pool discovery, liquidity positions, token locks, locked token queries, composite pool data, cross-chain b

1,403 lines (1,166 loc) 116 kB
"use strict"; /** * SDK Usage Explanation Tool * * Provides detailed explanations and code examples for using the Gala Launchpad SDK directly. * Acts as a development reference showing how MCP tools map to SDK methods. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.explainSdkUsageTool = exports.COMPOSITE_TOPICS = exports.TOPIC_METHOD_MAPPING = void 0; const error_handler_js_1 = require("../../utils/error-handler.js"); const response_formatter_js_1 = require("../../utils/response-formatter.js"); /** * Topic-to-method mapping for documentation validation * Defines which SDK methods are covered by each documentation topic */ exports.TOPIC_METHOD_MAPPING = { // Trading Workflows 'buy-tokens': ['calculateBuyAmount', 'buy'], 'sell-tokens': ['calculateSellAmount', 'sell'], 'pool-graduation': ['calculateBuyAmountForGraduation', 'graduateToken'], // Pool Discovery 'fetch-pools': [ 'fetchPools', 'fetchAllPools', 'fetchPoolDetails', 'fetchPoolDetailsForCalculation', 'fetchVolumeData', 'fetchTokenPrice', 'fetchLaunchpadTokenSpotPrice', 'fetchTokenDistribution', 'fetchTokenBadges', 'resolveVaultAddress', 'resolveTokenClassKey' ], 'balances': ['fetchGalaBalance', 'fetchTokenBalance', 'fetchTokensHeld', 'fetchTokensCreated', 'fetchAvailableBalance'], // Token Creation & Management 'token-creation': ['isTokenNameAvailable', 'isTokenSymbolAvailable', 'fetchLaunchTokenFee', 'uploadTokenImage', 'launchToken'], 'token-details': ['fetchTokenDetails'], 'token-distribution': ['fetchTokenDistribution'], 'token-status': ['isTokenGraduated', 'onDexPoolCreation', 'onLaunchpadTokenCreation'], // Portfolio Management 'multi-wallet': [], // Composite workflow topic 'transfers': ['transferGala', 'transferToken'], 'locks': ['lockToken', 'unlockToken', 'fetchLockedBalance'], // DEX Trading 'dex-trading': ['getSwapQuoteExactInput', 'getSwapQuoteExactOutput', 'executeSwap', 'getSwapUserAssets', 'getAllSwapUserAssets', 'getSwapPoolInfo'], 'error-handling': [], // Cross-cutting concern // Developer Tools 'installation': [], // Setup topic 'local-calculations': ['calculateBuyAmountLocal', 'calculateSellAmountLocal', 'calculateBuyAmountExternal', 'calculateSellAmountExternal', 'calculateInitialBuyAmount'], // Market Data 'price-history': ['fetchPriceHistory', 'fetchAllPriceHistory'], 'spot-prices-smart-routing': ['fetchTokenPrice', 'getSwapPoolPrice'], // User Profile 'profile-management': ['fetchProfile', 'updateProfile', 'uploadProfileImage'], // Liquidity Management 'liquidity-positions': ['getSwapUserLiquidityPositions', 'getAllSwapUserLiquidityPositions', 'getSwapLiquidityPosition', 'getSwapLiquidityPositionById', 'addSwapLiquidityByPrice', 'addSwapLiquidityByTicks', 'getSwapEstimateRemoveLiquidity', 'removeSwapLiquidity', 'collectSwapPositionFees'], // Advanced Analysis 'advanced-dex-analysis': ['fetchCompositePoolData', 'calculateDexPoolQuoteExactAmountLocal', 'calculateDexPoolQuoteExactAmountExternal', 'calculateDexPoolQuoteExactAmount'], 'trading-analytics': ['fetchTrades'], 'utilities-and-helpers': ['fetchGalaPrice', 'fetchTokenClassesWithSupply', 'calculateInitialBuyAmount', 'getBundlerTransactionResult', 'getSwapPoolPrice', 'fetchSwapPositionDirect', 'getAllSwapUserAssets', 'cleanup', 'clearCache', 'getCacheInfo'], 'utilities-system': ['getAddress', 'getConfig', 'getEthereumAddress', 'getUrlByTokenName', 'getVersion', 'getWallet', 'hasWallet', 'setWallet', 'createWallet', 'connectWebSocket', 'disconnectWebSocket', 'isWebSocketConnected'], // DEX Leaderboards & Metrics 'fetch-all-dex-seasons': ['fetchAllDexSeasons'], 'fetch-current-dex-season': ['fetchCurrentDexSeason'], 'fetch-dex-leaderboard-by-season-id': ['fetchDexLeaderboardBySeasonId', 'fetchCurrentDexLeaderboard'], 'fetch-dex-aggregated-volume-summary': ['fetchDexAggregatedVolumeSummary'], 'fetch-dex-pools': ['fetchDexPools', 'fetchAllDexPools'], // Event Subscriptions 'event-subscriptions': ['subscribeToEvent', 'subscribeToDexLiquidityAdded', 'subscribeToDexLiquidityChanged', 'subscribeToDexLiquidityRemoved', 'subscribeToDexPoolAdded', 'subscribeToDexSwapExecuted', 'subscribeToTokenCreations'], // MCP Integration 'mcp-to-sdk-mapping': [], // Composite workflow topic // Bridge Operations 'bridge-operations': [ 'estimateBridgeFee', 'bridgeOut', 'bridgeIn', 'getBridgeStatus', 'waitForBridgeCompletion', 'fetchEthereumWalletTokenBalance', 'fetchEthereumWalletNativeBalance', 'fetchEthereumWalletAllBalances', 'fetchSolanaWalletTokenBalance', 'fetchSolanaWalletNativeBalance', 'fetchSolanaWalletAllBalances', 'getEthereumTokenBalance', 'getEthereumNativeBalance', 'getSolanaTokenBalance', 'getSolanaNativeBalance' ], }; /** * Composite topics that don't map 1:1 to SDK methods * These are workflow-based topics that group multiple methods */ exports.COMPOSITE_TOPICS = new Set([ 'buy-tokens', 'sell-tokens', 'pool-graduation', 'fetch-pools', 'balances', 'token-creation', 'token-status', 'multi-wallet', 'transfers', 'locks', 'dex-trading', 'error-handling', 'installation', 'local-calculations', 'price-history', 'token-details', 'spot-prices-smart-routing', 'profile-management', 'token-distribution', 'liquidity-positions', 'advanced-dex-analysis', 'trading-analytics', 'utilities-and-helpers', 'utilities-system', 'fetch-all-dex-seasons', 'fetch-current-dex-season', 'fetch-dex-leaderboard-by-season-id', 'fetch-dex-aggregated-volume-summary', 'fetch-dex-pools', 'event-subscriptions', 'mcp-to-sdk-mapping', 'bridge-operations', ]); /** * SDK code examples organized by topic */ const SDK_EXAMPLES = { // ============================================================================ // TRADING WORKFLOWS: Bonding Curve Trading // ============================================================================ // - buy-tokens: Purchase tokens from bonding curve pools // - sell-tokens: Sell tokens back to bonding curve pools // - pool-graduation: Transition pools to full DEX trading // ============================================================================ 'buy-tokens': ` ## Buying Tokens with SDK **Covers Methods:** - \`calculateBuyAmount()\` - \`buy()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function buyTokens() { // 1. Create SDK instance const sdk = createLaunchpadSDK({ wallet: 'your-private-key-or-mnemonic' }); // 2. Calculate expected amounts FIRST (REQUIRED) const calculation = await sdk.calculateBuyAmount({ tokenName: 'dragnrkti', amount: '100', // Spending 100 GALA type: 'native' // 'native' = GALA amount, 'exact' = token amount }); console.log('Expected tokens:', calculation.amount); console.log('RBC Fee:', calculation.reverseBondingCurveFee); console.log('Transaction fee:', calculation.transactionFee); // 3. Execute buy with slippage protection const result = await sdk.buy({ tokenName: 'dragnrkti', amount: '100', type: 'native', expectedAmount: calculation.amount, // REQUIRED: from step 2 maxAcceptableReverseBondingCurveFee: calculation.reverseBondingCurveFee, // RECOMMENDED slippageToleranceFactor: 0.01 // 1% slippage tolerance (REQUIRED) }); console.log('Transaction ID:', result.transactionId); console.log('GALA spent:', result.inputAmount); console.log('Tokens received:', result.outputAmount); console.log('Total fees:', result.totalFees); } \`\`\` **MCP Tool Equivalent:** \`gala_launchpad_buy_tokens\` `, 'sell-tokens': ` ## Selling Tokens with SDK **Covers Methods:** - \`calculateSellAmount()\` - \`sell()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function sellTokens() { // 1. Create SDK instance const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // 2. Calculate expected GALA FIRST (REQUIRED) const calculation = await sdk.calculateSellAmount({ tokenName: 'dragnrkti', amount: '1000', // Selling 1000 tokens type: 'exact' // 'exact' = exact tokens, 'native' = target GALA amount }); console.log('Expected GALA:', calculation.amount); console.log('RBC Fee:', calculation.reverseBondingCurveFee); // 3. Execute sell with slippage protection const result = await sdk.sell({ tokenName: 'dragnrkti', amount: '1000', type: 'exact', expectedAmount: calculation.amount, // REQUIRED: from step 2 maxAcceptableReverseBondingCurveFee: calculation.reverseBondingCurveFee, // RECOMMENDED slippageToleranceFactor: 0.01 // 1% slippage }); console.log('Tokens sold:', result.inputAmount); console.log('GALA received:', result.outputAmount); } \`\`\` **MCP Tool Equivalent:** \`gala_launchpad_sell_tokens\` `, 'pool-graduation': ` ## Pool Graduation with SDK **Covers Methods:** - \`calculateBuyAmountForGraduation()\` - \`graduateToken()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function graduatePool() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Option 1: Calculate graduation cost first (recommended) const calculation = await sdk.calculateBuyAmountForGraduation('dragnrkti'); console.log('GALA cost to graduate:', calculation.amount); console.log('RBC Fee:', calculation.reverseBondingCurveFee); console.log('Transaction fee:', calculation.transactionFee); // Check if you have enough balance const balance = await sdk.fetchGalaBalance(); if (parseFloat(balance.balance) < parseFloat(calculation.amount)) { throw new Error('Insufficient GALA balance'); } // Option 2: One-step graduation (convenience method) const result = await sdk.graduateToken({ tokenName: 'dragnrkti', slippageToleranceFactor: 0.01 // Optional: defaults to SDK config }); console.log('Pool graduated!'); console.log('Transaction ID:', result.transactionId); console.log('Total GALA spent:', result.inputAmount); console.log('Tokens received:', result.outputAmount); } \`\`\` **MCP Tool Equivalents:** - \`gala_launchpad_calculate_buy_amount_for_graduation\` - \`gala_launchpad_graduate_token\` `, // ============================================================================ // POOL DISCOVERY: Launchpad Pool Queries // ============================================================================ // - fetch-pools: Query bonding curve pools with pagination and filtering // - balances: Check GALA and token balances in wallet // ============================================================================ 'fetch-pools': ` ## Fetching Pool Data with Advanced Methods **Covers Methods:** - \`fetchPools()\` - \`fetchAllPools()\` - \`fetchPoolDetails()\` - \`fetchPoolDetailsForCalculation()\` - \`fetchVolumeData()\` - \`fetchTokenPrice()\` - \`fetchLaunchpadTokenSpotPrice()\` - \`fetchTokenDistribution()\` - \`fetchTokenBadges()\` - \`resolveVaultAddress()\` - \`resolveTokenClassKey()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; // 1. BASIC POOL FETCHING - With Pagination async function basicPoolFetching() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Fetch recent pools with pagination const pools = await sdk.fetchPools({ type: 'recent', limit: 10, page: 1 }); console.log(\`Found \${pools.total} pools, page \${pools.page} of \${pools.totalPages}\`); pools.pools.forEach(pool => { console.log(\`\${pool.tokenName}: \${pool.tokenSymbol}\`); }); } // 2. AUTO-PAGINATED FETCHING - Get ALL Pools async function fetchAllPools() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Auto-paginated - returns all pools without manual pagination const allPools = await sdk.fetchAllPools({ type: 'recent' }); console.log(\`Total pools: \${allPools.pools.length}\`); } // 3. POOL DETAILS - Complete information async function getPoolDetails(tokenName) { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); const details = await sdk.fetchPoolDetails(tokenName); console.log('Sale status:', details.saleStatus); // 'Ongoing' or 'Completed' console.log('Base price:', details.basePrice); console.log('Max supply:', details.maxSupply); console.log('Remaining tokens:', details.sellingTokenQuantity); } // 4. POOL DETAILS FOR CALCULATIONS - Optimized for math async function getOptimizedPoolDetails(tokenName) { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Returns only fields needed for bonding curve calculations const poolData = await sdk.fetchPoolDetailsForCalculation(tokenName); console.log('Current supply:', poolData.currentSupply); console.log('Remaining tokens:', poolData.remainingTokens); console.log('Max supply:', poolData.maxSupply); console.log('Reverse bonding curve max fee:', poolData.reverseBondingCurveMaxFeeFactor); } // 5. VOLUME & OHLCV DATA - Historical candlestick data async function getVolumeData(tokenName) { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Different resolutions: '1m', '5m', '15m', '1h', '4h', '1d' const volumeData = await sdk.fetchVolumeData({ tokenName: tokenName, from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // Last 7 days to: new Date(), resolution: '1h' // 1-hour candlesticks }); volumeData.forEach(candle => { console.log(\`\${candle.time}: O:\${candle.open} H:\${candle.high} L:\${candle.low} C:\${candle.close} V:\${candle.volume}\`); }); } // 6. SPOT PRICES - DEX tokens (GALA, SILK, MUSIC) async function getDexTokenPrices() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Fetch prices for multiple DEX tokens const prices = await sdk.fetchTokenPrice(['GALA', 'SILK', 'MUSIC']); console.log(\`GALA: $\${prices.GALA}\`); console.log(\`SILK: $\${prices.SILK}\`); console.log(\`MUSIC: $\${prices.MUSIC}\`); } // 7. LAUNCHPAD TOKEN SPOT PRICES async function getLaunchpadTokenPrice(tokenName) { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Get USD spot price for a launchpad token (anime, woohoo, etc.) const price = await sdk.fetchLaunchpadTokenSpotPrice(tokenName); console.log(\`\${tokenName} price: $\${price}\`); } // 8. RESOLVE UTILITY ADDRESSES async function resolveAddresses(tokenName) { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Get GalaChain vault address for token const vaultAddress = await sdk.resolveVaultAddress(tokenName); console.log(\`Vault address: \${vaultAddress}\`); // Get TokenClassKey for token const tokenClassKey = await sdk.resolveTokenClassKey(tokenName); console.log(\`TokenClassKey: \${tokenClassKey}\`); } // 9. COMPLETE INVESTMENT ANALYSIS WORKFLOW async function analyzeToken(tokenName) { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Get all token data in parallel const [details, volumeData, distribution, badges] = await Promise.all([ sdk.fetchPoolDetails(tokenName), sdk.fetchVolumeData({ tokenName, resolution: '1d' }), sdk.fetchTokenDistribution(tokenName), sdk.fetchTokenBadges(tokenName) ]); // Analyze status console.log(\`Pool Status: \${details.saleStatus}\`); console.log(\`Supply: \${details.currentSupply} / \${details.maxSupply}\`); // Analyze volume trend const volumes = volumeData.map(v => parseFloat(v.volume)); const avgVolume = volumes.reduce((a, b) => a + b, 0) / volumes.length; console.log(\`Avg daily volume: $\${avgVolume.toFixed(2)}\`); // Analyze distribution const top5Ownership = distribution.holders .sort((a, b) => parseFloat(b.balance) - parseFloat(a.balance)) .slice(0, 5) .reduce((sum, h) => sum + h.percentage, 0); console.log(\`Top 5 holders: \${top5Ownership.toFixed(2)}%\`); // Check badges console.log(\`Badges: \${badges.join(', ')}\`); } \`\`\` **MCP Tool Equivalents:** - \`gala_launchpad_fetch_pools\` - Paginated pool list - \`gala_launchpad_fetch_all_pools\` - Auto-paginated all pools - \`gala_launchpad_fetch_pool_details\` - Complete pool information - \`gala_launchpad_fetch_pool_details_for_calculation\` - Optimized for calculations - \`gala_launchpad_fetch_volume_data\` - OHLCV candlestick data - \`gala_launchpad_fetch_token_spot_price\` - DEX token prices (GALA, SILK, MUSIC) - \`gala_launchpad_fetch_launchpad_token_spot_price\` - Launchpad token USD prices - \`gala_launchpad_fetch_token_distribution\` - Token holder analysis - \`gala_launchpad_fetch_token_badges\` - Achievement badges - \`gala_launchpad_resolve_vault_address\` - Get vault address - \`gala_launchpad_resolve_token_class_key\` - Get TokenClassKey `, 'balances': ` ## Checking Balances with SDK **Covers Methods:** - \`fetchGalaBalance()\` - \`fetchTokenBalance()\` - \`fetchTokensHeld()\` - \`fetchTokensCreated()\` - \`fetchProfile()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function checkBalances() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Check GALA balance const galaBalance = await sdk.fetchGalaBalance(); console.log(\`GALA: \${galaBalance.balance}\`); console.log(\`Decimals: \${galaBalance.decimals}\`); console.log(\`Last updated: \${galaBalance.lastUpdated.toISOString()}\`); // Check specific token balance const tokenBalance = await sdk.fetchTokenBalance({ tokenName: 'dragnrkti', address: sdk.getAddress() }); console.log(\`Token: \${tokenBalance.quantity}\`); console.log(\`USD value: $\${tokenBalance.holdingPriceUsd}\`); console.log(\`GALA value: \${tokenBalance.holdingPriceGala}\`); // Check all tokens held const portfolio = await sdk.fetchTokensHeld({ address: sdk.getAddress(), limit: 20 }); console.log(\`Holding \${portfolio.total} different tokens\`); portfolio.tokens.forEach(token => { console.log(\`\${token.name}: \${token.quantity}\`); }); // Check tokens created by this wallet const createdTokens = await sdk.fetchTokensCreated({ address: sdk.getAddress(), limit: 10 }); console.log(\`Created \${createdTokens.total} tokens\`); createdTokens.tokens.forEach(token => { console.log(\` \${token.symbol}: \${token.name}\`); }); // Get user profile const profile = await sdk.fetchProfile(); console.log(\`Profile: \${profile.fullName}\`); // Check profile of another user const otherProfile = await sdk.fetchProfile('eth|0x...'); console.log(\`Other user: \${otherProfile.fullName}\`); } \`\`\` **MCP Tool Equivalents:** - \`gala_launchpad_fetch_gala_balance\` - \`gala_launchpad_fetch_token_balance\` - \`gala_launchpad_fetch_tokens_held\` - \`gala_launchpad_fetch_tokens_created\` - \`gala_launchpad_fetch_profile\` `, // ============================================================================ // TOKEN CREATION & MANAGEMENT: Launch New Tokens // ============================================================================ // - token-creation: Create new tokens and manage token metadata // - token-details: Fetch comprehensive token information // - token-distribution: Analyze token holder distribution // ============================================================================ 'token-creation': ` ## Creating Tokens with SDK **Covers Methods:** - \`isTokenNameAvailable()\` - \`isTokenSymbolAvailable()\` - \`fetchLaunchTokenFee()\` - \`uploadTokenImage()\` - \`launchToken()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function launchToken() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // 1. Check if name/symbol available const nameAvailable = await sdk.isTokenNameAvailable('mytoken'); const symbolAvailable = await sdk.isTokenSymbolAvailable('MTK'); if (!nameAvailable || !symbolAvailable) { throw new Error('Name or symbol already taken'); } // 2. Check launch fee const launchFee = await sdk.fetchLaunchTokenFee(); console.log(\`Launch fee: \${launchFee} GALA\`); // 3. Upload token image (Node.js only) const imageUpload = await sdk.uploadTokenImage({ tokenName: 'mytoken', imagePath: '/path/to/image.png' }); // 4. Launch the token const result = await sdk.launchToken({ tokenName: 'mytoken', tokenSymbol: 'MTK', tokenDescription: 'My awesome token', tokenImage: imageUpload.imageUrl, websiteUrl: 'https://mytoken.com', twitterUrl: 'https://twitter.com/mytoken', preBuyQuantity: '100' // Optional: pre-buy with GALA }); console.log('Token launched!'); console.log('Transaction ID:', result.transactionId); // Get frontend URL const url = sdk.getUrlByTokenName('mytoken'); console.log(\`View at: \${url}\`); } \`\`\` **MCP Tool Equivalents:** - \`gala_launchpad_check_token_name\` - \`gala_launchpad_check_token_symbol\` - \`gala_launchpad_fetch_launch_token_fee\` - \`gala_launchpad_upload_token_image\` - \`gala_launchpad_launch_token\` - \`gala_launchpad_get_url_by_token_name\` `, // ============================================================================ // PORTFOLIO MANAGEMENT: Multi-Wallet & Transfers // ============================================================================ // - multi-wallet: Manage multiple wallets and sessions // - transfers: Send GALA and tokens to other addresses // ============================================================================ 'multi-wallet': ` ## Multi-Wallet Support with SDK **Covers Methods:** - \`createWallet()\` (utility function) - \`buy()\`, \`sell()\`, \`launchToken()\` with privateKey override \`\`\`typescript import { createLaunchpadSDK, createWallet } from '@gala-chain/launchpad-sdk'; async function multiWalletExample() { // Main SDK with your wallet const sdk = createLaunchpadSDK({ wallet: 'your-main-private-key' }); // Create a test wallet const testWallet = createWallet(); console.log('Test wallet:', testWallet.address); // 1. Fund test wallet from main wallet await sdk.transferGala({ recipientAddress: testWallet.address, amount: '1000' }); // 2. Have test wallet buy tokens (using privateKey override) const buyCalc = await sdk.calculateBuyAmount({ tokenName: 'dragnrkti', amount: '100', type: 'native' }); const buyResult = await sdk.buy({ tokenName: 'dragnrkti', amount: '100', type: 'native', expectedAmount: buyCalc.amount, slippageToleranceFactor: 0.01, privateKey: testWallet.privateKey // Override to use test wallet }); console.log('Test wallet bought tokens'); // 3. Check balances for both wallets const mainBalance = await sdk.fetchGalaBalance(); // Main wallet const testBalance = await sdk.fetchGalaBalance(testWallet.address); // Test wallet console.log(\`Main wallet: \${mainBalance.balance} GALA\`); console.log(\`Test wallet: \${testBalance.balance} GALA\`); } \`\`\` **Key Points:** - All signing operations support \`privateKey\` parameter - Creates temporary SDK instance internally - Supports: buy, sell, launchToken, transfers, profile updates `, 'transfers': ` ## Token Transfers with SDK **Covers Methods:** - \`transferGala()\` - \`transferToken()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function transferTokens() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // Transfer GALA tokens const galaTransfer = await sdk.transferGala({ recipientAddress: '0x1234...', // or 'eth|1234...' amount: '100', uniqueKey: 'galaconnect-operation-my-transfer-123' // Optional idempotency }); console.log('GALA transfer ID:', galaTransfer.transactionId); console.log('Status:', galaTransfer.status); // Transfer launchpad tokens const tokenTransfer = await sdk.transferToken({ to: 'eth|5678...', tokenName: 'dragnrkti', amount: '1000', // Token amount uniqueKey: 'galaconnect-operation-token-456' }); console.log('Token transfer ID:', tokenTransfer.transactionId); } \`\`\` **Features:** - EIP-712 signatures for security - Supports both \`0x\` and \`eth|\` address formats - Optional idempotency keys prevent duplicates - Comprehensive validation **MCP Tool Equivalents:** - \`gala_launchpad_transfer_gala\` - \`gala_launchpad_transfer_token\` `, 'locks': ` ## Token Locking and Unlocking with SDK **Covers Methods:** - \`lockToken()\` - \`unlockToken()\` Lock and unlock tokens on GalaChain for staking, escrow, vesting, or governance. \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function tokenLocking() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // ============================================================================ // LOCK TOKENS - Basic usage // ============================================================================ // Lock 1000 tokens with default options (caller is lock authority) const lockResult = await sdk.lockToken({ tokenName: 'anime', amount: '1000' }); console.log('Lock transaction ID:', lockResult.transactionId); console.log('Lock status:', lockResult.status); // ============================================================================ // LOCK TOKENS - Advanced options // ============================================================================ // Lock with custom lock authority (another address can unlock) const escrowLock = await sdk.lockToken({ tokenName: 'anime', amount: '500', lockAuthority: 'eth|0x1234...', // Escrow agent address name: 'escrow-payment-001', // Identifier for matching during unlock expires: Date.now() + 30 * 24 * 60 * 60 * 1000 // Auto-release in 30 days }); console.log('Escrow lock created'); // Lock for time-based vesting const vestingLock = await sdk.lockToken({ tokenName: 'anime', amount: '10000', name: 'vesting-q1-2025', expires: new Date('2025-04-01').getTime() // Auto-unlock on April 1st }); console.log('Vesting lock created with expiry'); // ============================================================================ // UNLOCK TOKENS - Release locked tokens // ============================================================================ // Unlock tokens (must be called by lock authority) const unlockResult = await sdk.unlockToken({ tokenName: 'anime', amount: '500' }); console.log('Unlock transaction ID:', unlockResult.transactionId); console.log('Unlock status:', unlockResult.status); // Unlock with matching name (for specific lock identification) const namedUnlock = await sdk.unlockToken({ tokenName: 'anime', amount: '1000', name: 'escrow-payment-001' // Match the lock name used during lock }); console.log('Named unlock completed'); // ============================================================================ // STAKING WORKFLOW EXAMPLE // ============================================================================ async function stakingWorkflow() { // Step 1: Lock tokens for staking period const stake = await sdk.lockToken({ tokenName: 'anime', amount: '5000', name: 'staking-period-1', expires: Date.now() + 90 * 24 * 60 * 60 * 1000 // 90-day staking period }); console.log('Staked 5000 tokens for 90 days'); // Step 2: After staking period expires, unlock // (This would happen after the expires timestamp) const unstake = await sdk.unlockToken({ tokenName: 'anime', amount: '5000', name: 'staking-period-1' }); console.log('Unstaked tokens after staking period'); return { stake, unstake }; } // ============================================================================ // ESCROW WORKFLOW EXAMPLE // ============================================================================ async function escrowWorkflow(buyerAddress: string, sellerAddress: string) { // Step 1: Buyer locks payment in escrow (seller is lock authority) const escrow = await sdk.lockToken({ tokenName: 'anime', amount: '1000', lockAuthority: sellerAddress, // Seller can release upon delivery name: 'order-12345' }); console.log('Escrow created: seller can release payment upon delivery'); // Step 2: Seller releases escrow after delivery (seller calls unlock) // This would be executed by the seller's SDK instance // const release = await sellerSdk.unlockToken({ // tokenName: 'anime', // amount: '1000', // name: 'order-12345' // }); return escrow; } } \`\`\` **Key Features:** - **Lock Authority**: Specify who can unlock (defaults to caller) - **Expiration**: Optional auto-release timestamp for time-based vesting - **Named Locks**: Use \`name\` to identify specific locks for targeted unlocks - **EIP-712 Signatures**: Secure blockchain transactions - **Error Handling**: \`LockError\` class with specific error types **Lock Parameters:** | Parameter | Required | Description | |-----------|----------|-------------| | \`tokenName\` | Yes | Token to lock (e.g., 'anime') | | \`amount\` | Yes | Amount of tokens to lock | | \`lockAuthority\` | No | Address that can unlock (defaults to caller) | | \`expires\` | No | Timestamp in ms for auto-unlock | | \`name\` | No | Identifier for matching during unlock | **Unlock Parameters:** | Parameter | Required | Description | |-----------|----------|-------------| | \`tokenName\` | Yes | Token to unlock (e.g., 'anime') | | \`amount\` | Yes | Amount of tokens to unlock | | \`name\` | No | Lock name to match (if used during lock) | **Use Cases:** - **Staking**: Lock tokens for rewards/governance - **Escrow**: Third-party controlled releases - **Vesting**: Time-based token releases - **Governance**: Lock tokens for voting power **MCP Tool Equivalents:** - \`gala_launchpad_lock_token\` - \`gala_launchpad_unlock_token\` `, // ============================================================================ // DEX TRADING: GalaSwap Integration // ============================================================================ // - dex-trading: Execute trades, get quotes, manage assets on GalaSwap // - error-handling: Handle transaction errors gracefully // ============================================================================ 'dex-trading': ` ## DEX Trading with SDK - GalaSwap Integration **Covers Methods:** - \`getSwapQuoteExactInput()\` - \`getSwapQuoteExactOutput()\` - \`executeSwap()\` - \`getSwapUserAssets()\` - \`getAllSwapUserAssets()\` - \`getSwapPoolInfo()\` Trade graduated tokens on the GalaSwap DEX with real-time WebSocket monitoring: \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function dexTradingExample() { // 1. Initialize SDK with wallet const sdk = createLaunchpadSDK({ wallet: 'your-private-key', env: 'production' }); // ============================================================================ // QUOTES: Get pricing information (read-only operations) // ============================================================================ // Quote 1: Exact input (spend known GALA amount) const quoteIn = await sdk.getSwapQuoteExactInput('GALA', 'GUSDC', '100'); console.log('Spend 100 GALA → get ~' + quoteIn.estimatedOutput + ' GUSDC'); console.log('Price impact: ' + quoteIn.priceImpact + '%'); console.log('Fee tier: ' + quoteIn.feeTier + ' bps'); // Quote 2: Exact output (get known token amount) const quoteOut = await sdk.getSwapQuoteExactOutput('GALA', 'GUSDC', '100'); console.log('Get exactly 100 GUSDC → need ~' + quoteOut.inputAmount + ' GALA'); // ============================================================================ // EXECUTE: Perform the swap with slippage protection // ============================================================================ const result = await sdk.executeSwap( 'GALA', // from token 'GUSDC', // to token '100', // input amount (100 GALA) quoteIn.estimatedOutput, // Use quote's output! quoteIn.feeTier, // Use quote's fee tier! 0.01 // 1% slippage tolerance ); console.log('Transaction ID: ' + result.transactionId); console.log('Status: ' + result.status); console.log('Received: ' + result.outputAmount + ' ' + result.toToken); // ============================================================================ // PORTFOLIO: Check balances and assets // ============================================================================ const assets = await sdk.getSwapUserAssets(sdk.getEthereumAddress()); console.log('Assets in wallet:'); assets.forEach(asset => { console.log(' ' + asset.symbol + ': ' + asset.balance); }); // ============================================================================ // PORTFOLIO: Get ALL assets (auto-paginated) // ============================================================================ const allAssets = await sdk.getAllSwapUserAssets(sdk.getEthereumAddress()); console.log('Complete asset portfolio:'); console.log('Total assets: ' + allAssets.length); allAssets.forEach(asset => { console.log(' ' + asset.symbol + ': ' + asset.balance); }); // ============================================================================ // POOL INFO: Check liquidity before trading // ============================================================================ const pool = await sdk.getSwapPoolInfo('GALA', 'GUSDC'); console.log('GALA↔GUSDC Pool Info:'); console.log(' Liquidity: ' + pool.liquidity); console.log(' Available fee tiers: ' + pool.feeTiers.join(', ') + ' bps'); console.log(' 24h swaps: ' + pool.swapCount); } \`\`\` **Key Architecture:** - **Unified WebSocket**: Uses LaunchpadSDK's unified WebSocket for transaction monitoring - **Environment Alignment**: STAGE/PROD URLs must match between LaunchpadSDK and GSwapService - **Token Formats**: Supports simple names ('GALA') or full IDs ('GALA|Unit|none|none') - **Slippage Protection**: Always use quote values for execution - **Fee Tiers**: 500 (0.05%), 3000 (0.30%), 10000 (1.00%) - **Auto-Pagination**: Use \`getAllSwapUserAssets()\` for complete portfolio **MCP Tool Equivalents:** - \`gala_launchpad_get_swap_quote_exact_input\` - \`gala_launchpad_get_swap_quote_exact_output\` - \`gala_launchpad_execute_swap\` - \`gala_launchpad_get_swap_user_assets\` - \`gala_launchpad_get_all_swap_user_assets\` - \`gala_launchpad_get_swap_pool_info\` `, 'error-handling': ` ## Error Handling with SDK **Covers Methods:** - Error types from SDK (ValidationError, NetworkError, TransactionError, TokenNotFoundError, etc.) \`\`\`typescript import { createLaunchpadSDK, ValidationError, NetworkError, TransactionError, TokenNotFoundError } from '@gala-chain/launchpad-sdk'; async function errorHandlingExample() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); try { // Attempt trade const result = await sdk.buy({ tokenName: 'dragnrkti', amount: '100', type: 'native', expectedAmount: '5000', slippageToleranceFactor: 0.01 }); console.log('Success:', result.transactionId); } catch (error) { if (error instanceof ValidationError) { console.error('Invalid input:', error.message); console.error('Field:', error.field); console.error('Code:', error.code); } else if (error instanceof TokenNotFoundError) { console.error('Token does not exist:', error.tokenName); } else if (error instanceof NetworkError) { console.error('Network issue:', error.message); console.error('Status code:', error.statusCode); } else if (error instanceof TransactionError) { console.error('Transaction failed:', error.message); console.error('Transaction ID:', error.transactionId); } else { console.error('Unexpected error:', error); } } } \`\`\` **Error Types:** - \`ValidationError\` - Invalid input parameters - \`NetworkError\` - HTTP/network failures - \`TransactionError\` - Blockchain transaction failures - \`TokenNotFoundError\` - Token doesn't exist - \`ConfigurationError\` - SDK misconfiguration - \`WebSocketError\` - Real-time connection issues `, // ============================================================================ // DEVELOPER TOOLS & SETUP: Installation & Utilities // ============================================================================ // - installation: Install and import the SDK // - local-calculations: Offline bonding curve calculations // - utilities-and-helpers: Helper functions and utilities // ============================================================================ 'installation': ` ## Installing and Importing SDK **Covers Methods:** - SDK installation, imports, and configuration ### NPM Installation \`\`\`bash # Install SDK npm install @gala-chain/launchpad-sdk # Install peer dependencies npm install ethers@^6.15.0 @gala-chain/api@^2.4.3 @gala-chain/connect@^2.4.3 \\ socket.io-client@^4.8.1 axios@^1.12.2 bignumber.js@^9.1.2 zod@^3.25.76 \`\`\` ### Import Patterns \`\`\`typescript // Main SDK class import { LaunchpadSDK } from '@gala-chain/launchpad-sdk'; // Helper functions (recommended) import { createLaunchpadSDK, createTestLaunchpadSDK, createWallet, validateWalletInput } from '@gala-chain/launchpad-sdk'; // Error types import { ValidationError, NetworkError, TransactionError, TokenNotFoundError } from '@gala-chain/launchpad-sdk'; // Type definitions import type { PoolData, TradeResult, TokenBalanceInfo, BuyTokenOptions, SellTokenOptions } from '@gala-chain/launchpad-sdk'; \`\`\` ### Environment Configuration \`\`\`typescript // Production (default) const sdk = createLaunchpadSDK({ wallet: 'your-private-key', config: { baseUrl: 'https://lpad-backend-prod1.defi.gala.com', debug: false, timeout: 60000 } }); // Development const sdk = createLaunchpadSDK({ wallet: 'your-private-key', config: { baseUrl: 'https://lpad-backend-dev1.defi.gala.com', debug: true } }); \`\`\` `, 'local-calculations': ` ## Local Bonding Curve Calculations with SDK **Covers Methods:** - \`calculateBuyAmountLocal()\` - \`calculateSellAmountLocal()\` - \`calculateBuyAmountExternal()\` - \`calculateSellAmountExternal()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function localCalculationsExample() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // ============================================================================ // LOCAL CALCULATIONS - Instant quotes without network calls // ============================================================================ // 1. Buy calculation (local, instant) const localBuy = await sdk.calculateBuyAmountLocal({ tokenName: 'dragnrkti', amount: '100', // Spending 100 GALA type: 'native' // 'native' = GALA amount, 'exact' = token amount }); console.log('LOCAL Buy Quote (instant):'); console.log(' Tokens received:', localBuy.amount); console.log(' Transaction fee:', localBuy.transactionFee); console.log(' RBC Fee:', localBuy.reverseBondingCurveFee); // Always "0" for buys console.log(' Gas fee:', localBuy.gasFee); // 2. Sell calculation (local, requires pool details) const poolDetails = await sdk.fetchPoolDetails('dragnrkti'); const localSell = await sdk.calculateSellAmountLocal({ tokenName: 'dragnrkti', amount: '1000', // Selling 1000 tokens type: 'exact', // Required parameters from pool details: maxSupply: poolDetails.maxSupply.toString(), minFeePortion: poolDetails.reverseBondingCurveMinFeeFactor || 0, maxFeePortion: poolDetails.reverseBondingCurveMaxFeeFactor || 0 }); console.log('LOCAL Sell Quote (instant):'); console.log(' GALA received:', localSell.amount); console.log(' RBC Fee:', localSell.reverseBondingCurveFee); console.log(' Transaction fee:', localSell.transactionFee); // ============================================================================ // EXTERNAL CALCULATIONS - Real-time network queries (explicit) // ============================================================================ // 3. External buy (explicit network call) const externalBuy = await sdk.calculateBuyAmountExternal({ tokenName: 'dragnrkti', amount: '100', type: 'native' }); console.log('EXTERNAL Buy Quote (network):'); console.log(' Tokens received:', externalBuy.amount); // 4. External sell (explicit network call) const externalSell = await sdk.calculateSellAmountExternal({ tokenName: 'dragnrkti', amount: '1000', type: 'exact' }); console.log('EXTERNAL Sell Quote (network):'); console.log(' GALA received:', externalSell.amount); // ============================================================================ // A/B COMPARISON - Verify local accuracy // ============================================================================ const buyDiff = Math.abs(parseFloat(localBuy.amount) - parseFloat(externalBuy.amount)); const buyPct = (buyDiff / parseFloat(externalBuy.amount)) * 100; console.log('Local vs External Accuracy:'); console.log(\` Buy difference: \${buyPct.toFixed(4)}% (should be <0.01%)\`); // ============================================================================ // PERFORMANCE BENEFIT - Local is instant // ============================================================================ console.time('Local calculation'); await sdk.calculateBuyAmountLocal({ tokenName: 'dragnrkti', amount: '100', type: 'native' }); console.timeEnd('Local calculation'); // ~0ms (instant) console.time('External calculation'); await sdk.calculateBuyAmountExternal({ tokenName: 'dragnrkti', amount: '100', type: 'native' }); console.timeEnd('External calculation'); // ~200-500ms (network roundtrip) } \`\`\` **Benefits of Local Calculations:** - ✅ Instant quotes (no network delay) - ✅ Offline support (no internet required) - ✅ No API rate limits - ✅ Perfect accuracy (<0.01% difference) - ✅ Reduced server load **When to Use:** - Local: Price discovery, UI updates, offline scenarios - External: Production trades (always verify before executing) **MCP Tool Equivalents:** - \`gala_launchpad_calculate_buy_amount_local\` - \`gala_launchpad_calculate_buy_amount_external\` - \`gala_launchpad_calculate_sell_amount_local\` - \`gala_launchpad_calculate_sell_amount_external\` `, // ============================================================================ // MARKET DATA: Prices & Historical Data // ============================================================================ // - price-history: Fetch historical price data for tokens // - spot-prices-smart-routing: Get current token prices // ============================================================================ 'price-history': ` ## Historical Price Analysis with SDK **Covers Methods:** - \`fetchPriceHistory()\` - \`fetchAllPriceHistory()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function analyzePriceHistory() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key-or-mnemonic' }); // Paginated price history const history = await sdk.fetchPriceHistory({ tokenId: 'GUSDC|Unit|none|eth:0x...', from: new Date('2025-01-01'), to: new Date('2025-01-31'), sortOrder: 'DESC', page: 1, limit: 50 }); console.log(\`Found \${history.snapshots.length} snapshots\`); console.log(\`Total available: \${history.total} (page \${history.page} of \${history.totalPages})\`); // Auto-paginated complete history const allHistory = await sdk.fetchAllPriceHistory({ tokenId: 'GWETH|Unit|none|none', from: new Date('2024-01-01'), sortOrder: 'ASC' }); // Price analysis const prices = allHistory.snapshots.map(s => parseFloat(s.price)); const avg = prices.reduce((a, b) => a + b, 0) / prices.length; const variance = prices.reduce((sum, p) => sum + Math.pow(p - avg, 2), 0) / prices.length; const volatility = Math.sqrt(variance); console.log(\`Average: $\${avg.toFixed(4)}, Volatility: $\${volatility.toFixed(4)}\`); // Data export (CSV) const csv = ['timestamp,price'].concat( allHistory.snapshots.map(s => \`\${s.timestamp.toISOString()},\${s.price}\`) ).join('\\n'); console.log('CSV export:', csv.split('\\n').slice(0, 3).join('\\n')); } \`\`\` **Key Methods:** - \`fetchPriceHistory()\` - Paginated historical prices (max 50 per page) - \`fetchAllPriceHistory()\` - Auto-paginated complete history (all snapshots) **Response Fields:** - \`price\` - Token price as decimal string - \`timestamp\` - ISO 8601 timestamp - \`tokenId\` - Token identifier (pipe-delimited) **Use Cases:** - Technical analysis and charting - Volatility assessment - Price trend identification - Data export for analytics - Backtesting strategies **Token ID Formats:** - String: \`GUSDC|Unit|none|eth:0x...\` - Object: \`{ collection, category, type, additionalKey }\` **MCP Tool Equivalents:** - \`gala_launchpad_fetch_price_history\` - Paginated - \`gala_launchpad_fetch_all_price_history\` - Auto-paginated `, 'token-details': ` ## Token Details and Metadata with SDK **Covers Methods:** - \`fetchTokenDetails()\` \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function analyzeTokenDetails() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key-or-mnemonic' }); // Fetch token metadata const details = await sdk.fetchTokenDetails('GUSDC|Unit|none|eth:0x...'); console.log('Token Information:'); console.log(\` Name: \${details.name}\`); console.log(\` Symbol: \${details.symbol}\`); console.log(\` Decimals: \${details.decimals}\`); console.log(\` Verified: \${details.verified}\`); console.log(\` Trading: \${details.tradingEnabled}\`); console.log(\` Network: \${details.network}\`); console.log(\` Image: \${details.image}\`); // Pre-trading validation async function validateBeforeTrade(tokenId: string) { const token = await sdk.fetchTokenDetails(tokenId); if (!token.verified) { console.warn(\`⚠️ \${token.symbol} is NOT verified\`); } if (!token.tradingEnabled) { throw new Error(\`Trading disabled for \${token.symbol}\`); } if (token.network !== 'ethereum') { throw new Error(\`Wrong network: got \${token.network}\`); } return token; } // Batch token comparison const tokens = ['GALA|Unit|none|none', 'GUSDC|Unit|none|eth:0x...']; const details_list = await Promise.all( tokens.map(id => sdk.fetchTokenDetails(id).catch(() => null)) ); const verified = details_list.filter(t => t?.verified).length; console.log(\`Verified tokens: \${verified}/\${tokens.length}\`); } \`\`\` **Response Fields:** - \`symbol\` - Token symbol (e.g., 'GUSDC') - \`name\` - Full token name - \`decimals\` - Decimal places - \`verified\` - Verification status - \`tradingEnabled\` - Trading availability - \`network\` - Network name (e.g., 'ethereum') - \`contractAddress\` - Smart contract address - \`image\` - Token image URL - \`chainId\` - Blockchain chain ID **Use Cases:** - Pre-trading validation and safety checks - Display token metadata in UI - Verify token authenticity - Network compatibility checking **Token ID Formats:** - String: \`GUSDC|Unit|none|eth:0x...\` - Object: \`{ collection, category, type, additionalKey }\` **MCP Tool Equivalent:** \`gala_launchpad_fetch_token_details\` `, 'spot-prices-smart-routing': ` ## Smart Spot Price Routing with DEX Fallback **Covers Methods:** - \`fetchTokenPrice()\` (smart routing) - \`fetchLaunchpadTokenSpotPrice()\` - \`isTokenGraduated()\` The SDK intelligently routes pricing requests between DEX and Launchpad backends based on token graduation status - no need to know which backend a token uses! \`\`\`typescript import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk'; async function tokenPricing() { const sdk = createLaunchpadSDK({ wallet: 'your-private-key' }); // OPTION 1: SMART ROUTING (Recommended) - Automatic backend selection // Use tokenId for ANY token (graduated or ungraduated) // SDK automatically detects and routes to correct backend console.log('=== Smart Routing (Recommended) ==='); const smartPrice = await sdk.fetchTokenPrice({ tokenId: 'Token|Unit|ANIME|eth:0x...' // Works for ANY token! }); console.log(\`Token price: $\${smartPrice}\`); // ✅ Handles graduated tokens (DEX) automatically // ✅ Handles ungraduated tokens (Launchpad) automatically // ✅ No need to know token status beforehand // OPTION 2: EXPLICIT DEX PRICING - Graduated tokens only // Use tokenId directly for DEX tokens console.log('\\n=== Explicit DEX Pricing ==='); const dexPrices = await sdk.fetchTokenPrice({ tokenId: 'GALA|Unit|none|none' // Or other DEX token }); console.log(\`DEX Token GALA: $\${dexPrices}\`); // OPTION 3: EXPLICIT LAUNCHPAD PRICING - Ungraduated tokens // Use tokenName for launchpad bonding curve tokens console.log('\\n=== Explicit Launchpad Pricing ==='); const launchpadPrice = await sdk.fetchLaunchpadTokenSpotPrice('anime'); console.log(\`Launchpad token anime: $\${launchpadPrice}\`); // ADVANCED: Handle both pricing metho