UNPKG

@gala-chain/launchpad-sdk

Version:

TypeScript SDK for Gala Launchpad Backend API - Production-ready DeFi token launchpad integration with wallet-based authentication, GalaChain trading, and comprehensive user operations. 100% tested (22/22 endpoints working).

924 lines 39.7 kB
/** * Launchpad API Controller * * This class provides access to all launchpad-related endpoints, handling * file uploads, pool creation, data fetching, and analysis operations. */ import { HttpClient } from '../utils/http'; import { Logger } from '../utils/Logger'; import { TokenResolverService } from '../services/TokenResolverService'; import { FetchPoolOptions, PoolsResult, AmountCalculationResult, CheckPoolOptions, GraphDataResult, TokenDistributionResult, LaunchTokenData, TokenBadgesResult, TokenSpotPrice } from '../types/launchpad.dto'; import { CalculatePreMintData } from '../types/trade.dto'; import { FetchVolumeDataOptions, CalculateBuyAmountOptions, CalculateSellAmountOptions, CalculateBuyAmountLocalOptions, CalculateSellAmountLocalOptions, HasTokenBadgeOptions, UploadImageByTokenNameOptions, FetchLaunchpadTokenSpotPriceOptions, CalculateBuyAmountForGraduationOptions } from '../types/options.dto'; /** * Launchpad API controller for pool creation and management operations * * This controller provides access to all launchpad-related functionality including: * - Image uploads for token branding * - Pool creation and lifecycle management * - Pool data fetching with filtering and pagination * - Amount calculations for trading operations * - Pool existence checking and validation * - Historical graph data and analytics * * All methods include comprehensive input validation, automatic type conversion * for backend compatibility, and detailed error handling. * * @category API Controllers * @since 1.0.0 * * @example Basic pool creation workflow * ```typescript * const sdk = new LaunchpadSDK({ wallet }); * * // 1. Upload token image * const uploadResult = await sdk.launchpad.uploadImage({ * file: imageFile, * tokenName: 'mytoken' * }); * * // 2. Launch the token * const launch = await sdk.launchpad.launchToken({ * tokenName: 'mytoken', * tokenSymbol: 'MTK', * tokenDescription: 'My awesome token', * tokenImage: uploadResult.data?.imageUrl, * preBuyQuantity: '500' * }); * * console.log('Sale created:', sale.vaultAddress); * ``` */ export declare class LaunchpadAPI { private readonly http; private readonly tokenResolver; private readonly logger; private readonly bundleHttp?; private readonly galaChainHttp?; private readonly dexApiHttp?; private readonly defaultCalculateAmountMode; private readonly metadataCache; constructor(http: HttpClient, tokenResolver: TokenResolverService, logger: Logger, bundleHttp?: HttpClient | undefined, galaChainHttp?: HttpClient | undefined, dexApiHttp?: HttpClient | undefined, defaultCalculateAmountMode?: 'local' | 'external'); /** * Helper to conditionally add properties to an object (for exactOptionalPropertyTypes compliance) * @private */ private addIfDefined; /** * Uploads an image for a token pool * * Uploads a token image that will be used for branding and display purposes. * Supports both browser File objects and Node.js Buffer objects for maximum * compatibility across environments. * * File Requirements: * - Format: PNG, JPG, JPEG, WebP * - Size: Maximum 5MB * - Dimensions: Recommended 512x512px or higher * - Aspect ratio: Square (1:1) recommended * * @category File Operations * @param options Upload configuration object * @param options.file Image file as File object (browser) or Buffer (Node.js) * @param options.tokenName Token name for the image (must be valid token name format) * @returns Promise that resolves to upload result containing image URL and metadata * @throws {ValidationError} If token name format is invalid * @throws {FileValidationError} If file doesn't meet requirements * @throws {Error} If upload fails due to network or server issues * @since 1.0.0 * * @example Browser file upload * ```typescript * // From file input element * const fileInput = document.querySelector('#image-upload') as HTMLInputElement; * const file = fileInput.files?.[0]; * * if (file) { * const result = await sdk.launchpad.uploadImage({ * file, * tokenName: 'mytoken' * }); * console.log('Image uploaded:', result.imageUrl); * } * ``` * * @example Node.js buffer upload * ```typescript * import * as fs from 'fs'; * * const imageBuffer = fs.readFileSync('./token-image.png'); * const result = await sdk.launchpad.uploadImage({ * file: imageBuffer, * tokenName: 'mytoken' * }); * console.log('Image URL:', result.imageUrl); * ``` * * @example With error handling * ```typescript * try { * const result = await sdk.launchpad.uploadImage({ file, tokenName }); * return result.imageUrl; * } catch (error) { * if (error instanceof FileValidationError) { * console.error('Invalid file:', error.message); * } else if (error instanceof ValidationError) { * console.error('Invalid token name:', error.message); * } else { * console.error('Upload failed:', error.message); * } * throw error; * } * ``` * * @see {@link launchToken} - Launch token using uploaded image */ uploadImageByTokenName(options: UploadImageByTokenNameOptions): Promise<string>; /** * Fetches pools with filtering and pagination * * ✅ VERIFIED: Real API payload confirmed - endpoint /launchpad/fetch-pool * * @param options Fetch options including type, search, and pagination * @returns Promise<PoolsResult> Clean pool data with full pagination */ private fetchPoolsFromAPI; /** * Calculates amount for trading operations with hybrid approach * Uses direct GalaChain for supported operations, falls back to backend for others * (PRIVATE - Internal use only) * * @private * @param options Amount calculation options * @returns Promise<AmountCalculationResult> Clean calculated amount */ private _getAmount; /** * Checks if a pool exists for given token name or symbol * * @param options Check options with token name and/or symbol * @returns Promise<boolean> True if pool exists, false otherwise */ checkPool(options: CheckPoolOptions): Promise<boolean>; /** * Fetches volume data for a token * * ✅ VERIFIED: Real API payload confirmed - endpoint /launchpad/get-graph-data * * @param options Volume data options * @returns Promise<GraphDataResult> Clean volume and price data points */ fetchVolumeData(options: FetchVolumeDataOptions): Promise<GraphDataResult>; /** * Gets pools with flexible filtering options (unified method) * * @param options Filtering options including search, tokenName, type, pagination * @returns Promise<PoolsResult> Filtered pools * * @example * ```typescript * // Get recent pools * const recent = await sdk.launchpad.getPools({ type: 'recent', page: 1, limit: 10 }); * * // Get popular pools * const popular = await sdk.launchpad.getPools({ type: 'popular', page: 1, limit: 10 }); * * // Search pools * const searched = await sdk.launchpad.getPools({ search: 'rocket', page: 1, limit: 5 }); * * // Get specific token pools * const tokenPools = await sdk.launchpad.getPools({ tokenName: 'ROCKETCH' }); * ``` */ fetchPools(options?: { search?: string; tokenName?: string; type?: 'recent' | 'popular'; page?: number; limit?: number; }): Promise<PoolsResult>; /** * Checks if a token name is available (convenience method) * * @param tokenName Token name to check * @returns Promise<boolean> True if available (pool doesn't exist) */ isTokenNameAvailable(tokenName: string): Promise<boolean>; /** * Checks if a token symbol is available (convenience method) * * @param symbol Token symbol to check * @returns Promise<boolean> True if available (pool doesn't exist) */ isTokenSymbolAvailable(symbol: string): Promise<boolean>; /** * Get buy token amount calculation with unified API (replaces getBuyWithNativeAmountByTokenName/getBuyExactTokenAmountByTokenName) * * Supports both local (instant) and external (network-based) calculation modes with a flexible priority chain: * 1. Per-call `options.mode` override (highest priority) * 2. SDK-level `calculateAmountMode` configuration * 3. Hardcoded default ('local') * * Priority chain resolution examples: * - Per-call override: `calculateBuyAmount({ mode: 'external' })` → uses 'external' (regardless of SDK config) * - SDK config: `new SDK({ calculateAmountMode: 'external' })` → uses 'external' (if no per-call override) * - Hardcoded default: `new SDK({})` → uses 'local' (if no config or override) * * @param {CalculateBuyAmountOptions} options - Calculation options * @param {string} options.tokenName - Token name (e.g., "dragnrkti", "rocketri", "unicornri") * @param {string} options.amount - Amount to calculate (GALA for 'native', tokens for 'exact') * @param {'native' | 'exact'} options.type - Calculation type: 'native' = GALA input, 'exact' = token output * @param {'local' | 'external'} [options.mode] - Calculation mode: 'local' = instant client-side, 'external' = network-based (optional, uses SDK default if not provided) * @param {string} [options.currentSupply] - Current token supply for local calculations (optional, auto-fetched if mode is 'local' and not provided) * @returns {Promise<AmountCalculationResult>} Calculated amount * @throws {ValidationError} If parameters are invalid or token not found * * @example * ```typescript * // Calculate tokens received when spending 1 GALA (uses SDK default mode) * const result = await sdk.launchpad.calculateBuyAmount({ * tokenName: "dragnrkti", * amount: "1", // 1 GALA * type: "native" * }); * * // Calculate GALA cost for buying 100 tokens (force external mode) * const result = await sdk.launchpad.calculateBuyAmount({ * tokenName: "dragnrkti", * amount: "100", // 100 tokens * type: "exact", * mode: "external" // Override: always use network calculation * }); * * // Fast local calculation with known supply (instant, no network calls) * const result = await sdk.launchpad.calculateBuyAmount({ * tokenName: "dragnrkti", * amount: "100", * type: "exact", * mode: "local", * currentSupply: "500000" // Pre-fetched supply eliminates API roundtrip * }); * ``` */ calculateBuyAmount(options: CalculateBuyAmountOptions): Promise<AmountCalculationResult>; /** * Calculate buy amount using external network calculation (GalaChain) * * Performs network-based calculation via GalaChain gateway. This method bypasses local * bonding curve calculations and queries the blockchain directly for accurate, real-time pricing. * * Use this method when: * - You need guaranteed accuracy from the blockchain source * - You want to ensure calculations match on-chain state exactly * - Network latency is acceptable for your use case * * For instant calculations without network calls, use `calculateBuyAmountLocal()` instead. * * @param options External calculation options * @param options.tokenName Token name (e.g., "dragnrkti", "rocketri", "unicornri") * @param options.amount Amount to calculate (GALA for 'native', tokens for 'exact') * @param options.type Calculation type: 'native' = GALA input, 'exact' = token output * @returns Promise<AmountCalculationResult> Calculated amount from GalaChain * @throws ValidationError if token not found or parameters invalid * * @example Calculate GALA cost for buying 100 tokens * ```typescript * const result = await sdk.launchpad.calculateBuyAmountExternal({ * tokenName: 'mytoken', * amount: '100', * type: 'exact' * }); * console.log('GALA needed:', result.amount); * ``` * * @example Calculate tokens received for 1 GALA * ```typescript * const result = await sdk.launchpad.calculateBuyAmountExternal({ * tokenName: 'mytoken', * amount: '1', * type: 'native' * }); * console.log('Tokens received:', result.amount); * ``` * * @since 3.8.0 * @category External Calculations */ calculateBuyAmountExternal(options: { tokenName: string; amount: string; type: 'native' | 'exact'; }): Promise<AmountCalculationResult>; /** * Get sell token amount calculation with unified API (replaces getSellExactTokenAmountByTokenName/getSellWithNativeAmountByTokenName) * * Supports both local (instant) and external (network-based) calculation modes with a flexible priority chain: * 1. Per-call `options.mode` override (highest priority) * 2. SDK-level `calculateAmountMode` configuration * 3. Hardcoded default ('local') * * Priority chain resolution examples: * - Per-call override: `calculateSellAmount({ mode: 'external' })` → uses 'external' (regardless of SDK config) * - SDK config: `new SDK({ calculateAmountMode: 'external' })` → uses 'external' (if no per-call override) * - Hardcoded default: `new SDK({})` → uses 'local' (if no config or override) * * @param {CalculateSellAmountOptions} options - Calculation options * @param {string} options.tokenName - Token name (e.g., "dragnrkti", "rocketri", "unicornri") * @param {string} options.amount - Amount to calculate (tokens for 'exact', GALA for 'native') * @param {'exact' | 'native'} options.type - Calculation type: 'exact' = token input, 'native' = GALA output * @param {'local' | 'external'} [options.mode] - Calculation mode: 'local' = instant client-side, 'external' = network-based (optional, uses SDK default if not provided) * @param {string} [options.currentSupply] - Current token supply for local calculations (optional, auto-fetched if mode is 'local' and not provided) * @param {string} [options.maxSupply] - Maximum token supply for local calculations (optional, auto-fetched if mode is 'local' and not provided) * @param {number} [options.reverseBondingCurveMaxFeeFactor] - Max fee factor for local calculations (optional, auto-fetched if mode is 'local' and not provided) * @param {number} [options.reverseBondingCurveMinFeeFactor] - Min fee factor for local calculations (optional, auto-fetched if mode is 'local' and not provided) * @returns {Promise<AmountCalculationResult>} Calculated amount * @throws {ValidationError} If parameters are invalid or token not found * * @example * ```typescript * // Calculate GALA received when selling 50 tokens (uses SDK default mode) * const result = await sdk.launchpad.calculateSellAmount({ * tokenName: "dragnrkti", * amount: "50", // 50 tokens * type: "exact" * }); * * // Calculate tokens needed to receive 0.5 GALA (force external mode) * const result = await sdk.launchpad.calculateSellAmount({ * tokenName: "dragnrkti", * amount: "0.5", // 0.5 GALA * type: "native", * mode: "external" // Override: always use network calculation * }); * * // Fast local calculation with all parameters (instant, no network calls) * const result = await sdk.launchpad.calculateSellAmount({ * tokenName: "dragnrkti", * amount: "50", * type: "exact", * mode: "local", * currentSupply: "500000", * maxSupply: "10000000", * reverseBondingCurveMaxFeeFactor: 0.5, * reverseBondingCurveMinFeeFactor: 0.0 // Pre-fetched params eliminate API roundtrip * }); * ``` */ calculateSellAmount(options: CalculateSellAmountOptions): Promise<AmountCalculationResult>; /** * Calculate sell amount using external network calculation (GalaChain) * * Performs network-based calculation via GalaChain gateway. This method bypasses local * bonding curve calculations and queries the blockchain directly for accurate, real-time pricing. * * Use this method when: * - You need guaranteed accuracy from the blockchain source * - You want to ensure calculations match on-chain state exactly * - Network latency is acceptable for your use case * * For instant calculations without network calls, use `calculateSellAmountLocal()` instead. * * @param options External calculation options * @param options.tokenName Token name (e.g., "dragnrkti", "rocketri", "unicornri") * @param options.amount Amount to calculate (tokens for 'exact', GALA for 'native') * @param options.type Calculation type: 'exact' = token input, 'native' = GALA output * @returns Promise<AmountCalculationResult> Calculated amount from GalaChain * @throws ValidationError if token not found or parameters invalid * * @example Calculate GALA received when selling 50 tokens * ```typescript * const result = await sdk.launchpad.calculateSellAmountExternal({ * tokenName: 'mytoken', * amount: '50', * type: 'exact' * }); * console.log('GALA received:', result.amount); * ``` * * @example Calculate tokens needed to sell to receive 0.5 GALA * ```typescript * const result = await sdk.launchpad.calculateSellAmountExternal({ * tokenName: 'mytoken', * amount: '0.5', * type: 'native' * }); * console.log('Tokens to sell:', result.amount); * ``` * * @since 3.8.0 * @category External Calculations */ calculateSellAmountExternal(options: { tokenName: string; amount: string; type: 'exact' | 'native'; }): Promise<AmountCalculationResult>; /** * Calculate buy amount locally using bonding curve formula * * Performs instant client-side calculation without network calls to GalaChain. * Uses exponential bonding curve mathematics to calculate GALA costs or token amounts. * * Benefits: * - Instant calculation (no network latency) * - No API rate limits * - Works offline with known supply * - Perfect for real-time price discovery * * Returns the same AmountCalculationResult structure as calculateBuyAmount for * drop-in compatibility with existing code. * * @param options Local calculation options * @param options.tokenName Token name (optional if currentSupply provided, required for auto-fetching) * @param options.amount Amount to calculate (GALA for 'native', tokens for 'exact') * @param options.type Calculation type: 'native' = GALA input, 'exact' = token output * @param options.currentSupply Current token supply (optional - auto-fetched if missing) * @returns Promise<AmountCalculationResult> Calculated amount and fees * @throws ValidationError if parameters are invalid or tokenName missing when auto-fetching needed * * @example Calculate with auto-fetch (requires tokenName) * ```typescript * const result = await sdk.launchpad.calculateBuyAmountLocal({ * tokenName: 'mytoken', * amount: '1000', * type: 'exact' * }); * ``` * * @example Pure calculation without network calls (tokenName not needed!) * ```typescript * const result = await sdk.launchpad.calculateBuyAmountLocal({ * amount: '1000', * type: 'exact', * currentSupply: '500000' * }); * console.log('GALA needed:', result.amount); * ``` * * @since 3.8.0 * @category Local Calculations */ calculateBuyAmountLocal(options: CalculateBuyAmountLocalOptions): Promise<AmountCalculationResult>; /** * Calculate sell amount locally using bonding curve formula * * Performs instant client-side calculation without network calls to GalaChain. * Uses exponential bonding curve mathematics to calculate GALA received or tokens needed. * * Benefits: * - Instant calculation (no network latency) * - No API rate limits * - Works offline with known parameters * - Perfect for real-time price discovery * * Returns the same AmountCalculationResult structure as calculateSellAmount for * drop-in compatibility with existing code. Includes reverse bonding curve fee * calculation that scales with supply. * * @param options Local calculation options * @param options.tokenName Token name (optional if all parameters provided, required for auto-fetching) * @param options.amount Amount to calculate (tokens for 'exact', GALA for 'native') * @param options.type Calculation type: 'exact' = token input, 'native' = GALA output * @param options.currentSupply Current token supply (optional - auto-fetched if missing) * @param options.maxSupply Maximum token supply (optional - auto-fetched if missing) * @param options.reverseBondingCurveMaxFeeFactor Max fee factor (optional - auto-fetched if missing) * @param options.reverseBondingCurveMinFeeFactor Min fee factor (optional - auto-fetched if missing) * @returns Promise<AmountCalculationResult> Calculated amount and fees * @throws ValidationError if parameters are invalid or tokenName missing when auto-fetching needed * * @example Calculate with auto-fetch (requires tokenName) * ```typescript * const result = await sdk.launchpad.calculateSellAmountLocal({ * tokenName: 'mytoken', * amount: '500', * type: 'exact' * }); * ``` * * @example Pure calculation without network calls (tokenName not needed!) * ```typescript * const result = await sdk.launchpad.calculateSellAmountLocal({ * amount: '500', * type: 'exact', * currentSupply: '500000', * maxSupply: '10000000', * reverseBondingCurveMaxFeeFactor: 0.5, * reverseBondingCurveMinFeeFactor: 0.0 * }); * ``` * * @since 3.8.0 * @category Local Calculations */ calculateSellAmountLocal(options: CalculateSellAmountLocalOptions): Promise<AmountCalculationResult>; /** * Calculate buy amount needed to graduate a token pool * * Convenience method that fetches pool details and calculates the exact * cost to buy all remaining tokens. Returns standard AmountCalculationResult. * * Performance optimization: Provide currentSupply to avoid fetching pool details twice. * * @param tokenNameOrOptions Token name string OR CalculateBuyAmountForGraduationOptions object * @returns Promise<AmountCalculationResult> Same result as calculateBuyAmount * @throws ValidationError if token not found or already graduated * * @example Legacy string usage * ```typescript * const result = await sdk.launchpad.calculateBuyAmountForGraduation('mytoken'); * console.log('Remaining tokens:', result.amount); * console.log('GALA required:', result.totalCost); * ``` * * @example Options object with performance optimization * ```typescript * import { CALCULATION_MODES } from '@gala-chain/launchpad-sdk'; * * const poolDetails = await sdk.fetchPoolDetailsForCalculation('anime'); * const result = await sdk.calculateBuyAmountForGraduation({ * tokenName: 'anime', * calculateAmountMode: CALCULATION_MODES.LOCAL, * currentSupply: poolDetails.currentSupply * }); * ``` */ calculateBuyAmountForGraduation(tokenNameOrOptions: string | CalculateBuyAmountForGraduationOptions): Promise<AmountCalculationResult>; /** * Creates a new token sale using the bundle backend * * ✅ VERIFIED: Real API payload confirmed - endpoint /bundle with CreateSale method * * This method provides a clean interface for creating token sales by handling: * - Optional image upload (if image is File/Buffer) * - DTO signing with required fields and defaults * - Bundle backend API call with proper request format * * @category Sale Operations * @param data Sale creation configuration * @param data.tokenName Unique token name (lowercase, alphanumeric, max 10 chars) * @param data.tokenSymbol Token symbol (3-10 characters) * @param data.tokenDescription Token description (max 500 characters) * @param data.tokenImage Optional image - File, Buffer, or URL string * @param data.preBuyQuantity Pre-buy quantity as decimal string * @param data.websiteUrl Optional website URL * @param data.telegramUrl Optional Telegram channel URL * @param data.twitterUrl Optional Twitter profile URL * @param data.tokenCategory Optional token category (defaults to 'Unit') * @param data.tokenCollection Optional token collection (defaults to 'Token') * @param data.reverseBondingCurveConfiguration Optional curve config (uses defaults) * @returns Promise that resolves to sale creation result * @throws {ValidationError} If any input validation fails * @throws {Error} If sale creation fails due to network or signature issues * @since 1.0.0 * * @example Launch a token with image upload * ```typescript * const result = await sdk.launchpad.launchToken({ * tokenName: 'mytoken', * tokenSymbol: 'MTK', * tokenDescription: 'My awesome token for trading', * tokenImage: imageFile, // File object from input * preBuyQuantity: '100', * websiteUrl: 'https://mytoken.com', * twitterUrl: 'https://twitter.com/mytoken' * }); * * console.log('Token launched successfully!'); * console.log('Transaction ID:', result.data); * ``` * * @example Launch a token with existing image URL * ```typescript * const result = await sdk.launchpad.launchToken({ * tokenName: 'simpletoken', * tokenSymbol: 'SIMPLE', * tokenDescription: 'A simple token', * tokenImage: 'https://example.com/token-logo.png', * preBuyQuantity: '50', * websiteUrl: 'https://simple.com' * }); * ``` * * @example Minimal token launch * ```typescript * const result = await sdk.launchpad.launchToken({ * tokenName: 'minimal', * tokenSymbol: 'MIN', * tokenDescription: 'Minimal token configuration', * preBuyQuantity: '10' * // Uses all defaults for optional fields * }); * ``` */ launchToken(data: LaunchTokenData): Promise<string>; /** * Get token distribution showing top holders * * Retrieves the list of top token holders for a specific token, * along with their balances and percentage of total supply. * * @param vaultAddress Token vault address in backend format (eth|40hex) * @returns Promise resolving to token distribution data * * @example * ```typescript * const distribution = await launchpad.getTokenDistributionByTokenName('mytoken'); * console.log('Top holders:', distribution.data?.holders); * ``` */ fetchTokenDistribution(tokenName: string): Promise<TokenDistributionResult>; /** * Gets badge achievements for a token * * This endpoint retrieves volume and engagement badges for a specific token. * Badges indicate milestones in trading volume and community engagement. * * **Note**: This endpoint does not require authentication. * * @param tokenName The name of the token to get badges for * @returns Promise<TokenBadgesResult> Badge information * * @example * ```typescript * const badges = await launchpad.getTokenBadges('mytoken'); * console.log('Volume badges:', badges.data?.volumeBadge); * console.log('Engagement badges:', badges.data?.engagementBadge); * ``` */ fetchTokenBadges(tokenName: string): Promise<TokenBadgesResult>; /** * Convenience method to check if a token has achieved a specific badge * * @param tokenName The token name to check * @param badgeType Type of badge to check ('volume' or 'engagement') * @param badgeName Specific badge name to check for * @returns Promise<boolean> Whether the token has achieved this badge * * @example * ```typescript * const has10kVolume = await launchpad.hasTokenBadgeByTokenName('mytoken', 'volume', '10k'); * const hasCrowdEngagement = await launchpad.hasTokenBadgeByTokenName('mytoken', 'engagement', 'CROWD'); * ``` */ hasTokenBadgeByTokenName(options: HasTokenBadgeOptions): Promise<boolean>; /** * Calculates pre-mint token amounts using bonding curve calculations * * This method calculates how many tokens a user will receive for a given * amount of GALA during the token launch phase. Uses standard bonding curve * math for consistent results with the rest of the trading system. * * **Implementation Note**: Falls back to mathematical calculation since the * original CallMemeTokenOut endpoint is not available on the backend. * * @param data Pre-mint calculation data * @returns Promise resolving to calculated token amounts and fees * * @example * ```typescript * const result = await launchpad.calculateInitialBuyAmount({ * nativeTokenQuantity: '100' // 100 GALA * }); * console.log('Tokens to receive:', result.amount); * console.log('Transaction fee:', result.transactionFee); * ``` */ calculateInitialBuyAmount(data: CalculatePreMintData): Promise<AmountCalculationResult>; /** * Fetches pool details from GalaChain optimized for local calculations * * Retrieves essential pool parameters needed for bonding curve calculations: * - Current supply (computed with full precision) * - Reverse bonding curve fee factors (normalized to numbers) * - Net fee factor (max - min, for convenience) * - Remaining tokens available in the pool * * This method is more efficient than `fetchPoolDetails()` as it returns only * the fields needed for calculations, with automatic normalization applied. * * @param tokenName Token name to fetch pool details for * @returns Promise with calculation-optimized pool details * @throws {ValidationError} If token not found or vault address invalid * @throws {ConfigurationError} If GalaChain client not configured * @throws {NetworkError} If API request fails * * @example * ```typescript * const details = await sdk.launchpad.fetchPoolDetailsForCalculation('mytoken'); * console.log('Current supply:', details.currentSupply); * console.log('Remaining tokens:', details.remainingTokens); * console.log('Max fee factor:', details.reverseBondingCurveMaxFeeFactor); * console.log('Min fee factor:', details.reverseBondingCurveMinFeeFactor); * console.log('Net fee factor:', details.reverseBondingCurveNetFeeFactor); * ``` * * @since 3.8.0 * @category Pool Information */ fetchPoolDetailsForCalculation(tokenName: string): Promise<{ currentSupply: string; remainingTokens: string; maxSupply: string; reverseBondingCurveMaxFeeFactor: number; reverseBondingCurveMinFeeFactor: number; reverseBondingCurveNetFeeFactor: number; }>; /** * Fetch current supply for a token (optimized for real-time calculations) * * Retrieves only the current supply from GalaChain, minimizing payload size. * Automatically detects and caches custom maxSupply values (if != 10M default). * * This method is optimized for frequent calls - it fetches only the minimal * data needed (sellingTokenQuantity + maxSupply) and caches custom maxSupply * for future use. * * @param tokenName Token name to fetch current supply for * @returns Promise<string> Current token supply as decimal string * @throws {ValidationError} If token not found or vault address invalid * @throws {ConfigurationError} If GalaChain client not configured * @throws {NetworkError} If API request fails * * @example * ```typescript * const supply = await sdk.launchpad.fetchCurrentSupply('mytoken'); * console.log('Current supply:', supply); // "5234567.123456789" * ``` * * @since 3.9.2 * @category Pool Information */ fetchCurrentSupply(tokenName: string): Promise<string>; /** * Gets the authenticated user's address in backend format * * @returns Address in eth|{40-hex-chars} format */ getAddress(): string; /** * Converts Ethereum address to backend format * * @param ethereumAddress Standard Ethereum address (0x...) * @returns Address in backend format (eth|...) */ formatAddressForBackend(ethereumAddress: string): string; /** * Validates a token name (exposed for external validation) * * @param tokenName Token name to validate * @throws ValidationError if validation fails */ validateTokenName(tokenName: string): void; /** * Validates pagination options (exposed for external validation) * * @param options Pagination options to validate * @throws ValidationError if validation fails */ validatePagination(options: FetchPoolOptions): void; /** * Fetch current USD spot prices for one or more DEX token symbols * * Uses the DEX API to retrieve current pricing information for tokens. * Supports both single symbol and multiple symbol requests with comma-separated format. * * @param symbols Single symbol string or array of symbols (e.g., 'GALA', ['GALA', 'SILK']) * @returns Promise<TokenSpotPrice[]> Array of simplified token spot prices * * @example Single token price * ```typescript * const prices = await launchpadAPI.fetchTokenSpotPrice('GALA'); * console.log(prices[0].price); // 0.01463269 * console.log(prices[0].symbol); // 'GALA' * ``` * * @example Multiple token prices * ```typescript * const prices = await launchpadAPI.fetchTokenSpotPrice(['GALA', 'SILK', 'MUSIC']); * prices.forEach(price => { * console.log(`${price.symbol}: $${price.price}`); * }); * ``` * * @throws Error if DEX API client not configured * @throws Error if no valid symbols provided * @throws Error if API request fails */ fetchTokenSpotPrice(symbols: string | string[]): Promise<TokenSpotPrice[]>; /** * Calculate spot price for a launchpad token in USD * * Calculates the USD price of a launchpad token by: * 1. Determining how many tokens you get for 1 GALA using calculateBuyAmount * 2. Getting the current GALA price in USD * 3. Computing: GALA_price_USD / tokens_per_GALA * * @param tokenNameOrOptions Token name string OR FetchLaunchpadTokenSpotPriceOptions object * @returns Promise<TokenSpotPrice> Spot price with symbol and USD price * * @example Legacy string usage * ```typescript * const price = await launchpadAPI.fetchLaunchpadTokenSpotPrice('dragnrkti'); * console.log(`${price.symbol}: $${price.price.toFixed(6)}`); * ``` * * @example Options object with performance optimization * ```typescript * import { CALCULATION_MODES } from '@gala-chain/launchpad-sdk'; * * const poolDetails = await sdk.fetchPoolDetailsForCalculation('anime'); * const price = await sdk.fetchLaunchpadTokenSpotPrice({ * tokenName: 'anime', * calculateAmountMode: CALCULATION_MODES.LOCAL, * currentSupply: poolDetails.currentSupply * }); * ``` * * @throws Error if token not found * @throws Error if price calculation fails * @throws Error if GALA price unavailable */ fetchLaunchpadTokenSpotPrice(tokenNameOrOptions: string | FetchLaunchpadTokenSpotPriceOptions): Promise<TokenSpotPrice>; /** * Warm cache from pool data (opportunistic caching) * * Public API for warming the token metadata cache with data extracted from * pool responses. This method is used internally by SDK operations and can * also be called directly for custom caching scenarios. * * The cache stores immutable token metadata (RBC fees, vault addresses, maxSupply) * that never change and can be reused across operations. * * @param tokenName - Token name (normalized to lowercase internally) * @param metadata - Partial metadata to cache (any combination of fields) * * @category Cache Management * @since 3.9.2 * * @example Warm cache from custom pool data * ```typescript * sdk.warmCacheFromPoolData('anime', { * vaultAddress: 'service|Token$Unit$ANIME$...', * reverseBondingCurveMinFeeFactor: 0.0, * reverseBondingCurveMaxFeeFactor: 0.5 * }); * ``` * * @example Warm cache from fetchPools response * ```typescript * const pools = await sdk.fetchPools({ limit: 20 }); * pools.pools.forEach(pool => { * sdk.warmCacheFromPoolData(pool.tokenName, { * vaultAddress: pool.vaultAddress, * reverseBondingCurveMinFeeFactor: parseFloat(pool.reverseBondingCurveMinFeePortion), * reverseBondingCurveMaxFeeFactor: parseFloat(pool.reverseBondingCurveMaxFeePortion) * }); * }); * ``` */ warmCacheFromPoolData(tokenName: string, metadata: Partial<import('../services/TokenMetadataCache').TokenMetadata>): void; /** * Get cache statistics * * Returns statistics about the token metadata cache including size, memory usage, * and age of entries. Useful for monitoring and debugging cache performance. * * ⚠️ **Performance**: O(n) - iterates over all cache entries. Do not call in hot paths. * * @returns Cache statistics * * @category Cache Management * @since 3.9.2 * * @example Monitor cache size * ```typescript * const stats = sdk.getCacheStats(); * console.log(`Cached ${stats.totalTokens} tokens (${stats.cacheSize} bytes)`); * console.log(`Oldest entry: ${new Date(stats.oldestEntry).toISOString()}`); * ``` */ getCacheStats(): import('../services/TokenMetadataCache').CacheStats; /** * Clear cache (all tokens or specific token) * * Removes cached metadata from the cache. This is useful for testing, * debugging, or forcing fresh data fetches. * * @param tokenName - Optional token name to clear (clears all if not provided) * * @category Cache Management * @since 3.9.2 * * @example Clear specific token * ```typescript * sdk.clearCache('anime'); // Clear only anime token * ``` * * @example Clear entire cache * ```typescript * sdk.clearCache(); // Clear all tokens * ``` */ clearCache(tokenName?: string): void; } //# sourceMappingURL=LaunchpadAPI.d.ts.map