@gala-chain/launchpad-sdk
v5.1.1
Published
TypeScript SDK for Gala Launchpad Backend API - 273 public methods supporting optional wallet (read-only and full-access modes). Production-ready DeFi token launchpad integration with AgentConfig setup, GalaChain trading, GSwap DEX integration, price hist
Readme
Gala Launchpad SDK
Version: 5.0.4-beta.46 (Latest)
A comprehensive TypeScript SDK for the Gala Launchpad Backend API, providing type-safe authentication, trading, and real-time features for DeFi applications.
⚠️ BREAKING CHANGE (v3.33.0+): Token format parsing now ONLY accepts delimited formats (
GALA|Unit|none|noneorGALA$Unit$none$none). Plain token strings ('GALA','GUSDC') are permanently rejected for security. See Migration Guide below.
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
- Auto-Pagination: Automatic multi-page fetching with configurable concurrency
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 objectClean API Architecture
Direct result access with no wrapper overhead:
// Get pools with direct property access
const pools = await sdk.fetchPools({ type: 'recent' });
console.log(pools.items); // Direct access to pool array
console.log(pools.meta.total); // Immediate pagination info
console.log(pools.meta.page < pools.meta.totalPages); // Has more pagesKey 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
- Auto-Pagination: Automatic multi-page fetching for large result sets
- 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
- DEX Pool Discovery: Discover and explore GalaSwap liquidity pools with filtering, sorting, and pagination
- DEX Trading: Real-time token swaps on GalaSwap DEX with quote generation and slippage protection
- Liquidity Management: Manage liquidity positions on GalaSwap (add, remove, collect fees) with filtering and organization utilities
- 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
- Price History: Fetch historical price data for DEX tokens with pagination (Node.js only)
- Cross-Chain Bridging: Transfer tokens between GalaChain, Ethereum, and Solana with fee estimation
- External Wallet Balances: Query Ethereum and Solana wallet balances (single-token or full portfolio)
- Live Streaming: Start/stop streams, manage recordings and simulcast targets for token pools (v5.1.0+)
- Stream Chat: Real-time chat messaging via REST and WebSocket with admin controls (v5.1.0+)
- Events Tracking: SDK-side event batching with automatic persistence and overseer monitoring (v8.2.0+)
- Global Feed: Unified real-time event stream for token updates and site configuration changes (v7.0.0+)
- Overseer System: Global platform oversight with CCTV dashboard, invite management, platform summary, and cache management (v5.9.0+)
- Moderator System: Token-scoped moderation with magic link invites (v5.7.0+)
- Content Flags: Report and manage flagged content with two-tier review system (v5.8.0+)
- User Bans: Per-token and global user banning with active user tracking (v5.5.0+)
- Comprehensive Validation: Input validation and error handling for all operations
- Multi-Environment Support: Production, staging, and custom backend URLs
Installation
NPM
npm install @gala-chain/launchpad-sdkYarn
yarn add @gala-chain/launchpad-sdkPeer Dependencies
This SDK requires the following peer dependencies to be installed:
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.76Or with yarn:
yarn add 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.76All peer dependencies are required - this includes socket.io-client which is needed for transaction verification via WebSocket.
Module Formats
The SDK is distributed in three module formats to support both modern and legacy projects:
ESM (ES Modules) - Primary Format
For modern bundlers and Node.js 16+:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});When to use:
- ✅ React, Vue, Svelte, Angular applications
- ✅ Next.js, Nuxt, SvelteKit
- ✅ Vite, Webpack, esbuild bundlers
- ✅ Modern Node.js projects with
"type": "module"
CommonJS - Legacy Support
For CommonJS projects and older Node.js environments:
const { createLaunchpadSDK } = require('@gala-chain/launchpad-sdk');
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});When to use:
- ✅ Legacy Node.js projects with CommonJS modules
- ✅ Older tooling that doesn't support ESM
- ✅ Express.js, Nest.js (CommonJS mode)
- ✅ Projects without build tools
UMD (Universal Module Definition) - Browser Legacy
For browser globals and legacy environments:
<script src="node_modules/@gala-chain/launchpad-sdk/dist/index.js"></script>
<script>
const sdk = window.GalaLaunchpadSDK.createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
</script>When to use:
- ✅ Direct browser
<script>tags - ✅ Older browser environments
- ✅ CDN delivery
Module Resolution
Node.js automatically selects the correct module format based on your project:
| Project Type | Method | Format Used | File |
|---|---|---|---|
| ESM Module | import | ESM | dist/index.esm.js |
| CommonJS | require() | CommonJS | dist/index.cjs.js |
| Legacy Tools | Direct Include | UMD | dist/index.js |
No configuration needed - Node.js and bundlers automatically select the optimal format via the package exports field!
Wallet Configuration Modes
The SDK supports two operational modes with optional wallet configuration:
Full-Access Mode (with Wallet)
For executing trades, creating tokens, and managing funds:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Initialize with wallet - enables signing operations
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
// Now you can execute trades
const result = await sdk.buy({
tokenName: 'anime',
amount: '100',
type: 'native',
slippageToleranceFactor: 0.01
});Capabilities:
- ✅ Execute token trades (buy/sell)
- ✅ Create new tokens
- ✅ Transfer GALA and tokens
- ✅ Update user profile
- ✅ Post comments
- ✅ All read operations (fetch pools, prices, etc.)
Read-Only Mode (without Wallet)
For querying data without wallet authentication:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Initialize without wallet - read-only operations only
const sdk = createLaunchpadSDK({});
// Query operations work fine
const pools = await sdk.fetchPools({ type: 'recent' });
const prices = await sdk.fetchTokenSpotPrice('anime');
const balance = await sdk.fetchGalaBalance();Capabilities:
- ✅ Fetch token pools and details
- ✅ Get real-time prices and price history
- ✅ Check balances and portfolio
- ✅ Browse comments and token information
- ✅ Explore token metadata and distributions
- ❌ Cannot: Execute trades, create tokens, transfer funds (require signatures)
Dynamic Wallet Configuration
Upgrade from read-only to full-access mode at runtime:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Start in read-only mode
const sdk = createLaunchpadSDK({});
console.log(sdk.hasWallet()); // false
// Later, upgrade to full-access
sdk.setWallet('your-private-key-or-mnemonic');
console.log(sdk.hasWallet()); // true
// Now signing operations work
const result = await sdk.buy({
tokenName: 'anime',
amount: '100',
type: 'native',
slippageToleranceFactor: 0.01
});Wallet Management Methods:
hasWallet()- Check if wallet is configuredgetWallet()- Retrieve current wallet instancesetWallet(wallet)- Configure wallet for signing operationsvalidateWallet()- Type guard that throws if wallet not present
How to Connect Your Wallet
The SDK ships a complete wallet provider system with EIP-6963 browser detection, 4 provider types, and React hooks. Here's how to go from zero to connected.
Node.js / CLI (PrivateKeyProvider)
import { PrivateKeyProvider } from '@gala-chain/launchpad-sdk/wallet';
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const provider = new PrivateKeyProvider('0xYOUR_PRIVATE_KEY');
const sdk = createLaunchpadSDK({ walletProvider: provider });
// Ready — sign messages, execute trades, transfer tokens
const address = await provider.getAddress(); // 0x checksummed
const galaAddr = await provider.getGalaAddress(); // eth|{40-hex}
const sig = await provider.signMessage('Hello');Browser (React — 3 steps)
Step 1: Wrap your app
import { WalletProvider } from '@gala-chain/launchpad-sdk/react';
function App() {
return (
<WalletProvider autoDetect>
<YourApp />
</WalletProvider>
);
}Step 2: Show detected wallets and connect
import { useWalletDetection, useWalletConnection } from '@gala-chain/launchpad-sdk/react';
function WalletPicker() {
const { wallets, isDetecting } = useWalletDetection();
const { connectDetected, isConnecting } = useWalletConnection();
if (isDetecting) return <p>Scanning for wallets...</p>;
return (
<div>
{wallets.map(wallet => (
<button key={wallet.id} onClick={() => connectDetected(wallet)} disabled={isConnecting}>
<img src={wallet.icon} alt="" width={24} /> {wallet.name}
</button>
))}
</div>
);
}Step 3: Use wallet state
import { useWallet, useGalaAddress, useWalletProvider } from '@gala-chain/launchpad-sdk/react';
function Dashboard() {
const { isConnected, address } = useWallet();
const galaAddress = useGalaAddress();
const provider = useWalletProvider();
if (!isConnected) return <WalletPicker />;
return (
<div>
<p>ETH: {address}</p>
<p>GalaChain: {galaAddress}</p>
<button onClick={async () => {
const sig = await provider.signMessage('Prove ownership');
console.log('Signature:', sig);
}}>
Sign Message
</button>
</div>
);
}Browser (Vanilla — no React)
import { detectWallets, ExternalWalletProvider, KNOWN_WALLET_RDNS } from '@gala-chain/launchpad-sdk/wallet';
// Detect installed wallets (EIP-6963, 500ms scan)
const { wallets, primary, hasWallets } = await detectWallets();
if (hasWallets) {
// Connect to the first detected wallet
const provider = new ExternalWalletProvider(primary.provider);
const address = await provider.connect(); // triggers wallet popup
console.log('Connected:', address);
// Sign a message
const sig = await provider.signMessage('Hello from Launchpad');
// Sign EIP-712 typed data (required for GalaChain transactions)
const typedSig = await provider.signTypedData(
{ name: 'GalaChain', version: '1' },
{ Transfer: [{ name: 'to', type: 'string' }, { name: 'amount', type: 'string' }] },
{ to: 'eth|0000000000000000000000000000000000000001', amount: '100' }
);
// Disconnect
await provider.disconnect();
}
// Or check for a specific wallet
import { getWalletByRdns } from '@gala-chain/launchpad-sdk/wallet';
const metamask = await getWalletByRdns(KNOWN_WALLET_RDNS.METAMASK);
if (metamask) {
const provider = new ExternalWalletProvider(metamask.provider);
await provider.connect();
}Supported Wallets
EIP-6963 auto-detects any compatible wallet. Known identifiers:
| Wallet | RDNS | Constant |
|--------|------|----------|
| MetaMask | io.metamask | KNOWN_WALLET_RDNS.METAMASK |
| Coinbase Wallet | com.coinbase.wallet | KNOWN_WALLET_RDNS.COINBASE |
| Trust Wallet | com.trustwallet.app | KNOWN_WALLET_RDNS.TRUST_WALLET |
| Phantom | app.phantom | KNOWN_WALLET_RDNS.PHANTOM |
| Rainbow | me.rainbow | KNOWN_WALLET_RDNS.RAINBOW |
| OKX Wallet | com.okex.wallet | KNOWN_WALLET_RDNS.OKX |
| Rabby | io.rabby | KNOWN_WALLET_RDNS.RABBY |
| Brave Wallet | com.brave.wallet | KNOWN_WALLET_RDNS.BRAVE |
| Frame | sh.frame | KNOWN_WALLET_RDNS.FRAME |
| Ledger | com.ledger | KNOWN_WALLET_RDNS.LEDGER |
| Zerion | io.zerion.wallet | KNOWN_WALLET_RDNS.ZERION |
| Gala Wallet | com.gala.wallet | KNOWN_WALLET_RDNS.GALA |
Falls back to window.ethereum if no EIP-6963 announcements received.
React Hooks Reference
| Hook | Returns |
|------|---------|
| useWallet() | { isConnected, address, galaAddress, provider, error } |
| useWalletAddress() | string \| null (0x format) |
| useGalaAddress() | string \| null (eth| format) |
| useWalletProvider() | WalletProvider \| null |
| useIsWalletConnected() | boolean |
| useWalletConnection() | { connectDetected, disconnect, isConnecting } |
| useWalletDetection() | { wallets, isDetecting, refreshWallets } |
Provider Types
| Provider | Use Case | Private Key Access | Browser Required |
|----------|----------|--------------------|-----------------|
| PrivateKeyProvider | CLI, bots, scripts | Yes | No |
| ExternalWalletProvider | MetaMask, Coinbase, etc. | No | Yes |
| GalaWalletProvider | Gala Wallet extension | No | Yes |
| GalaChainConnectProvider | @gala-chain/connect | No | Yes |
Error Handling
import { WalletProviderError, WalletProviderErrorCode } from '@gala-chain/launchpad-sdk/wallet';
try {
await provider.connect();
} catch (e) {
if (e instanceof WalletProviderError) {
switch (e.code) {
case WalletProviderErrorCode.USER_REJECTED:
console.log('User cancelled');
break;
case WalletProviderErrorCode.PROVIDER_NOT_AVAILABLE:
console.log('Wallet not installed');
break;
case WalletProviderErrorCode.CONNECTION_FAILED:
console.log('Connection failed:', e.message);
break;
}
}
}Full reference: docs/WALLET-PROVIDERS.md | Live demo: npm run demo:wallet
Method Categorization: Wallet Requirements
Methods that DON'T require a wallet (Read-Only Operations):
| Category | Methods | Notes |
|----------|---------|-------|
| Pool Queries | fetchPools, fetchAllPools, fetchPoolDetails, fetchPoolDetailsForCalculation, isTokenGraduated, isTokenNameAvailable, isTokenSymbolAvailable | Query pool data and token availability |
| Token Data | fetchTokenDetails, fetchTokenDistribution, fetchTokenBadges | Get token metadata and holder information |
| Pricing | fetchTokenSpotPrice, fetchGalaSpotPrice, fetchLaunchpadTokenSpotPrice, fetchVolumeData | Get current prices and OHLCV data |
| Price History | fetchPriceHistory, fetchAllPriceHistory | Get historical price snapshots (Node.js only) |
| Balance Info | fetchGalaBalance, fetchTokenBalance | Check GALA and token balances (your own only) |
| Portfolio | fetchTokensHeld, fetchTokensCreated | View your token portfolio and created tokens |
| Profile | fetchProfile | Retrieve user profile information |
| Comments | fetchComments | View comments on token pools |
| Trade History | fetchTrades | View your past trades |
| Utilities | getAddress, getEthereumAddress, getConfig, getVersion, getUrlByTokenName, getCacheInfo, clearCache, cleanup, cleanupAll | Utility and configuration methods |
| Reference | resolveTokenClassKey, resolveVaultAddress, calculateInitialBuyAmount | Resolve IDs and get reference data |
Methods that REQUIRE a wallet (Signing Operations):
| Category | Methods | Error When Missing |
|----------|---------|-------------------|
| Trading | buy, sell, calculateBuyAmount, calculateSellAmount, calculateBuyAmountLocal, calculateBuyAmountExternal, calculateSellAmountLocal, calculateSellAmountExternal | ValidationError: Wallet is required |
| Token Creation | launchToken, uploadTokenImage, uploadProfileImage, calculateBuyAmountForGraduation, graduateToken | ValidationError: Wallet is required |
| Account Management | updateProfile, postComment | ValidationError: Wallet is required |
| Transfers | transferGala, transferToken | ValidationError: Wallet is required |
| Admin | getBundlerTransactionResult | May require wallet for certain operations |
Key Points:
- ✅ All read operations work in read-only mode without a wallet
- ✅ Wallet can be added later via
setWallet()to enable signing operations - ✅ Missing wallet throws
ValidationErrorwith codeWALLET_REQUIRED - ⚠️ Only methods that sign transactions require a wallet
Environment Configuration
The SDK supports multiple environments (STAGE and PROD). All demo scripts and examples use a centralized environment configuration pattern via .env file.
Quick Setup
Create/edit .env in the repository root:
# .env
ENVIRONMENT=STAGE # Switch between STAGE and PROD
WALLET_PRIVATE_KEY=0x... # Your wallet private key (optional)All demo scripts automatically read from this .env file:
npm run demo:read-only # Uses ENVIRONMENT from .env
npm run demo:dex # Uses ENVIRONMENT from .env
npm run demo:liquidity # Uses ENVIRONMENT from .envEnvironment Values
| Value | Accepts | Use Case |
|-------|---------|----------|
| STAGE | STAGE, STAGING | Development/staging |
| PROD | PROD, PRODUCTION | Production |
| Default | (if not set) | Defaults to STAGE with warning |
SDK Initialization
When using demo scripts or examples, the environment is automatically loaded:
import { getEnvironment } from './examples/utils/get-environment';
const environment = getEnvironment(); // Reads from .env
const sdk = new LaunchpadSDK({
env: environment,
wallet: undefined // Optional
});Validation
Prevent hardcoded environment values:
npm run validate:env # Validates no hardcoded 'STAGE' or 'PROD'Full Documentation
See docs/ENVIRONMENT_CONFIGURATION.md for:
- Architecture and implementation details
- Pattern for adding new scripts
- Troubleshooting guide
- Migration guide for existing scripts
Token Format Migration (v3.33.0)
Breaking Change: Strict Token Format Enforcement
v3.33.0 removes support for plain token strings and requires all tokens to use delimited format.
Old Behavior (v3.32.x and below) - DEPRECATED
Plain token strings were accepted:
// ❌ NO LONGER WORKS (v3.33.0+)
await sdk.addSwapLiquidityByPrice({
token0: 'GALA', // Plain string
token1: 'GUSDC', // Plain string
fee: 3000,
minPrice: '0.95',
maxPrice: '1.05',
amount0Desired: '100',
amount1Desired: '100'
});New Behavior (v3.33.0+) - REQUIRED
All tokens must use pipe-delimited (|) or dollar-delimited ($) format:
// ✅ REQUIRED FORMAT (v3.33.0+)
await sdk.addSwapLiquidityByPrice({
token0: 'GALA|Unit|none|none', // Delimited format
token1: 'GUSDC|Unit|none|none', // Delimited format
fee: 3000,
minPrice: '0.95',
maxPrice: '1.05',
amount0Desired: '100',
amount1Desired: '100'
});Format Options
Pipe-Delimited (Recommended):
'GALA|Unit|none|none'
'GUSDC|Unit|none|none'
'MYTOKEN|Unit|none|none'Dollar-Delimited (Alternative):
'GALA$Unit$none$none'
'GUSDC$Unit$none$none'
'MYTOKEN$Unit$none$none'Migration Checklist
- [ ] Search codebase for plain token strings:
'GALA','GUSDC', etc. - [ ] Replace with delimited format:
'GALA|Unit|none|none','GUSDC|Unit|none|none' - [ ] Update all SDK method calls that pass token parameters
- [ ] Test thoroughly - TypeScript strict mode will catch most issues
- [ ] Update internal token handling code
Affected Methods
The following methods now require delimited token format:
getSwapQuoteExactInput(token0, token1, amount)getSwapQuoteExactOutput(token0, token1, amount)executeSwap(token0, token1, ...)addSwapLiquidityByPrice({token0, token1, ...})addSwapLiquidityByTicks({token0, token1, ...})removeSwapLiquidity({token0, token1, ...})getSwapPoolInfo(token0, token1)
Security Rationale
This breaking change enforces strict token format validation to:
- ✅ Prevent injection attacks via token string manipulation
- ✅ Ensure deterministic parsing with no ambiguous fallbacks
- ✅ Eliminate security gaps from loose string handling
- ✅ Force explicit token specification with full TokenClassKey structure
Plain string support created a dangerous "escape hatch" where ambiguous token identifiers could be accepted. v3.33.0 eliminates this by requiring all tokens be properly delimited.
Upgrading to v4.0.0
Breaking Changes: Removed Deprecated Methods
v4.0.0 removes one deprecated method that was superseded in v3.22.7. This is a clean removal with minimal migration effort - most users will not be affected.
Removed Method: fetchLaunchpadTokenSpotPrice()
This method was deprecated in v3.22.7 in favor of the more flexible fetchTokenPrice() method.
Old Code (v3.35.x and below) - NO LONGER WORKS:
// ❌ REMOVED in v4.0.0
const price = await sdk.fetchLaunchpadTokenSpotPrice('anime');
console.log(`Price: ${price} USD`);New Code (v4.0.0+) - REQUIRED:
// ✅ REQUIRED - Works for both launchpad and DEX tokens
const price = await sdk.fetchTokenPrice('anime');
console.log(`Price: ${price} USD`);Why This Change?
The new fetchTokenPrice() method:
- ✅ Unified pricing - Works for both launchpad tokens and DEX-graduated tokens
- ✅ Automatic routing - Detects token type and fetches from correct backend
- ✅ Better performance - Single method instead of specialized variants
- ✅ Cleaner API - Less method duplication in SDK
Migration Checklist
- [ ] Search codebase for
fetchLaunchpadTokenSpotPrice( - [ ] Replace all occurrences with
fetchTokenPrice( - [ ] Test with both launchpad tokens (e.g.,
'anime') and DEX tokens - [ ] Verify price results haven't changed (same calculation logic)
Impact Assessment
Affected Users:
- ⚠️ Only if you explicitly called
fetchLaunchpadTokenSpotPrice() - ✅ Not affected if you used
fetchTokenPrice()orfetchTokenSpotPrice()methods - ✅ Not affected if you never queried token prices
Migration Effort:
- ⏱️ 5 minutes - Simple find/replace across codebase
- ⚙️ Zero logic changes - Functionality remains identical
- 🎯 Low risk - Price calculation algorithm unchanged
New Features: Service Clients Documentation
v4.0.0 adds internal service client documentation for advanced users who need direct access to underlying blockchain services.
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key'
});
// Advanced: Direct access to DEX Backend API
// Use case: Custom swap parameters or debugging
const quote = await sdk.dexBackendClient.querySwapQuote({
orderedTokens: [...],
zeroForOne: false,
inputAmount: '10',
// ... additional parameters
});
// Advanced: Direct access to GalaChain Gateway
// Use case: Custom transaction building
const result = await sdk.galaChainGatewayClient.callContract({
address: 'contract-address',
method: 'transfer',
// ... parameters
});⚠️ Important: Service clients are internal implementation details. For standard operations, always use public SDK methods:
- ✅ Use
sdk.buy()instead ofsdk.galaChainGatewayClient - ✅ Use
sdk.executeSwap()instead ofsdk.dexBackendClient - ✅ These public methods provide better error handling and validation
For detailed service client documentation, see docs/API-REFERENCE.md#service-clients.
Migration Summary
For Most Users: Nothing to do! v4.0.0 is backward compatible except for the removal of fetchLaunchpadTokenSpotPrice().
If You Used fetchLaunchpadTokenSpotPrice(): Replace with fetchTokenPrice() - identical functionality, better flexibility.
If You Need Service Client Access: They're now documented and available for advanced use cases, but use public SDK methods when possible.
DEX Pool Discovery & Analysis
Overview
The SDK provides complete DEX liquidity pool discovery for GalaSwap with filtering, sorting, and pagination. Perfect for finding trading pairs, analyzing pool metrics, and discovering investment opportunities.
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({});
// Discover DEX pools with filtering
const pools = await sdk.fetchDexPools({
search: 'GALA', // Filter by token symbol
sortBy: 'tvl', // Sort options: tvl, volume30d, volume1d
sortOrder: 'desc', // asc or desc
pageSize: 20 // Results per page (default: 20, max: 50)
});
console.log(`Found ${pools.meta?.total || 'many'} pools`);
console.log(`Showing ${pools.items.length} pools with cursor-based pagination`);
// Fetch ALL pools with automatic pagination
const allPools = await sdk.fetchAllDexPools({
search: 'GUSDC',
sortBy: 'volume30d',
sortOrder: 'asc'
});
console.log(`Retrieved ${allPools.items.length} total pools`);Pool Data Structure
Each DEX pool includes comprehensive trading metrics:
interface DexPoolData {
poolPair: string; // e.g., "GALA/GUSDC"
poolHash: string; // Unique pool identifier
token0: string; // Token A symbol
token1: string; // Token B symbol
token0Price: string; // Token A USD price
token1Price: string; // Token B USD price
fee: string; // Fee tier (0.05%, 0.30%, 1.00%)
fee24h: number; // 24h accumulated fees
tvl: number; // Total Value Locked (USD)
token0Tvl: number; // TVL in Token A
token1Tvl: number; // TVL in Token B
token0TvlUsd: number; // Token A TVL in USD
token1TvlUsd: number; // Token B TVL in USD
volume1d: number; // 24h trading volume
volume30d: number; // 30d trading volume
apr1d: number; // 24h APR for liquidity providers
dayPerTvl: number; // Fee ratio (volume/TVL)
}Common Use Cases
Find high-volume pools:
const highVolumePoolsAsc = await sdk.fetchAllDexPools({
sortBy: 'volume1d',
sortOrder: 'desc'
});
const topPool = highVolumePoolsAsc.items[0];
console.log(`Highest volume pair: ${topPool.poolPair}`);
console.log(`24h Volume: $${topPool.volume1d}`);
console.log(`APR: ${topPool.apr1d.toFixed(2)}%`);Discover GALA trading pairs:
const galaPools = await sdk.fetchDexPools({
search: 'GALA',
sortBy: 'tvl',
pageSize: 20
});
galaPools.items.forEach(pool => {
console.log(`${pool.poolPair}: $${pool.tvl.toLocaleString()} TVL`);
});Analyze liquidity provider opportunities:
const liquidityOpportunities = await sdk.fetchAllDexPools({
sortBy: 'apr1d',
sortOrder: 'desc'
});
// Find pools with highest APR
const bestAprPools = liquidityOpportunities.items.slice(0, 10);
bestAprPools.forEach(pool => {
console.log(`${pool.poolPair}: ${pool.apr1d.toFixed(2)}% APR`);
});Sorting Options
| Sort Value | Description | Best For |
|-----------|-------------|----------|
| tvl (default) | Total Value Locked | Finding main liquidity pools |
| volume1d | 24-hour trading volume | High-activity pairs |
| volume30d | 30-day trading volume | Trend analysis |
Pagination
The SDK uses cursor-based pagination with configurable page sizes. Use fetchAllDexPools() for complete enumeration:
// Cursor-based discovery (20 max per page)
let cursor: string | undefined;
const result = await sdk.fetchDexPools({ pageSize: 20, cursor });
console.log(`Showing: ${result.items.length} pools`);
console.log(`Has next: ${result.pageInfo?.hasNextPage}`);
if (result.pageInfo?.hasNextPage) cursor = result.pageInfo?.nextCursor;
// Automatic pagination - get all at once
const allAtOnce = await sdk.fetchAllDexPools();
console.log(`All pools: ${allAtOnce.items.length}`);Cursor-Based Pagination Loop:
// Manually iterate through paginated results using cursors
let cursor: string | undefined;
const allPools = [];
while (true) {
const result = await sdk.fetchDexPools({ pageSize: 20, cursor });
allPools.push(...result.items);
if (!result.pageInfo?.hasNextPage) break;
cursor = result.pageInfo?.nextCursor;
}
console.log(`Retrieved ${allPools.length} total pools`);Development vs Production Environments
The SDK automatically uses the correct DEX backend based on your environment configuration:
// Production (default)
const prodSdk = createLaunchpadSDK({
environment: 'production' // Uses prod DEX backend
});
// Development
const devSdk = createLaunchpadSDK({
environment: 'development' // Uses dev DEX backend
});
// Custom URL
const customSdk = createLaunchpadSDK({
dexBackendBaseUrl: 'https://custom-dex.example.com'
});WebSocket Event Watchers (v3.29.0+)
Real-time event monitoring for DEX pools and launchpad tokens using polling-based watchers with automatic deduplication.
Public WebSocket Methods
Connect and manage WebSocket connections for real-time event subscriptions:
// Connect to WebSocket
sdk.connectWebSocket();
// Check connection status
if (sdk.isWebSocketConnected()) {
console.log('✅ WebSocket connected');
}
// Subscribe to custom WebSocket events
const unsubscribe = sdk.subscribeToEvent<MyEventType>('custom-channel', (data) => {
console.log('Event received:', data);
});
// Cleanup when done
unsubscribe();
// Disconnect from WebSocket
sdk.disconnectWebSocket();Event Watchers: Real-Time Pool & Token Discovery
Watch for new DEX pools and launchpad tokens with optional filtering and automatic deduplication.
Watch DEX Pool Creation
Monitor new liquidity pool creation with TVL and token pair filtering:
const unsubscribe = sdk.onDexPoolCreation(
(pool) => {
console.log(`✨ New pool: ${pool.poolName}`);
console.log(` Pair: ${pool.token0} / ${pool.token1}`);
console.log(` TVL: $${pool.tvl.toFixed(2)}`);
console.log(` 24h Volume: $${pool.volume1d.toFixed(2)}`);
},
{
minTVL: 10000, // Only notify for pools with TVL >= $10,000
tokens: ['GALA', 'GUSDC'], // Only GALA or GUSDC pairs
intervalMs: 30000 // Poll every 30 seconds (default)
}
);
// Stop watching after some time
setTimeout(() => {
unsubscribe();
console.log('Stopped watching for new pools');
}, 300000); // 5 minutesWatch Launchpad Token Creation
Monitor new token launches with optional creator filtering:
const unsubscribe = sdk.onLaunchpadTokenCreation(
(token) => {
console.log(`🚀 New token: ${token.tokenName}`);
console.log(` Symbol: ${token.symbol}`);
console.log(` Creator: ${token.creatorAddress}`);
console.log(` Created: ${new Date(token.createdAt).toISOString()}`);
},
{
creatorAddress: 'eth|0x1234...', // Only watch specific creator (optional)
intervalMs: 30000 // Poll every 30 seconds (default)
}
);
// Example: Watch all tokens for 2 minutes
setTimeout(() => {
unsubscribe();
console.log('Stopped watching for new tokens');
}, 120000);Key Characteristics
- Polling-Based: Intelligent polling with configurable intervals (recommended minimum: 5 seconds)
- Automatic Deduplication: Prevents duplicate callbacks for the same pool/token
- Client-Side Filtering: Minimizes API calls with local filtering (minTVL, token pairs, creator address)
- Cleanup Functions: All watchers return cleanup functions for proper resource management
- Error Resilience: Watchers continue polling after errors without blocking
- Long-Running Support: Suitable for background monitoring in production applications
Demo Scripts
Try the event watcher examples:
# Watch for new DEX pools
npm run demo:watch-pools
# Watch for new launchpad tokens
npm run demo:watch-tokensAI Agent Integration
For Claude Desktop Users
Install the MCP server to enable Claude to interact with Gala Launchpad directly:
Full-Access Mode (with wallet for executing trades):
claude mcp add "galachain-launchpad" -- env PRIVATE_KEY=<YOUR_PRIVATE_KEY> ENVIRONMENT=development npx -y @gala-chain/launchpad-mcp-server@latestRead-Only Mode (query data without wallet):
claude mcp add "galachain-launchpad-readonly" -- env ENVIRONMENT=development npx -y @gala-chain/launchpad-mcp-server@latestEnvironment Variables:
PRIVATE_KEY(optional) - Your wallet private key (omit for read-only mode)ENVIRONMENT- Backend environment:development|production(default: production)DEBUG- Enable debug logging:true|false(default: false)TIMEOUT- Request timeout in milliseconds (default: 30000)
Features: 224 tools for complete Gala Launchpad operations including:
- Pool management, pricing, and token discovery
- Token trading with slippage protection
- Token creation and management
- Balance and portfolio queries
- Wallet status checking and configuration
- Price history and analysis (Node.js only)
- Comments and social features
- Transfers and transactions
Try slash commands (MCP v1.4.0+):
/galachain-launchpad:analyze-token tokenName=anime
/galachain-launchpad:portfolio
/galachain-launchpad:buy-tokens tokenName=anime galaAmount=100For AI Developers
Need help with SDK integration, trading bots, or MCP server development?
Ask @agent-galachain-launchpad-developer - a specialized AI agent with expertise in:
- Complete SDK API (230+ methods)
- Optional wallet configuration and dual operational modes
- Trading patterns and DeFi best practices
- MCP server architecture
- Error handling strategies
- Performance optimization
Full Integration Guide: AI Agent Guide
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', pageSize: 20 });
console.log(`Found ${pools.meta?.total} pools`);
console.log(`Has next page: ${pools.pageInfo?.hasNextPage}`);
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: '1', // 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: '1',
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.meta.total} trades`);
console.log(`Page ${trades.meta.page} of ${trades.meta.totalPages}`);
trades.items.forEach(trade => {
console.log(`Trade: ${trade.tradeType} ${trade.tokenAmount} at ${trade.createdAt.toISOString()}`);
});
const comments = await sdk.fetchComments({ tokenName: 'dragnrkti' });
console.log(`${comments.meta.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',
address: 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'}`);
// URL Utilities - Generate frontend URLs
const tokenUrl = sdk.getUrlByTokenName('dragnrkti');
console.log(`View token: ${tokenUrl}`);
// Output: https://lpad-frontend-test1.defi.gala.com/buy-sell/dragnrktiAuto-Pagination Feature
The SDK now supports automatic pagination for pool fetching with three powerful modes:
Three Pagination Modes
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
// MODE 1: Single Page (backward compatible)
// Limit <= 20: Single API call
const recent = await sdk.fetchPools({ type: 'recent', pageSize: 20 });
console.log(`Fetched ${recent.items.length} pools in one request`);
// MODE 2: Multi-Page Auto-Fetch
// Limit > 20: Automatic concurrent multi-page fetching
const large = await sdk.fetchPools({ type: 'popular', pageSize: 100 });
console.log(`Fetched ${large.items.length} pools across multiple pages`);
// Internally uses cursor-based pagination to efficiently fetch all items
// MODE 3: Infinite Fetch
// Limit = 0: Fetches ALL available pools
const all = await sdk.fetchAllPools();
console.log(`Fetched all ${all.items.length} pools from the platform`);
// Convenience method for "fetch all" pattern
const allRecent = await sdk.fetchAllPools({ type: 'recent' });
console.log(`Total pools: ${allRecent.meta.total}`);Concurrency Configuration
The SDK uses MAX_CONCURRENT_POOL_FETCHES to control parallel API requests:
import { MAX_CONCURRENT_POOL_FETCHES } from '@gala-chain/launchpad-sdk';
console.log(`SDK fetches up to ${MAX_CONCURRENT_POOL_FETCHES} pages concurrently`);
// Output: "SDK fetches up to 5 pages concurrently"Default: 5 concurrent requests Benefit: Balances speed with API rate limits
Performance Benefits
| Scenario | Pages Fetched | Network Calls | Time (Sequential) | Time (Concurrent) | Improvement | |----------|---------------|---------------|-------------------|-------------------|-------------| | 20 pools | 1 page | 1 call | ~200ms | ~200ms | No change | | 100 pools | 5 pages | 5 calls | ~1000ms | ~200ms | 5x faster | | 500 pools | 25 pages | 25 calls | ~5000ms | ~1000ms | 5x faster | | All pools (1000+) | 50+ pages | 50+ calls | ~10,000ms | ~2000ms | 5x faster |
When to Use Each Mode
Single Page (limit <= 20)
- Quick queries
- UI pagination with next/previous buttons
- When you only need recent results
Multi-Page (limit > 20)
- Analytics dashboards
- Bulk operations on specific token counts
- When you know how many results you need
Infinite (limit = 0 or fetchAllPools())
- Complete market scans
- Full portfolio analysis
- Trading bot initialization
- Data exports and backups
Example: Market Scanner
async function scanEntireMarket() {
// Fetch all pools at once (auto-pagination handles everything)
const allPools = await sdk.fetchAllPools({ type: 'popular' });
console.log(`Scanning ${allPools.meta.total} pools...`);
// Filter for interesting opportunities
const highVolume = allPools.items.filter(pool =>
parseFloat(pool.volumeGala) > 10000
);
console.log(`Found ${highVolume.length} high-volume pools`);
return highVolume;
}New Methods
fetchAllPools(options?)
Convenience method that automatically fetches all available pools:
// Fetch all recent pools
const allRecent = await sdk.fetchAllPools({ type: 'recent' });
// Fetch all pools matching search
const dragons = await sdk.fetchAllPools({ search: 'dragon' });
// Fetch specific token across all results
const specific = await sdk.fetchAllPools({ tokenName: 'anime' });
// Automatic pagination handles all pages internally
const all = await sdk.fetchAllPools();Stream Filtering (v5.7.0+)
Filter pools by streaming activity and language:
// Find pools with upcoming scheduled shows
const upcomingShows = await sdk.fetchPools({ hasUpcomingShows: true });
// Find pools that recently went live (last 24 hours)
const recentlyLive = await sdk.fetchPools({ recentlyStreamed: 24 });
// Find active streaming communities (last week)
const activeCommunities = await sdk.fetchAllPools({ recentlyStreamed: 168 });
// Filter by stream language (ISO 639-1 codes)
const englishPools = await sdk.fetchPools({ language: 'en' });
const spanishPools = await sdk.fetchPools({ language: 'es' });
// Pool data includes stream stats
const pools = await sdk.fetchPools({ type: 'popular' });
pools.items.forEach(pool => {
console.log(`${pool.tokenName}:`);
console.log(` Viewers: ${pool.currentViewerCount || 0}`);
console.log(` Peak viewers: ${pool.peakViewerCount || 0}`);
console.log(` Last streamed: ${pool.lastStreamedAt || 'Never'}`);
});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',
pageSize: 20
});
console.log(`Found ${pools.meta.total} pools`);
pools.items.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.meta.total} trades on page ${trades.meta.page}`);
console.log(`Has more pages: ${trades.meta.page < trades.meta.totalPages}`);
trades.items.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',
address: 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: '1', // 1 GALA
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
Lock/Unlock Operations
Lock and unlock tokens on GalaChain for staking, escrow, and vesting mechanisms:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
// Lock tokens - caller becomes lock authority by default
const lockResult = await sdk.lockToken({
tokenName: 'tinyevil',
amount: '1000' // Token amount in smallest unit
});
console.log(`Locked tokens, tx: ${lockResult.transactionId}`);
// Lock with custom authority and expiration
const escrowLock = await sdk.lockToken({
tokenName: 'tinyevil',
amount: '5000',
lockAuthority: 'eth|0xEscrowContract...', // Third party can unlock
expires: Date.now() + 7 * 24 * 60 * 60 * 1000, // Auto-release in 1 week
name: 'escrow-deal-123' // Named lock for matching
});
// Unlock tokens - must be called by lock authority
const unlockResult = await sdk.unlockToken({
tokenName: 'tinyevil',
amount: '1000'
});
console.log(`Unlocked tokens, tx: ${unlockResult.transactionId}`);
// Unlock specific named lock
await sdk.unlockToken({
tokenName: 'tinyevil',
amount: '5000',
name: 'escrow-deal-123' // Must match lock name
});Lock Features
- Lock Authority: Specify who can unlock (defaults to caller)
- Expiration: Optional auto-release timestamp
- Named Locks: Identify locks by name for targeted unlocks
- EIP-712 Signatures: Secure blockchain transactions
- Idempotency: Optional unique keys prevent duplicate operations
Use Cases
- Staking: Lock tokens for reward programs
- Escrow: Third-party holds tokens until conditions met
- Vesting: Time-locked token releases with expiration
Cross-Chain Bridge Operations
The SDK provides comprehensive cross-chain bridging for GalaChain ↔ Ethereum and GalaChain ↔ Solana transfers.
Configuration
import { LaunchpadSDK } from '@gala-chain/launchpad-sdk';
const sdk = new LaunchpadSDK({
wallet: process.env.PRIVATE_KEY,
// Bridge configuration (optional - enables bridge operations)
ethereumPrivateKey: process.env.ETHEREUM_PRIVATE_KEY, // Required for Ethereum bridging
solanaPrivateKey: process.env.SOLANA_PRIVATE_KEY, // Required for Solana bridging
});Wallet Balance Queries
Query Ethereum and Solana wallet balances with two approaches:
Single Token Queries (Fast - 1 RPC call)
// Single ERC-20 token balance
const gala = await sdk.fetchEthereumWalletTokenBalance('GALA');
// Returns: { symbol: 'GALA', quantity: '1234.56', decimals: 8, contractAddress: '0x...', isNative: false }
// Native ETH balance
const eth = await sdk.fetchEthereumWalletNativeBalance();
// Returns: { symbol: 'ETH', quantity: '0.5', decimals: 18, contractAddress: null, isNative: true }
// Single SPL token balance (Solana)
const solGala = await sdk.fetchSolanaWalletTokenBalance('GALA');
// Returns: { symbol: 'GALA', quantity: '789.01', decimals: 8, contractAddress: '...', isNative: false }
// Native SOL balance
const sol = await sdk.fetchSolanaWalletNativeBalance();
// Returns: { symbol: 'SOL', quantity: '2.5', decimals: 9, contractAddress: null, isNative: true }All Tokens Queries (Complete portfolio view)
// Ethereum: ETH + all supported ERC-20s (GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC)
const allEth = await sdk.fetchEthereumWalletAllBalances();
console.log(allEth.native.quantity); // ETH balance
console.log(allEth.tokens); // 6 ERC-20 balances
console.log(allEth.address); // Wallet address
console.log(allEth.timestamp); // Query timestamp
// Solana: SOL + all supported SPL tokens (GALA, GSOL)
const allSol = await sdk.fetchSolanaWalletAllBalances();
console.log(allSol.native.quantity); // SOL balance
console.log(allSol.tokens); // 2 SPL balancesWhen to use which:
- Single-token queries: Quick checks, performance-critical scenarios, frequent polling
- All-tokens queries: Portfolio dashboards, wallet UIs, multi-token operations
Bridge Operations
// Estimate fees before bridging
const fee = await sdk.estimateBridgeFee({
tokenSymbol: 'GALA',
destinationChain: 'Ethereum',
amount: '1000',
});
// Bridge OUT: GalaChain → Ethereum/Solana
const result = await sdk.bridgeOut({
tokenSymbol: 'GALA',
amount: '1000',
destinationChain: 'Ethereum',
recipientAddress: '0x...',
});
// Bridge IN: Ethereum/Solana → GalaChain
const result = await sdk.bridgeIn({
tokenSymbol: 'GALA',
amount: '1000',
sourceChain: 'Ethereum',
});
// Check bridge status
const status = await sdk.getBridgeStatus(result.transactionHash);Supported Tokens
| Token | Symbol | Ethereum | Solana | Decimals | |-------|--------|----------|--------|----------| | GALA | GALA | ✅ | ✅ | 8 | | Wrapped ETH | GWETH | ✅ | - | 18 | | USD Coin | GUSDC | ✅ | - | 6 | | Tether USD | GUSDT | ✅ | - | 6 | | Wrapped TRON | GWTRX | ✅ | - | 6 | | Wrapped BTC | GWBTC | ✅ | - | 8 | | Wrapped SOL | GSOL | - | ✅ | 9 |
Multi-Wallet Support
The SDK supports per-operation wallet overrides for testing multi-wallet workflows without creating new SDK instances. This is ideal for:
- Testing trading scenarios with multiple wallets
- Building multi-user applications
- Simulating different user behaviors
- Creating automated trading bots
Private Key Override Pattern
All signing operations accept an optional privateKey parameter to use a different wallet for that specific operation:
import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
// Create SDK with your main wallet
const sdk = createLaunchpadSDK({
wallet: 'your-main-private-key'
});
// Different wallet's private key (must be in '0x' + 64 hex format)
const busterPrivateKey = '0x1234567890abcdef...'; // Buster's wallet
// 1. Send GALA from main wallet to Buster
await sdk.transferGala({
recipientAddress: '0xBusterAddress...',
amount: '1000'
// Uses main SDK wallet (no privateKey override)
});
// 2. Have Buster buy tokens using his own wallet
const buyResult = await sdk.buy({
tokenName: 'tinyevil',
amount: '100',
type: 'native',
expectedAmount: '500000',
slippageToleranceFactor: 0.05,
privateKey: busterPrivateKey // Override to use Buster's wallet
});
// 3. Have Buster post a comment
await sdk.postComment({
tokenName: 'tinyevil',
content: 'Great buy!',
privateKey: busterPrivateKey // Buster posts the comment
});
// 4. Main wallet continues operations normally
const mainWalletBalance = await sdk.fetchGalaBalance();
// Uses main SDK wallet addressSupported Operations with Private Key Override
All signing operations support the privateKey parameter:
Trading Operations:
buy(options)- Buy tokens with different walletsell(options)- Sell tokens with different wallet
Token Creation:
launchToken(data)- Create token from different walletuploadTokenImage(options)- Upload image for token
Transfer Operations:
transferGala(options)- Transfer GALA from different wallettransferToken(options)- Transfer tokens from different wallet
Social & Profile:
postComment(options)- Post comment from different walletupdateProfile(data)- Update profile for different walletuploadProfileImage(options)- Upload profile image for different wallet
Complete Multi-Wallet Example
import { createLaunchpadSDK, createWallet } from '@gala-chain/launchpad-sdk';
// Main SDK instance
const sdk = createLaunchpadSDK({
wallet: 'your-main-private-key'
});
// Create a test wallet for "Buster"
const busterWallet = createWallet(); // Random wallet
const busterPrivateKey = busterWallet.privateKey;
const busterAddress = busterWallet.address;
console.log(`Buster's address: ${busterAddress}`);
// 1. Fund Buster with GALA from main wallet
await sdk.transferGala({
recipientAddress: busterAddress,
amount: '1000'
});
// 2. Send Buster some tokens from main wallet
await sdk.transferToken({
to: busterAddress,
tokenName: 'tinyevil',
amount: '10000'
});
// 3. Have Buster send some tokens back to main wallet
await sdk.transferToken({
to: sdk.getEthereumAddress(), // Main wallet address
tokenName: 'tinyevil',
amount: '5000',
privateKey: busterPrivateKey // Buster's wallet signs
});
// 4. Have Buster buy more tokens
const buyQuote = await sdk.calculateBuyAmount({
tokenName: 'tinyevil',
amount: '100',
type: 'native'
});
await sdk.buy({
tokenName: 'tinyevil',
amount: '100',
type: 'native',
expectedAmount: buyQuote.amount,
slippageToleranceFactor: 0.05,
privateKey: busterPrivateKey // Buster buys
});
// 5. Have Buster sell some tokens
const sellQuote = await sdk.calculateSellAmount({
tokenName: 'tinyevil',
amount: '50',
type: 'native'
});
await sdk.sell({
tokenName: 'tinyevil',
amount: '50',
type: 'native',
expectedAmount: sellQuote.amount,
slippageToleranceFactor: 0.05,
privateKey: busterPrivateKey // Buster sells
});
// 6. Check final balances for both wallets
const mainBalance = await sdk.fetchGalaBalance(); // Main wallet
const busterBalance = await sdk.fetchGalaBalance(busterAddress); // Buster's wallet
console.log(`Main wallet: ${mainBalance.balance} GALA`);
console.log(`Buster wallet: ${busterBalance.balance} GALA`);Private Key Format Requirements
The privateKey parameter must be a string in the format:
- Format:
'0x' + 64 hexadecimal characters - Example:
'0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' - Invalid: Raw hex without '0x' prefix, mnemonic phrases, addresses
// ✅ Valid private key formats
const validKey1 = '0x' + 'a'.repeat(64); // Correct format
const validKey2 = wallet.privateKey; // From ethers.js Wallet
// ❌ Invalid formats (will throw validation error)
const invalidKey1 = 'a'.repeat(64); // Missing '0x' prefix
const invalidKey2 = 'word1 word2 ... word24'; // Mnemonic not accepted
const invalidKey3 = '0x123'; // Too shortAvailable Methods & Result Types
Fetch Operations
// Pool Management
fetchPools(options?): Promise<PoolsResult>
// Returns: { items, meta: { total }, pageInfo: { hasNextPage, nextCursor } }
// Supports cursor-based pagination with configurable pageSize
fetchAllPools(options?): Promise<PoolsResult>
// Returns: { items, meta: { total }, pageInfo: { hasNextPage } }
// Convenience method that fetches ALL pools using cursor-based pagination
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, ... }
fetchTokenDetails(tokenId): Promise<TokenDetails>
// Returns: { symbol, decimals, name, image, verified, network, chainId, contractAddress, tradingEnabled, ... }
// Supports flexible tokenId: string ('GUSDC|Unit|none|eth:0x...') or object format
fetchVolumeData(options): Promise<GraphDataResult>
// Returns: { dataPoints }
// Trade & User Data
fetchTrades(options): Promise<TradesResult>
// Returns: { items, meta: { total }, pageInfo: { hasNextPage, nextCursor } }
fetchGalaBalance(address?): Promise<GalaBalanceInfo>
// Returns: { userAddress, balance, decimals, lastUpdated }
fetchTokenBalance(options): Promise<TokenBalanceInfo>
// Returns: { quantity, holdingPriceUsd, holdingPriceGala, isFinalized, ... }
fetchComments(options): Promise<CommentsResult>
// Returns: { items, meta: { total }, pageInfo: { hasNextPage, nextCursor } }
fetchProfile(address?): Promise<UserProfile>
// Returns: { fullName, profileImage, address, ... }
fetchLaunchTokenFee(): Promise<number>
// Returns: Current GALA fee required to launch a new token (e.g., 0.001)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 }
calculateBuyAmountForGraduation(tokenName): Promise<AmountCalculationResult>
// Returns: { amount, reverseBondingCurveFee, transactionFee }
// Calculates exact GALA cost to buy all remaining tokens and graduate pool
// Local Calculations (Client-Side, No Network)
calculateBuyAmountLocal(options): Promise<AmountCalculationResult>
// Options: { tokenName, amount, type: 'native' | 'exact' }
// Returns: { amount, reverseBondingCurveFee: '0', transactionFee, gasFee }
// Instant buy calculation using local bonding curve formulas
calculateSellAmountLocal(options): Promise<AmountCalculationResult>
// Options: { tokenName, amount, type: 'native' | 'exact', maxSupply, minFeePortion, maxFeePortion }
// Returns: { amount, reverseBondingCurveFee, transactionFee, gasFee }
// Instant sell calculation with reverse bonding curve fees
// External Calculations (GalaChain Network)
calculateBuyAmountExternal(options): Promise<AmountCalculationResult>
// Explicit external calculation wrapper (same as calculateBuyAmount)
calculateSellAmountExternal(options): Promise<AmountCalculationResult>
// Explicit external calculation wrapper (same as calculateSellAmount)
// Note: Pass `calculateAmountMode: 'local' | 'external'` to override SDK default mode
// Price History Operations (DEX Backend API, Node.js only)
fetchPriceHistory(options): Promise<PriceHistoryResult>
// Options: { tokenName?, tokenId?, from?, to?, sortOrder?, page?, limit? }
// Token identification (provide EXACTLY ONE):
// - tokenName: Simple token name (e.g., "demonkpop") - auto-resolves to tokenId
// - tokenId: Full token class key (e.g., "Token|Unit|DKP|eth:...")
// Returns: { items, meta: { total }, pageInfo: { hasNextPage, nextCursor } }
// Fetches paginated historical price snapshots from DEX Backend API
fetchAllPriceHistory(options): Promise<PriceHistoryResult>
// Options: { tokenName?, tokenId?, from?, to?, sortOrder? } (no pagination params)
// Token identification (provide EXACTLY ONE):
// - tokenName: Simple token name (e.g., "demonkpop") - auto-resolves to tokenId
// - tokenId: Full token class key (e.g., "Token|Unit|DKP|eth:...")
// Returns: All matching snapshots with total count
// Convenience method with automatic pagination (returns ALL snapshots)Performance Optimization
Reusing Pool Data to Avoid Redundant Network Calls
Methods that internally use calculateBuyAmount/calculateSellAmount now support optional calculateAmountMode and currentSupply parameters for performance optimization. This allows you to:
- Fetch pool details once using
fetchPoolDetailsForCalculation - Reuse
currentSupplyacross multiple calculations - Eliminate redundant network calls with local mode calculations
- Get instant results when real-time precision isn't required
Supported Methods
The following methods accept optional performance parameters:
fetchLaunchpadTokenSpotPrice(options)- PasscalculateAmountModeand/orcurrentSupplycalculateBuyAmountForGraduation(options)- PasscalculateAmountModeand/orcurrentSupplygraduateToken(options)- PasscalculateAmountModeand/orcurrentSupply
Using CALCULATION_MODES Constant
import { createLaunchpadSDK, CALCULATION_MODES } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
// Use type-safe calculation mode constants
console.log(CALCULATION_MODES.LOCAL); // 'local'
console.log(CALCULATION_MODES.EXTERNAL); // 'external'Basic Optimization Pattern
import { createLaunchpadSDK, CALCULATION_MODES } from '@gala-chain/launchpad-sdk';
const sdk = createLaunchpadSDK({
wallet: 'your-private-key-or-mnemonic'
});
const tokenName = 'tinyevil';
// ❌ WITHOUT OPTIMIZATION (3 network calls)
const spotPrice1 = await sdk.fetchLaunchpadTokenSpotPrice(tokenName);
// → Fetches pool details internally (call #1)
const graduation1 = await sdk.calculateBuyAmountForGraduation(tokenName);
// → Fetches pool details internally (call #2)
const graduationResult1 = await sdk.graduateToken({ tokenName });
// → Fetches pool details internally (call #3)
// ✅ WITH