Package Exports
- @gala-chain/launchpad-sdk
Readme
Gala Launchpad SDK v3.0.0
A comprehensive TypeScript SDK for the Gala Launchpad Backend API, providing type-safe authentication, trading, and real-time features for DeFi applications.
โจ New in v3.0.0: Production-ready release with service-based architecture, AgentConfig utilities, and clean result types - zero breaking changes!
๐ Features
Clean Result Types with No Wrapper Overhead:
- Direct Result Access: Get clean, typed results without wrapper objects
- Semantic Type Conversion: Dates as Date objects, numbers as numbers, strings for precision
- Comprehensive Type Safety: Full TypeScript support with precise result interfaces
- Zero Wrapper Overhead: No more
result.data.success- direct property access - Options Object Pattern: All methods with 2+ parameters use clean options objects
Developer Experience
import { createLaunchpadSDK, createWallet } from '@gala-chain/launchpad-sdk';
// Auto-detect wallet format and create SDK
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic' // Auto-detects format!
});
// Direct result access - no wrapper objects!
const pools = await sdk.fetchPools({ type: 'recent' });
console.log(`Found ${pools.total} pools`); // Direct property access
console.log(`Page ${pools.page} of ${pools.totalPages}`); // Clean pagination
console.log(`Has next: ${pools.hasNext}`); // Boolean convenience properties
// Clean typed results everywhere
const balance = await sdk.fetchGalaBalance();
console.log(`Balance: ${balance.balance} GALA`); // Direct balance access
console.log(`Last updated: ${balance.lastUpdated.toISOString()}`); // Date object๐ Clean API Architecture
Direct result access with no wrapper overhead:
// Before: Wrapper response types
const result = await sdk.fetchPools({ type: 'recent' });
if (result.success) {
console.log(result.data.pools); // Nested access
}
// After: Clean direct results
const pools = await sdk.fetchPools({ type: 'recent' });
console.log(pools.pools); // Direct access
console.log(pools.total); // Immediate pagination info
console.log(pools.hasNext); // Computed convenience properties๐ Key Features
- Type-Safe API Client: Full TypeScript support with comprehensive type definitions
- Clean Result Types: Direct property access without wrapper objects
- Options Object Pattern: All multi-parameter methods use clean options objects
- Signature Authentication: Ethereum wallet-based authentication with automatic signature generation
- Helper Functions: Auto-detecting wallet creation and SDK factory functions
- Pool Management: Create, fetch, and check token pools on the launchpad
- Token Trading: Buy and sell tokens with slippage protection via GalaChain
- Token Transfers: Transfer GALA and launchpad tokens between wallets with EIP-712 signatures
- User Operations: Portfolio management, token balances, and account management
- Comment System: Post and retrieve comments on token pools
- Comprehensive Validation: Input validation and error handling for all operations
- Multi-Environment Support: Production, staging, and custom backend URLs
๐ฆ Installation
npm install @gala-chain/launchpad-sdk@^3.0.0Or with yarn:
yarn add @gala-chain/launchpad-sdk@^3.0.0๐ Quick Start
Using Helper Functions (Recommended)
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Auto-detecting SDK creation (easiest method)
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic' // Auto-detects format!
});
// Clean, direct result access - All methods use options objects
// Pool Management - Direct result properties
const pools = await sdk.fetchPools({ type: 'recent', limit: 10 });
console.log(`Found ${pools.total} pools across ${pools.totalPages} pages`);
console.log(`Current page: ${pools.page}, Has next: ${pools.hasNext}`);
const badges = await sdk.fetchTokenBadges('dragnrkti');
console.log(`Volume badges: ${badges.volumeBadges.length}`);
console.log(`Engagement badges: ${badges.engagementBadges.length}`);
const details = await sdk.fetchPoolDetails('dragnrkti');
console.log(`Sale status: ${details.saleStatus}`);
console.log(`Native token quantity: ${details.nativeTokenQuantity}`);
// Price Calculations - Direct amount access
const buyAmount = await sdk.calculateBuyAmount({
tokenName: 'dragnrkti',
amount: '1000000000000000000', // 1 GALA
type: 'native'
});
console.log(`Buy amount: ${buyAmount.amount}`);
console.log(`Transaction fee: ${buyAmount.transactionFee}`);
// Trading Operations - Required expectedAmount and slippageToleranceFactor
const buyResult = await sdk.buy({
tokenName: 'dragnrkti',
amount: '1000000000000000000',
type: 'native',
expectedAmount: buyAmount.amount, // Required: from calculation
slippageToleranceFactor: 0.05 // Required: decimal format (5% slippage)
});
console.log(`Transaction ID: ${buyResult.transactionId}`);
// Data & Analytics - Clean pagination
const trades = await sdk.fetchTrades({ tokenName: 'dragnrkti' });
console.log(`Found ${trades.total} trades`);
console.log(`Page ${trades.page} of ${trades.totalPages}`);
trades.trades.forEach(trade => {
console.log(`Trade: ${trade.tradeType} ${trade.tokenAmount} at ${trade.createdAt.toISOString()}`);
});
const comments = await sdk.fetchComments({ tokenName: 'dragnrkti' });
console.log(`${comments.total} comments found`);
// User Operations - Direct balance access
const galaBalance = await sdk.fetchGalaBalance();
console.log(`GALA Balance: ${galaBalance.balance}`);
console.log(`Last updated: ${galaBalance.lastUpdated.toISOString()}`);
const tokenBalance = await sdk.fetchTokenBalance({
tokenName: 'dragnrkti',
walletAddress: sdk.getAddress()
});
console.log(`Token balance: ${tokenBalance.quantity}`);
console.log(`USD value: $${tokenBalance.holdingPriceUsd}`);
// Profile - Direct user data
const profile = await sdk.fetchProfile();
console.log(`Profile name: ${profile.fullName || 'Not set'}`);Manual SDK Creation (Alternative)
import { Wallet } from 'ethers';
import { LaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Create wallet manually
const wallet = new Wallet(process.env.PRIVATE_KEY);
// Initialize SDK
const sdk = new LaunchpadSDK({
wallet: wallet,
baseUrl: 'https://lpad-backend-dev1.defi.gala.com',
timeout: 30000,
debug: false
});
// Same clean API available
const pools = await sdk.fetchPools({ type: 'recent' });
console.log(`${pools.total} pools found`);๐ฏ Complete Example: Trading Flow with Clean Results
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// 1. Create SDK with auto-detection
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
// 2. Check available pools - direct access to results
const pools = await sdk.fetchPools({
type: 'recent',
limit: 10
});
console.log(`Found ${pools.total} pools across ${pools.totalPages} pages`);
pools.pools.forEach(pool => {
console.log(`Pool: ${pool.tokenName} created at ${pool.createdAt}`);
});
// 3. Get price quote - direct amount access
const quote = await sdk.calculateBuyAmount({
tokenName: 'tinyevil',
amount: '100',
type: 'native'
});
console.log(`Buying 100 GALA worth will get you: ${quote.amount} TINYEVIL`);
console.log(`Transaction fee: ${quote.transactionFee} GALA`);
console.log(`Reverse bonding curve fee: ${quote.reverseBondingCurveFee} GALA`);
// 4. Execute trade with slippage protection - requires expectedAmount
const buyResult = await sdk.buy({
tokenName: 'tinyevil',
amount: '100',
type: 'native',
expectedAmount: quote.amount, // Required: from calculation above
slippageToleranceFactor: 0.05 // Required: decimal format for 5% slippage
});
console.log(`Transaction submitted: ${buyResult.transactionId}`);
// 5. Check trade history - clean pagination
const trades = await sdk.fetchTrades({ tokenName: 'tinyevil' });
console.log(`Found ${trades.total} trades on page ${trades.page}`);
console.log(`Has more pages: ${trades.hasNext}`);
trades.trades.forEach(trade => {
console.log(`${trade.tradeType}: ${trade.tokenAmount} at ${trade.createdAt.toISOString()}`);
});
// 6. Post a comment about your trade
const comment = await sdk.postComment({
tokenName: 'tinyevil',
content: 'Just bought some tokens! Great project!'
});
console.log(`Comment posted with ID: ${comment.id}`);
// 7. Check your balance - direct balance access
const galaBalance = await sdk.fetchGalaBalance();
console.log(`GALA Balance: ${galaBalance.balance}`);
console.log(`Decimals: ${galaBalance.decimals}`);
console.log(`Last updated: ${galaBalance.lastUpdated.toISOString()}`);
const tokenBalance = await sdk.fetchTokenBalance({
tokenName: 'tinyevil',
walletAddress: sdk.getAddress()
});
console.log(`TINYEVIL Balance: ${tokenBalance.quantity}`);
console.log(`USD Value: $${tokenBalance.holdingPriceUsd}`);
console.log(`GALA Value: ${tokenBalance.holdingPriceGala} GALA`);
console.log(`Finalized: ${tokenBalance.isFinalized}`);๐ธ Transfer Operations
Transfer GALA and launchpad tokens between wallets with EIP-712 signatures:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
// Transfer GALA tokens - direct result access
const galaTransfer = await sdk.transferGala({
recipientAddress: 'eth|1234567890abcdef1234567890abcdef12345678', // or 0x format
amount: '1000000000000000000', // 1 GALA in wei
uniqueKey: 'galaconnect-operation-my-transfer-123' // Optional for idempotency
});
console.log(`GALA Transfer ID: ${galaTransfer.transactionId}`);
console.log(`Status: ${galaTransfer.status}`);
// Transfer launchpad tokens - direct result access
const tokenTransfer = await sdk.transferToken({
to: '0x9876543210fedcba9876543210fedcba98765432', // or eth| format
tokenName: 'tinyevil',
amount: '1000000', // Token amount in smallest unit
uniqueKey: 'galaconnect-operation-token-transfer-456' // Optional for idempotency
});
console.log(`Token Transfer ID: ${tokenTransfer.transactionId}`);
console.log(`Status: ${tokenTransfer.status}`);Transfer Features
- EIP-712 Signatures: Secure blockchain transactions
- Address Format Handling: Supports both
0xandeth|formats - Idempotency: Optional unique keys prevent duplicate transfers (must use
galaswap-operation-orgalaconnect-operation-prefix) - Comprehensive Validation: Amount limits, address formats, token names, unique key formats
- GalaChain Integration: Direct transfers via GalaChain gateway
- Error Handling: Detailed error types for different failure scenarios
๐ฏ Available Methods & Result Types
Fetch Operations
// Pool Management
fetchPools(options?): Promise<PoolsResult>
// Returns: { pools, page, limit, total, totalPages, hasNext, hasPrevious }
fetchTokenDistribution(tokenName): Promise<TokenDistributionResult>
// Returns: { holders, totalSupply, totalHolders, lastUpdated }
fetchTokenBadges(tokenName): Promise<TokenBadgesResult>
// Returns: { volumeBadges, engagementBadges }
fetchPoolDetails(tokenName): Promise<PoolDetailsData>
// Returns: { basePrice, maxSupply, saleStatus, nativeTokenQuantity, ... }
fetchVolumeData(options): Promise<GraphDataResult>
// Returns: { dataPoints }
// Trade & User Data
fetchTrades(options): Promise<TradesResult>
// Returns: { trades, page, limit, total, totalPages, hasNext, hasPrevious }
fetchGalaBalance(walletAddress?): Promise<GalaBalanceInfo>
// Returns: { userAddress, balance, decimals, lastUpdated }
fetchTokenBalance(options): Promise<TokenBalanceInfo>
// Returns: { quantity, holdingPriceUsd, holdingPriceGala, isFinalized, ... }
fetchComments(options): Promise<CommentsResult>
// Returns: { comments, page, limit, total, totalPages, hasNext, hasPrevious }
fetchProfile(walletAddress?): Promise<UserProfile>
// Returns: { fullName, profileImage, walletAddress, ... }Calculate Operations
// Price Calculations
calculateBuyAmount(options): Promise<AmountCalculationResult>
// Returns: { amount, reverseBondingCurveFee, transactionFee }
calculateSellAmount(options): Promise<AmountCalculationResult>
// Returns: { amount, reverseBondingCurveFee, transactionFee }
calculateInitialBuyAmount(options): Promise<AmountCalculationResult>
// Returns: { amount, reverseBondingCurveFee, transactionFee }Trading Operations
// Buy/Sell Tokens
buy(options): Promise<TransactionResult>
// Options: { tokenName, amount, type, expectedAmount, slippageToleranceFactor }
// Returns: { transactionId, status, ... }
sell(options): Promise<TransactionResult>
// Options: { tokenName, amount, type, expectedAmount, slippageToleranceFactor }
// Returns: { transactionId, status, ... }Content Operations
// Comments & Content
postComment(options): Promise<CommentResult>
// Returns: { id, content, createdAt, ... }
// Token Creation & Management
launchToken(data): Promise<LaunchTokenResult>
// Returns: { transactionId, status, ... }
uploadTokenImage(options): Promise<ImageUploadResult>
// Returns: { imageUrl, success, ... }
// Profile Management
updateProfile(data): Promise<ProfileUpdateResult>
// Returns: { success, data, ... }
uploadProfileImage(options): Promise<ImageUploadResult>
// Returns: { imageUrl, success, ... }Validation & Utilities
isTokenNameAvailable(tokenName: string): Promise<boolean>isTokenSymbolAvailable(symbol: string): Promise<boolean>getAddress(): string- Get backend format address (eth|...)getEthereumAddress(): string- Get Ethereum format address (0x...)resolveVaultAddress(tokenName: string): Promise<string>cleanup(): void- Cleanup resources
๐ง Helper Functions
Wallet Creation
import { createWallet, validateWalletInput } from '@gala-chain/launchpad-sdk';
// Auto-detect format and create wallet
const wallet = createWallet('private-key-or-24-word-mnemonic');
const randomWallet = createWallet(); // Generate random wallet
// Validate input format without creating wallet
const isValid = validateWalletInput('0x1234...'); // booleanSDK Factory Functions
import { createLaunchpadSDK, createTestLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Main factory with auto-detection
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic',
config: {
baseUrl: 'https://lpad-backend-dev1.defi.gala.com',
debug: true
}
});
// Test-optimized SDK
const testSDK = createTestLaunchpadSDK({
wallet: 'test-private-key'
});๐ง Configuration
interface LaunchpadSDKConfig {
wallet: Wallet; // ethers.js Wallet instance
baseUrl?: string; // Backend URL (default: dev environment)
galaChainBaseUrl?: string; // GalaChain gateway URL
bundleBaseUrl?: string; // Bundle service URL
webSocketUrl?: string; // WebSocket URL for monitoring
timeout?: number; // Request timeout (default: 30000ms)
debug?: boolean; // Enable debug logging
maxRetries?: number; // Retry attempts (default: 3)
retryDelay?: number; // Retry delay (default: 1000ms)
}๐งช Testing
# Run all tests
npm test
# Run integration tests (requires environment setup)
npm run test:integration
# Run type checking
npm run typecheck
# Run linting
npm run lint๐ Documentation
- SDK Method Reference - Complete flat API reference
- Clean Result Types Migration Guide - Migration guide for clean result types
- Service Architecture Migration Guide - Guide for v3.1.0 service-based architecture
- API Documentation - Detailed API documentation
- Examples - Code examples and demos
๐๏ธ Architecture (v3.0.0+)
The SDK uses a service-based architecture with backend-aligned services:
Backend-Aligned Services
// Each service maps 1:1 to a specific backend
import {
LaunchpadService, // โ launchpad-backend (pools, trades, comments, profiles)
GalaChainService, // โ galachain-gateway (balances, transfers, pool details)
DexService, // โ dex-api (spot prices)
BundleService, // โ bundle-backend (transaction bundling, trading)
WebSocketService // โ WebSocket endpoint (real-time monitoring)
} from '@gala-chain/launchpad-sdk';Service Responsibilities
LaunchpadService - Launchpad Backend Operations
- Pool management (fetch, create, check)
- Trade history
- Comments (post, fetch)
- User profiles
- Token images
- Faucet operations
GalaChainService - Blockchain Operations
- GALA balance queries
- Token balance queries
- Token transfers (GALA & launchpad tokens)
- Pool details from bonding curve contracts
- Token resolution
DexService - Price Queries
- Spot price fetching
- Multi-token price queries
BundleService - Transaction Bundling
- Buy token operations
- Sell token operations
- Slippage protection
- Transaction bundling
WebSocketService - Real-time Features
- Transaction monitoring
- Status updates
- Connection management
Benefits of Service Architecture
โ Clear Separation: Each service has a single backend responsibility โ Type Safety: Full TypeScript support across all services โ Testability: Services can be tested independently โ Maintainability: Easy to locate and update backend-specific logic โ Zero Breaking Changes: Public API remains unchanged (v3.0.0 is fully backward compatible)
๐ค AI Agent Integration
The SDK includes comprehensive utilities for AI agent development:
import { AgentConfig } from '@gala-chain/launchpad-sdk';
// Quick setup with intelligent defaults
const { sdk, validation } = await AgentConfig.quickSetup({
environment: 'development',
autoValidate: true
});
console.log(`Ready: ${validation.ready}`);
console.log(`Can trade: ${validation.capabilities.canTrade}`);For comprehensive AI agent integration, see:
- AI Agent Integration Guide - Complete guide for agent development
- MCP Tool Specification - Blueprint for MCP server creation
- Agent Examples - Working code examples
๐ฏ Clean Result Types Architecture
Key Benefits
โ
Direct Property Access: No more result.data.success chains
โ
Type Safety: Full TypeScript IntelliSense for all result properties
โ
Semantic Types: Dates as Date objects, numbers as numbers
โ
Computed Properties: hasNext, hasPrevious for convenience
โ
Zero Wrapper Overhead: Clean, direct access to all result data
โ
Options Object Pattern: All multi-parameter methods use options objects
Result Type Examples
// Pool results with pagination
interface PoolsResult {
pools: PoolData[]; // Direct pool array
page: number; // Current page
total: number; // Total items
hasNext: boolean; // Computed convenience
// ... more properties
}
// Token balance with typed values
interface TokenBalanceInfo {
quantity: string; // Token amount (string for precision)
holdingPriceUsd: number; // USD value (number for math)
lastUpdated: Date; // Date object (not string)
isFinalized: boolean; // Boolean flag
// ... more properties
}
// Trading results
interface AmountCalculationResult {
amount: string; // Calculated amount
transactionFee: string; // Fee breakdown
reverseBondingCurveFee: string; // RBC fee
// Direct access to all calculation data
}๐ Environment URLs
- Development:
https://lpad-backend-dev1.defi.gala.com - Production:
https://lpad-backend-prod1.defi.gala.com
๐ License
MIT License - see LICENSE file for details.
๐ค Contributing
Please read CONTRIBUTING.md for guidelines on contributing to this project.
๐ Support
- GitHub Issues: Report bugs and request features
- Documentation: Full documentation and examples
- API Status: All 22/22 endpoints working โ
Built with โค๏ธ for the Gala ecosystem