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).

867 lines (644 loc) 37.3 kB
# Changelog ## 3.15.4 ### Patch Changes - docs: comprehensive documentation updates for price history methods ### SDK Documentation Updates - Added complete documentation for all 4 price history methods in README.md - fetchPriceHistory (paginated) - fetchAllPriceHistory (auto-paginated) - fetchPrices (paginated latest prices) - fetchAllPrices (auto-paginated latest prices) - Added comprehensive examples showing usage patterns, configuration, and workflows - Updated MySQL configuration section with code examples for all 4 methods - Added price history patterns documentation to CLAUDE.md - Added latest token price queries section to CLAUDE.md with detailed examples - Created comprehensive fetch-all-price-history-demo.ts example script - Demonstrates statistical analysis, trend calculation, moving averages - Shows CSV export, time period comparison, and multi-token analysis - Includes volatility calculation and price statistics ### MCP Server Documentation Updates - Updated tool count from 52 to 55 in README (includes 4 price history tools) - Added "Price History & Analysis" section documenting 4 price history tools - Updated MCP installation version references (1.12.3, SDK 3.15.3) - Added complete price history tool descriptions with use cases and examples ### Agent Documentation Updates - Updated @agent-galachain-launchpad-developer.md - Updated SDK method count: 46 → 50 (includes price history) - Updated MCP tool count: 51 → 55 (includes 4 price history tools) - Updated version references: v3.11.0+ → v3.15.3+ - Added "Price History & Analysis" section to Complete Method Reference - Updated service architecture to include PriceHistoryService - Updated support section with latest version information ## 3.15.3 ### Patch Changes - Fix: Initialize connection pool in fetchPrices method fetchPrices was using this.pool! without calling ensureConnection first, causing a "Cannot read properties of null" error. Now properly initializes the connection pool before querying. ## 3.15.2 ### Patch Changes - Fix: Correct query result destructuring in fetchPrices and fetchAllPrices methods The fetchPrices method was incorrectly destructuring the query results, causing a "map is not a function" error. Changed from destructuring the first element to properly handling the array returned by executeQuery. ## 3.15.1 ### Patch Changes - Add comprehensive test coverage and example scripts for fetchPrices and fetchAllPrices methods **SDK Changes:** - Added 11 unit tests for fetchPrices and fetchAllPrices validation in price-history-service.test.ts - Added 19 integration tests for fetchPrices and fetchAllPrices functionality in price-history-service.integration.ts - Improved PriceHistoryService test coverage from 31.44% to 51.57% (+20.13 percentage points) - All 1096 tests passing **Example Scripts:** - Added examples/validate-fetch-prices.ts: Validates methods without MySQL setup, shows signatures and usage - Added examples/fetch-prices-demo.ts: Full demonstration with 5 use cases (pagination, sorting, auto-pagination, statistics) **Test Coverage Details:** - Unit Tests: Parameter validation, error handling, edge cases - Integration Tests: Empty results, latest price selection, multiple tokens, pagination, sorting, large datasets, auto-pagination combining ## 3.15.0 ### Minor Changes - Add fetchPrices() and fetchAllPrices() methods for fetching latest token prices Implements methods to fetch the most recent price snapshot for all unique tokens in the database, useful for market overviews and bulk price comparisons. Changes: - Added FetchPricesOptions and PricesResult types to priceHistory.dto.ts - Added fetchPrices() method to PriceHistoryService with pagination support - Added fetchAllPrices() convenience method with automatic pagination - Exposed both methods from LaunchpadSDK wrapper class - Created MCP tools: gala_launchpad_fetch_prices and gala_launchpad_fetch_all_prices - Updated tool count from 53 to 55 (pools category now has 18 tools) - Uses window function (ROW_NUMBER) for optimal database query performance ## 3.14.0 ### Minor Changes - Add fetchAllPriceHistory convenience method for automatic pagination Implements automatic pagination convenience method for price history queries, following the established fetchAllPools pattern for consistency. Changes: - Added fetchAllPriceHistory method to LaunchpadSDK wrapper class that handles pagination automatically - Created MCP tool gala_launchpad_fetch_all_price_history with automatic pagination support - Updated tool count from 52 to 53 (pools category now has 16 tools) - Follows established fetchAllPools pattern for API consistency ## 3.13.0 ### Minor Changes - 9dc16fd: feat: add PriceHistoryService with flexible tokenId support and fix FetchTokenBalanceOptions ghost parameter - **NEW**: Added `PriceHistoryService` for querying historical token price data from MySQL database with comprehensive pagination, date filtering, and sorting support - **NEW**: Added `fetchPriceHistory()` method to LaunchpadSDK with flexible `tokenId` parameter accepting string, TokenClassKey, or TokenInstanceKey formats - **NEW**: Added `PriceSnapshot` and `PriceHistoryResult` types for price history operations - **FIXED**: Removed unused `tokenClassKey` ghost parameter from `FetchTokenBalanceOptions` to improve API consistency - **IMPROVED**: All price history operations include read-only database protection and SQL injection prevention - **TESTED**: Added comprehensive unit tests (25+ test cases) and integration tests (21+ test cases) with production database verification This change aligns `fetchPriceHistory` with other SDK methods by using the flexible `tokenId` pattern for consistent token identification across all SDK operations. ## 3.12.8 ### Patch Changes - Fix SDK version detection by using build-time version injection instead of runtime file reading. The SDK now generates a version constant during build, ensuring it works in all environments (Node.js, browser, bundled). Additionally, added a `/version` slash command to the MCP server for easy version checking. ### Changes: - **SDK**: Implement build-time version injection via `scripts/inject-version.ts`, matching the MCP server pattern - **SDK**: Update `packages/sdk/package.json` to run `build:version` before compilation - **MCP Server**: Add new `utility` prompt category with `/version` command to fetch and display SDK/MCP server versions ## 3.12.7 ### Patch Changes - Fix: Include package.json in published npm package for version detection Resolves SDK version showing as "unknown" in runtime environments. The SDK's version loader uses `require('../../package.json')` to read the version at module load time, but package.json was not included in the published files array, causing the require to fail silently and return "unknown". This is essential for: - MCP server version reporting - Runtime version detection in applications - Dependency analysis tools - Following npm packaging best practices Package.json is now included in the published package files list, ensuring the version loader can successfully read and expose the SDK version. ## 3.12.6 ### Patch Changes - Fix: Properly define global File polyfill for Node.js environments Resolves "ReferenceError: File is not defined" error in CommonJS bundles by implementing a proper global File polyfill. The previous attempt to use web-file-polyfill as a side-effect import was ineffective because: 1. web-file-polyfill does NOT define a global File object - it only exports File as a named export 2. Zod schemas using z.instanceof(File) evaluate at module load time, before any conditional checks 3. The CommonJS bundle immediately referenced the undefined File global during schema initialization The fix creates a dedicated polyfill module that: - Imports File from web-file-polyfill - Defines it as a global in Node.js environments (where File is undefined) - Executes before all Zod schemas are evaluated - Maintains browser compatibility (native File API is already available) ## 3.12.5 ### Patch Changes - f92c0f6: Fix CommonJS bundle compatibility by downgrading uuid from ^13.0.0 to ^9.0.1 The CommonJS bundle (dist/index.cjs.js) was unable to load uuid@13.0.0 because that version is ESM-only. UUID v9.0.1 is the last version with dual ESM/CommonJS support, allowing the CommonJS bundle to properly require() the uuid package without ERR_REQUIRE_ESM errors. This fix enables full compatibility across all three bundle formats (UMD, ESM, CJS) for Node.js CommonJS environments and legacy bundlers. ## 3.12.4 ### Patch Changes - fix: Use web-file-polyfill for Node.js File API support (reverts complex lazy evaluation) Replaces complex lazy evaluation pattern with official web-file-polyfill package. This provides a clean, maintainable solution that allows z.instanceof(File) to work in Node.js environments without code complexity. Reverts unnecessary schema refactoring and Rollup configuration changes from v3.12.3. - Add web-file-polyfill import at SDK entry point - Revert to simple direct file schemas (no lazy evaluation) - Revert to simple Rollup configuration (single resolve plugin) - Fix CommonJS File API ReferenceError in Node.js 18+ ## 3.12.3 ### Patch Changes - 9b8e019: Fix CommonJS File API references causing ReferenceError in Node.js 18+. Implement lazy schema evaluation and Node.js-aware Rollup configuration to properly handle browser File API only in browser environments, eliminating need for user-side polyfills. ## 3.12.2 ### Patch Changes - Add dynamic version tools and fix CommonJS uuid bundling conflict **SDK Changes:** - Added `getVersion()` method to LaunchpadSDK class that returns the SDK version dynamically read from package.json - Created `src/constants/version.ts` with SDK_VERSION constant that reads from package.json at module load - Version is read using require() with proper error handling for different environments - **Fixed CommonJS build**: Updated `rollup.config.mjs` to bundle uuid only in CommonJS format - Conditional externals: uuid excluded from CJS externals but included in ESM/UMD externals - Resolves "ERR_REQUIRE_ESM" error when requiring uuid v13.0.0 (ESM-only package) in CommonJS environments - UMD/ESM bundles remain optimized with uuid external (~34KB) - CJS bundle includes uuid (~44KB) for complete self-contained CommonJS compatibility **MCP Server Changes:** - Created version injection script (`scripts/inject-version.ts`) that runs as a prebuild step - Added `build:version` npm script that injects MCP server version into `src/generated/version.ts` - Updated `.gitignore` to exclude auto-generated version file - Created `getVersionTool` MCP tool that returns both SDK and MCP server versions with timestamp Both versions are now dynamically read from their respective package.json files, ensuring they always stay in sync without manual version management in code. The CommonJS bundle now self-contains uuid to resolve ESM-only module conflicts in Node.js require() scenarios. ## 3.12.1 ### Patch Changes - Comprehensive documentation for CommonJS support and module formats **SDK Updates:** - Document all three module formats (ESM, CommonJS, UMD) - Add module resolution table showing automatic format selection - Clarify when to use each format with concrete examples - Explain package.json exports configuration **MCP Server Updates:** - Document CommonJS module format - Explain integration with SDK's multi-format support - Clarify automatic format selection by Node.js **Project Configuration (CLAUDE.md):** - Enhanced Build System section with detailed format breakdown - Added comprehensive "Launchpad SDK Module Formats (v3.12.0+)" section - Include size monitoring metrics for all three bundles ## 3.12.0 ### Minor Changes - Add CommonJS build support with proper exports configuration - Export CommonJS bundle (`index.cjs.js`) via package.json exports field - Maintain ESM as primary format with proper import/require resolution - Add CommonJS bundle to size-limit checks - Keep UMD bundle as "main" fallback for backward compatibility Enables legacy CommonJS projects to import the SDK without requiring build tool transformations. ## 3.11.8 ### Patch Changes - Fix: Update STAGE environment launchpadFrontendUrl from lpad-frontend-dev1 to lpad-frontend-test1 to correct MCP tool URL generation for token frontend links ## 3.11.7 ### Patch Changes - Update documentation across all files to reference correct SDK and MCP versions (3.11.7 and 1.7.7) - Add comprehensive Token Distribution Patterns section to CLAUDE.md - Update explainSdkUsage tool to show v3.11.7 ## 3.11.6 ### Patch Changes - Fix TypeScript declaration file output structure. The tsconfig.json `rootDir` was incorrectly set to "." instead of "src", causing declaration files to output to `dist/src/index.d.ts` instead of `dist/index.d.ts`. Restored original working configuration with `rootDir: "src"` and added test file exclusion patterns. **Key improvements:** - Restored correct TypeScript compilation structure - Added `**/*.test.ts` and `**/*.spec.ts` to exclude patterns - Declaration files now output to correct location (`dist/index.d.ts`) - MCP server builds successfully with proper SDK type imports **Breaking change:** None - This fixes a configuration regression that was preventing proper type resolution ## 3.11.5 ### Patch Changes - Fix fetchTokenDistribution API response parsing to match actual backend structure. The API returns holder data as an array of `{owner, quantity}` objects, which is now correctly transformed to the SDK's `{address, balance, percentage}` format. **Key improvements:** - Updated type definitions to match actual API response structure - Added BigNumber.js for precision-safe percentage calculations - Added comprehensive input validation to prevent crashes from malformed data - Preserved original string balance values to avoid precision loss - Enhanced JSDoc documentation with calculation formulas **Breaking change:** None - This is a bug fix that makes the method work correctly ## 3.11.4 ### Patch Changes - Eliminate all type assertions (46 total) for complete type safety - Fixed CommentService address type assertion - Exported WalletProvider interface from SignatureService - Fixed BundleService type assertions (walletProvider, error response, DTO signing) - Added getPrivateKey() public accessor to SignatureAuth - Fixed HTTP client private property access - Fixed LaunchpadSDK cache access with public API methods - Fixed multipart test environment detection with proper interfaces All `as any` and unnecessary `as unknown` casts have been replaced with proper type-safe patterns. ## 3.11.3 ### Patch Changes - Fix demo script failures caused by missing tokenName field in poolDetails response. **Root Causes:** - GalaChainService response transformation broke property access after Phase 2 type safety changes - fetchPoolDetails didn't include tokenName field that demo code expects **Changes:** - Add tokenName field to fetchPoolDetails return value for convenience - Fix GalaChainService response transformation to preserve structure using type assertion patterns - Maintain type safety throughout with proper TypeScript patterns **Impact:** - Resolves 9 failing demo scenarios with "Token name is required" validation errors - All calculation methods (calculateBuyAmountLocal, calculateSellAmountLocal, calculateBuyAmount) now work correctly - Demo script runs without validation errors ## 3.11.2 ### Patch Changes - chore: Remove temporary debug logging from cache warming investigation ## 3.11.0 - 2025-10-11 ### Added - **Auto-pagination for pool queries** - Fetch all available pools with zero configuration - `fetchAllPools()` - Convenience method that automatically paginates through all results - Three pagination modes: single-page (≤20), multi-page (>20), infinite (limit=0) - Concurrent fetching with up to 5 parallel requests (controlled by `MAX_CONCURRENT_POOL_FETCHES`) - Automatic pool total detection and dynamic batch allocation - Zero breaking changes - existing `fetchPools()` behavior unchanged - Available across all layers: `LaunchpadAPI`, `PoolService`, and `LaunchpadSDK` - **Performance optimization** - 5x faster for large pool queries - Concurrent request batching reduces wait time from ~5s (sequential) to ~1s (parallel) for 100+ pools - Configurable concurrency via `MAX_CONCURRENT_POOL_FETCHES` constant (default: 5) - Automatic cache warming for token metadata - Efficient memory usage with streaming results ### Benefits -**Zero configuration** - One method call fetches all pools -**5x performance improvement** - Concurrent fetching with configurable batch size -**Flexible modes** - Single, multi-page, or infinite pagination -**Backward compatible** - No breaking changes to existing code -**Production ready** - Comprehensive tests with 100% coverage -**Framework agnostic** - Works in Node.js and browser environments ### Documentation - Added auto-pagination examples to SDK README - Updated all integration guides with `fetchAllPools()` patterns - Performance benchmarks included in documentation ## 3.8.0 - 2025-10-10 ### Added - **Local bonding curve calculations** - Client-side instant price quotes without network calls - `calculateBuyAmountLocal()` - Calculate buy amounts locally using exponential bonding curve formulas - `calculateSellAmountLocal()` - Calculate sell amounts locally with reverse bonding curve fee support - `calculateBuyAmountExternal()` - Explicit wrapper for GalaChain buy calculations - `calculateSellAmountExternal()` - Explicit wrapper for GalaChain sell calculations - `BondingCurveCalculator` utility class with 4 calculation methods - `BondingCurveConstants` - All bonding curve parameters (BASE_PRICE, SCALE, fees, etc.) - Local calculations match external results with <0.01% difference - Supports per-call mode override via `calculateAmountMode` parameter - **Token graduation helper** - Convenient utility for checking pool completion status - `isTokenGraduated()` - Returns boolean indicating if token has completed bonding curve phase - Checks pool `saleStatus === 'Completed'` condition - Useful for conditional logic before graduation attempts - **Demo script** - Comprehensive trading demonstration - `npm run demo-trades` - Exercises all 4 calculation methods (buy native, buy exact, sell exact, sell native) - Creates test token for live trading - A/B comparison of local vs external calculations - Real trade execution with slippage protection - Complete workflow from token creation to final balance verification ### Fixed - **Critical bonding curve formula bug** - Fixed exponential integration limits - Changed from integrating 0→tokens to currentSupply→(currentSupply + tokens) - Previously caused mathematically impossible negative GALA costs - Formula now correctly uses: `exp((supply + tokens) * SCALE) - exp(supply * SCALE)` - All calculations now match GalaChain server results exactly ### Benefits -**Instant quotes** - No network delay for price calculations -**Offline support** - Calculate prices without internet connection -**Reduced costs** - No API rate limits or GalaChain call costs for quotes -**Perfect accuracy** - <0.01% difference from server calculations -**Flexible modes** - Use local or external calculations via `calculateAmountMode` -**Graduation utilities** - Easy pool status checking with `isTokenGraduated()` ### Documentation - Added `LOCAL_CALCULATIONS.md` - Complete bonding curve formula reference - Updated all examples with local calculation patterns - Added A/B comparison workflow documentation ## 3.7.6 - 2025-10-02 ### Documentation - **Graduation calculation clarification** - Updated CLAUDE.md with comprehensive token graduation patterns - Added "Token Graduation Patterns" section with detailed workflow examples - Clarified that `calculateBuyAmountForGraduation()` returns GALA cost, not token quantity - Added reference table showing what `amount` field represents across all calculation methods - Included real-world examples preventing misinterpretation (e.g., "1594263.419" = 1.59 million GALA) ### Benefits - ✅ Clearer understanding of bonding curve graduation mechanics - ✅ Prevents confusion between GALA cost and token quantities - ✅ Better AI agent integration with graduation workflows ## 3.7.1 ### Patch Changes - Fix memory leaks and enable incremental builds - Fix WebSocket onAny listener cleanup - Fix HTTP interceptor cleanup - Enable incremental TypeScript builds (50% faster rebuilds) - Add comprehensive performance documentation All notable changes to the Gala Launchpad SDK will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [3.7.0] - 2025-10-02 ### Changed **BREAKING CHANGE:** Peer dependencies are now required to be installed separately. - **Bundle size optimization** - Reduced from 525 KB to ~40-50 KB gzipped (90% reduction) - Externalized all major dependencies via Rollup configuration - Added 7 peer dependencies: `ethers`, `@gala-chain/api`, `@gala-chain/connect`, `socket.io-client`, `axios`, `bignumber.js`, `zod` - All peer dependencies are REQUIRED (including `socket.io-client` for transaction verification) - Updated UMD globals mapping for externalized dependencies ### Fixed - **TypeScript exports order** - Types now appear first in exports for proper resolution - **Package.json structure** - Added comprehensive `peerDependencies` field ### Migration Guide Users upgrading from 3.6.x need to install peer dependencies: ```bash 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 ``` This is a one-time setup that prevents dependency duplication and achieves the 50 KB bundle size target. ## [3.6.0] - 2025-10-02 ### Changed - **Major architectural refactoring** - LaunchpadService decomposed into specialized services - Extracted PoolService (~400 lines) - Pool queries, distribution, badges, volume data - Extracted TradeService (~150 lines) - Trade history and queries - Extracted CommentService (~200 lines) - Comments with vault resolution - Extracted UserService (~400 lines) - Profile management and token lists - Extracted ImageService (~150 lines) - Image upload operations - Extracted FaucetService (~100 lines) - Faucet transfer operations - Rewrote LaunchpadService as facade pattern (1,657 → 384 lines, 76.8% reduction) - All public methods maintained for 100% backward compatibility ### Added - **Centralized constants** - `constants/endpoints.ts` eliminates magic strings - 14 API endpoint URLs now defined in single location - Type-safe via `as const` assertion - Easier to maintain and update - **Unified query builder** - `utils/query-params.ts` consolidates 4 duplicate methods - `buildBackendQueryParams()` - Generic query parameter builder - `buildPaginationParams()` - Common pagination pattern - `buildTokenQueryParams()` - Token-specific queries - Configurable field transformations (stringification, mappings, optional fields) - Reduced from 81 lines (4 methods) to 30 lines (1 generic utility) - **Response normalizers** - `utils/response-normalizers.ts` for consistent data handling - `normalizePoolResponse()` - Handles multiple backend pool formats - `normalizeTradeResponse()` - Standardizes trade data - `normalizeTokenListResponse()` - Unifies token list formats - `normalizeCommentResponse()` - Comment data transformation - `extractPaginationMetadata()` - Pagination info extraction - `createPaginationFlags()` - hasNext/hasPrevious flag generation ### Removed - **Eliminated code duplication** - 163 lines of inline validation removed - All validation now uses centralized utilities - No functionality lost, just consolidated - **Deprecated query builders** - 4 nearly-identical methods replaced - `buildGetCommentsQueryParams``buildBackendQueryParams` - `buildTradeQueryParams``buildBackendQueryParams` - `buildTokenListQueryParams``buildBackendQueryParams` - `buildTokenHoldQueryParams``buildBackendQueryParams` ### Fixed - **TypeScript strict mode compliance** - Fixed exactOptionalPropertyTypes issues - Conditional property assignment pattern for optional fields - Type-safe field mapping in query builder - All compilation errors resolved ### Benefits -**76.8% reduction** in main service file (1,657 → 384 lines) -**100% backward compatible** - All public methods unchanged -**Single Responsibility Principle** - Each service has one clear purpose -**Improved maintainability** - Easier to locate and modify functionality -**Reduced duplication** - 244 lines eliminated (163 validation + 81 query builders) -**Better testability** - Services can be tested in isolation -**Modern patterns** - Template literals, optional chaining, nullish coalescing -**All tests passing** - 53/53 tests verified ### Architecture New service structure (facade pattern): ``` LaunchpadService (facade) ├── PoolService - Pool operations ├── TradeService - Trade history ├── CommentService - Social features ├── UserService - Profile & token lists ├── ImageService - Image uploads └── FaucetService - Faucet transfers ``` ## [3.5.2] - 2025-10-02 ### Changed - **Internal code quality improvements** - DRY refactoring to eliminate code duplication - Consolidated validation helper functions (`validateOptionalUrl`, `validatePositiveDecimalString`) - Reduced ~250 lines of duplicated validation logic - Fixed regex bug in `validateLaunchTokenData` (double-escaped pattern) - Removed legacy address format wrapper functions - No breaking changes - 100% backward compatible ### Benefits - ✅ Improved code maintainability and consistency - ✅ Reduced bundle size through code consolidation - ✅ Better validation error messages - ✅ All tests passing, zero regressions ## [3.5.1] - 2025-10-01 ### Changed - **BREAKING: Address parameter standardization** - Renamed `walletAddress` to `address` across entire SDK - Affected interfaces: `FetchGalaBalanceOptions`, `UpdateProfileData`, `UploadProfileImageOptions` - Affected methods: `fetchGalaBalance()`, `updateProfile()`, `uploadProfileImage()`, `fetchProfile()`, `retrieveGalaFromFaucet()` - All type guards and validation methods updated to use `address` parameter name - Error messages now reference `address` field instead of `walletAddress` ### Added - **Smart address parser** - New `normalizeAddressInput()` utility for automatic address format conversion - Accepts both Ethereum (`0x...`) and GalaChain (`eth|...`) formats - Automatically normalizes to GalaChain format required by backend - Eliminates manual address format conversion - Provides clear validation errors for invalid formats - Integrated into all SDK methods that accept address parameters ### Benefits - ✅ Use natural `0x...` addresses - no more manual conversion needed - ✅ Consistent parameter naming throughout SDK - always `address` - ✅ Better developer experience with automatic format handling - ✅ Clearer error messages with standardized field names ### Migration Guide ```typescript // Before (3.5.0) await sdk.fetchGalaBalance(walletAddress); await sdk.updateProfile({ walletAddress, fullName, profileImage }); await sdk.uploadProfileImage({ file, walletAddress }); // After (3.5.1) - accepts both formats! await sdk.fetchGalaBalance(address); // 'eth|...' or '0x...' await sdk.updateProfile({ address, fullName, profileImage }); await sdk.uploadProfileImage({ file, address }); ``` ## [3.5.0] - 2025-10-01 ### Added - **Multi-wallet support with privateKey override** - Execute operations from different wallets without creating new SDK instances - Added optional `privateKey` parameter to all 9 signing operations: - Trading: `buy()`, `sell()` - Token Creation: `launchToken()`, `uploadTokenImage()`, `uploadProfileImage()` - Transfers: `transferGala()`, `transferToken()` - Social & Profile: `postComment()`, `updateProfile()` - `privateKey` must be in format: `'0x' + 64 hexadecimal characters` - Enables multi-user trading bots, testing scenarios, and wallet coordination - SDK creates temporary instances with override wallet using new `createOverrideSdk()` helper method - Full validation ensures privateKey format compliance before execution - Example: `await sdk.buy({ ...options, privateKey: '0x1234...' })` uses different wallet for that operation ### Benefits - ✅ Test multi-wallet workflows without server restart - ✅ Build multi-user trading applications - ✅ Simulate different user behaviors in testing - ✅ Create automated market maker systems - ✅ Coordinate multiple wallets from single SDK instance ### Documentation - Added comprehensive multi-wallet section to SDK README with examples - Updated AI Agent Developer docs with multi-wallet patterns - Added privateKey format requirements and validation examples ## [3.3.4] - 2025-10-01 ### Fixed - **Launchpad token precision loss in trading DTOs** - Fixed critical bug truncating tokens to 8 decimals - `formatForDTO()` now accepts optional `decimals` parameter (defaults to 18) - Added `formatGalaForDTO()` helper for GALA amounts (8 decimals - GalaChain requirement) - Added `formatLaunchpadTokenForDTO()` helper for launchpad tokens (18 decimals - full precision) - Updated all BondingCurveDTOs to use context-aware formatting: - `nativeTokenQuantity` (GALA) → Uses `formatGalaForDTO()` (8 decimals) - `expectedToken` (Launchpad token) → Uses `formatLaunchpadTokenForDTO()` (18 decimals) - `tokenQuantity` (Launchpad token) → Uses `formatLaunchpadTokenForDTO()` (18 decimals) - `expectedNativeToken` (GALA) → Uses `formatGalaForDTO()` (8 decimals) - Prevents precision loss when trading high-precision launchpad tokens - GALA amounts still correctly limited to 8 decimals (GalaChain transaction requirement) - Example: Token amount `1000.123456789012345678` now preserved at full 18 decimals instead of truncated to `1000.12345679` ### Added - **Decimal Constants** - Token decimal precision constants for type-safe operations - `GALA_DECIMALS = 8` - GALA token decimal places (GalaChain standard) - `LAUNCHPAD_TOKEN_DECIMALS = 18` - Launchpad token decimal places (ERC-20 standard) - `GALA_TOKEN_CLASS_KEY` - GALA token identifier for GalaChain operations - Import: `import { GALA_DECIMALS, LAUNCHPAD_TOKEN_DECIMALS } from '@gala-chain/launchpad-sdk'` - Provides single source of truth for decimal specifications - Prevents hardcoded magic numbers across SDK ### Changed - **precision-math.ts** - Now uses `LAUNCHPAD_TOKEN_DECIMALS` constant instead of hardcoded 18 - Improves code maintainability and clarity - Self-documenting code intent ### Benefits - ✅ Full precision for launchpad tokens (18 decimals) - no more truncation - ✅ Correct precision limits for GALA (8 decimals) - prevents transaction failures - ✅ Type-safe decimal constants via const assertions - ✅ Context-aware formatting prevents precision bugs - ✅ Single source of truth for token specifications ## [3.3.3] - 2025-10-01 ### Fixed - **fetchLaunchpadTokenSpotPrice calculation** - Fixed critical precision and logic bugs - Removed incorrect division by 1e18 (buyResult.amount is already in decimal format, not wei) - Switched from `Number()` to `BigNumber.js` for precise calculations - Fixes spot prices being off by factor of ~1e18 (showing trillions instead of micro-cents) - Prevents precision loss for tokens with many decimal places - Example: ANIME token now shows $0.00000004 instead of $20,147,102,880,354 ## [3.3.2] - 2025-09-30 ### Added - **Public API exports** - Utility types now properly exported - Exported `TokenClassKey` - GalaChain token identifier interface - Exported `TokenInstanceKey` - Token instance identifier (extends TokenClassKey) - Exported `TokenId` - Flexible token identifier type (string | TokenClassKey | TokenInstanceKey) - These types are used by `resolveTokenClassKey()` and GalaChain operations ### Documentation - Clarified that `resolveTokenClassKey()` and `resolveVaultAddress()` are part of public SDK API - Both utility methods are now properly exposed for downstream consumers (e.g., MCP server) ## [3.3.1] - 2025-09-30 ### Fixed - **fetchPoolDetails response** - Extract clean PoolDetailsData from wrapper - Previously returned `InternalFetchPoolDetailsResponse` with `{ Status: 1, Data: {...} }` - Now returns just the `Data` field for cleaner consumption - Matches JSDoc documentation: `Promise<PoolDetailsData>` - Breaking for consumers expecting Status wrapper (unlikely, as JSDoc never documented it) ## [3.3.0] - 2025-09-30 ### Added - **Constants Export** - Type-safe constants for trading and pool operations - `TRADING_TYPES = { NATIVE: 'native', EXACT: 'exact' } as const` - `POOL_TYPES = { RECENT: 'recent', POPULAR: 'popular' } as const` - Provides single source of truth for type values - Prevents type mismatches between SDK and downstream consumers (e.g., MCP server) - Import: `import { TRADING_TYPES, POOL_TYPES } from '@gala-chain/launchpad-sdk'` ### Benefits - Type safety via TypeScript const assertions - Auto-completion in IDEs - Prevents hardcoded string typos - Single source of truth pattern for SDK integrations ## [3.2.0] - 2025-09-30 ### Added - **getUrlByTokenName() method** - Generate frontend URLs for token pages - Environment-based URL generation (PROD/STAGE) - Custom frontend URL override support via `launchpadFrontendUrl` config - Returns format: `{baseUrl}/buy-sell/{tokenName}` - Example: `sdk.getUrlByTokenName('mytoken')` `https://lpad-frontend-prod1.defi.gala.com/buy-sell/mytoken` ### Configuration - Added `launchpadFrontendUrl` to EnvironmentConfig - PROD: `https://lpad-frontend-prod1.defi.gala.com` - STAGE: `https://lpad-frontend-test1.defi.gala.com` - Supports custom URL override in LaunchpadSDKConfig ### Documentation - Added comprehensive JSDoc documentation for getUrlByTokenName - Updated examples and README with URL generation use cases ## [0.4.3] - 2024-09-24 ### Documentation Update - Updated all version references to v0.4.3 across README, documentation files, and source code - Fixed npm README display issue with consistent version numbers ## [0.4.0] - 2024-01-24 ### First Public Release A comprehensive TypeScript SDK for the Gala Launchpad Backend API, providing type-safe authentication, trading, and real-time features for DeFi applications. ### Core Features - **Flat API Architecture**: All methods directly accessible on SDK root for simplicity - Pool management, trading, user operations, and comments all on `sdk.methodName()` - No nested controllers or complex navigation patterns - **Wallet Creation with Auto-Detection**: Smart `createWallet()` function - Automatically detects private key vs mnemonic input format - Supports 12-word and 24-word mnemonics - Handles 64-character hex private keys (with or without 0x prefix) - Generates random wallets when no input provided - **SDK Factory Functions**: Simplified initialization - `createLaunchpadSDK()` - Main factory with wallet auto-detection - `createTestLaunchpadSDK()` - Test-optimized configuration - **Input Validation**: `validateWalletInput()` for format validation - **Type-Safe Authentication**: Ethereum wallet-based authentication with automatic signature generation - **Comprehensive Trading**: Buy/sell tokens with slippage protection via GalaChain - **Real-time Features**: WebSocket support for live data feeds - **Multi-Environment Support**: Production, staging, and custom backend URLs ### Technical Implementation - **Complete API Coverage**: 22/22 backend endpoints working - **TypeScript-First**: Full type safety with comprehensive type definitions - **Multi-Target**: Compatible with Node.js and browser environments - **Framework Integration**: React hooks and Vue composables available - **High Test Coverage**: 132 tests passing with 80%+ line coverage - **Production Ready**: Bundle size under 50KB, comprehensive error handling - **Security**: Input validation, secure defaults, no credential exposure