@gala-chain/launchpad-mcp-server 1.14.1 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/generated/version.d.ts +1 -1
  3. package/dist/generated/version.js +1 -1
  4. package/dist/tools/utils/explainSdkUsage.d.ts.map +1 -1
  5. package/dist/tools/utils/explainSdkUsage.js +441 -20
  6. package/dist/tools/utils/explainSdkUsage.js.map +1 -1
  7. package/docs/AI-AGENT-PATTERNS.md +555 -0
  8. package/docs/CONSTRAINTS-REFERENCE.md +454 -0
  9. package/docs/PROMPT-TOOL-MAPPING.md +352 -0
  10. package/docs/examples/default-values-pattern.md +240 -0
  11. package/docs/examples/tool-factory-pattern.md +217 -0
  12. package/jest.config.js +94 -0
  13. package/package.json +2 -2
  14. package/src/__tests__/integration/fetchTokenDetails.integration.test.ts +258 -0
  15. package/src/__tests__/integration/poolTools.integration.test.ts +185 -0
  16. package/src/constants/mcpToolNames.ts +141 -0
  17. package/src/index.ts +19 -0
  18. package/src/prompts/__tests__/promptStructure.test.ts +114 -0
  19. package/src/prompts/__tests__/registry.test.ts +145 -0
  20. package/src/prompts/analysis.ts +429 -0
  21. package/src/prompts/index.ts +127 -0
  22. package/src/prompts/portfolio.ts +242 -0
  23. package/src/prompts/trading.ts +191 -0
  24. package/src/prompts/utility.ts +43 -0
  25. package/src/prompts/utils/workflowTemplates.ts +344 -0
  26. package/src/schemas/common-schemas.ts +393 -0
  27. package/src/scripts/test-all-prompts.ts +184 -0
  28. package/src/server.ts +241 -0
  29. package/src/tools/balance/index.ts +174 -0
  30. package/src/tools/creation/index.ts +182 -0
  31. package/src/tools/index.ts +80 -0
  32. package/src/tools/pools/fetchAllPools.ts +47 -0
  33. package/src/tools/pools/fetchAllPriceHistory.ts +103 -0
  34. package/src/tools/pools/fetchPoolDetails.ts +27 -0
  35. package/src/tools/pools/fetchPoolDetailsForCalculation.ts +22 -0
  36. package/src/tools/pools/fetchPools.ts +47 -0
  37. package/src/tools/pools/fetchPriceHistory.ts +108 -0
  38. package/src/tools/pools/fetchTokenDetails.ts +77 -0
  39. package/src/tools/pools/index.ts +246 -0
  40. package/src/tools/social/index.ts +64 -0
  41. package/src/tools/trading/index.ts +605 -0
  42. package/src/tools/transfers/index.ts +75 -0
  43. package/src/tools/utils/clearCache.ts +36 -0
  44. package/src/tools/utils/createWallet.ts +19 -0
  45. package/src/tools/utils/explainSdkUsage.ts +1277 -0
  46. package/src/tools/utils/getAddress.ts +12 -0
  47. package/src/tools/utils/getCacheInfo.ts +14 -0
  48. package/src/tools/utils/getConfig.ts +11 -0
  49. package/src/tools/utils/getEthereumAddress.ts +12 -0
  50. package/src/tools/utils/getUrlByTokenName.ts +12 -0
  51. package/src/tools/utils/getVersion.ts +25 -0
  52. package/src/tools/utils/index.ts +27 -0
  53. package/src/tools/utils/isTokenGraduated.ts +16 -0
  54. package/src/types/mcp.ts +72 -0
  55. package/src/utils/__tests__/validation.test.ts +147 -0
  56. package/src/utils/constraints.ts +155 -0
  57. package/src/utils/default-values.ts +208 -0
  58. package/src/utils/error-handler.ts +69 -0
  59. package/src/utils/error-templates.ts +273 -0
  60. package/src/utils/response-formatter.ts +51 -0
  61. package/src/utils/tool-factory.ts +257 -0
  62. package/src/utils/tool-registry.ts +296 -0
  63. package/src/utils/validation.ts +336 -0
  64. package/tsconfig.json +23 -0
@@ -0,0 +1,1277 @@
1
+ /**
2
+ * SDK Usage Explanation Tool
3
+ *
4
+ * Provides detailed explanations and code examples for using the Gala Launchpad SDK directly.
5
+ * Acts as a development reference showing how MCP tools map to SDK methods.
6
+ */
7
+
8
+ import type { MCPTool } from '../../types/mcp.js';
9
+ import { withErrorHandling } from '../../utils/error-handler.js';
10
+ import { formatSuccess } from '../../utils/response-formatter.js';
11
+
12
+ /**
13
+ * SDK code examples organized by topic
14
+ */
15
+ const SDK_EXAMPLES = {
16
+ // Trading workflows
17
+ 'buy-tokens': `
18
+ ## Buying Tokens with SDK
19
+
20
+ \`\`\`typescript
21
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
22
+
23
+ async function buyTokens() {
24
+ // 1. Create SDK instance
25
+ const sdk = createLaunchpadSDK({
26
+ wallet: 'your-private-key-or-mnemonic'
27
+ });
28
+
29
+ // 2. Calculate expected amounts FIRST (REQUIRED)
30
+ const calculation = await sdk.calculateBuyAmount({
31
+ tokenName: 'dragnrkti',
32
+ amount: '100', // Spending 100 GALA
33
+ type: 'native' // 'native' = GALA amount, 'exact' = token amount
34
+ });
35
+
36
+ console.log('Expected tokens:', calculation.amount);
37
+ console.log('RBC Fee:', calculation.reverseBondingCurveFee);
38
+ console.log('Transaction fee:', calculation.transactionFee);
39
+
40
+ // 3. Execute buy with slippage protection
41
+ const result = await sdk.buy({
42
+ tokenName: 'dragnrkti',
43
+ amount: '100',
44
+ type: 'native',
45
+ expectedAmount: calculation.amount, // REQUIRED: from step 2
46
+ maxAcceptableReverseBondingCurveFee: calculation.reverseBondingCurveFee, // RECOMMENDED
47
+ slippageToleranceFactor: 0.01 // 1% slippage tolerance (REQUIRED)
48
+ });
49
+
50
+ console.log('Transaction ID:', result.transactionId);
51
+ console.log('GALA spent:', result.inputAmount);
52
+ console.log('Tokens received:', result.outputAmount);
53
+ console.log('Total fees:', result.totalFees);
54
+ }
55
+ \`\`\`
56
+
57
+ **MCP Tool Equivalent:** \`gala_launchpad_buy_tokens\`
58
+ `,
59
+
60
+ 'sell-tokens': `
61
+ ## Selling Tokens with SDK
62
+
63
+ \`\`\`typescript
64
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
65
+
66
+ async function sellTokens() {
67
+ // 1. Create SDK instance
68
+ const sdk = createLaunchpadSDK({
69
+ wallet: 'your-private-key'
70
+ });
71
+
72
+ // 2. Calculate expected GALA FIRST (REQUIRED)
73
+ const calculation = await sdk.calculateSellAmount({
74
+ tokenName: 'dragnrkti',
75
+ amount: '1000', // Selling 1000 tokens
76
+ type: 'exact' // 'exact' = exact tokens, 'native' = target GALA amount
77
+ });
78
+
79
+ console.log('Expected GALA:', calculation.amount);
80
+ console.log('RBC Fee:', calculation.reverseBondingCurveFee);
81
+
82
+ // 3. Execute sell with slippage protection
83
+ const result = await sdk.sell({
84
+ tokenName: 'dragnrkti',
85
+ amount: '1000',
86
+ type: 'exact',
87
+ expectedAmount: calculation.amount, // REQUIRED: from step 2
88
+ maxAcceptableReverseBondingCurveFee: calculation.reverseBondingCurveFee, // RECOMMENDED
89
+ slippageToleranceFactor: 0.01 // 1% slippage
90
+ });
91
+
92
+ console.log('Tokens sold:', result.inputAmount);
93
+ console.log('GALA received:', result.outputAmount);
94
+ }
95
+ \`\`\`
96
+
97
+ **MCP Tool Equivalent:** \`gala_launchpad_sell_tokens\`
98
+ `,
99
+
100
+ 'pool-graduation': `
101
+ ## Pool Graduation with SDK
102
+
103
+ \`\`\`typescript
104
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
105
+
106
+ async function graduatePool() {
107
+ const sdk = createLaunchpadSDK({
108
+ wallet: 'your-private-key'
109
+ });
110
+
111
+ // Option 1: Calculate graduation cost first (recommended)
112
+ const calculation = await sdk.calculateBuyAmountForGraduation('dragnrkti');
113
+
114
+ console.log('GALA cost to graduate:', calculation.amount);
115
+ console.log('RBC Fee:', calculation.reverseBondingCurveFee);
116
+ console.log('Transaction fee:', calculation.transactionFee);
117
+
118
+ // Check if you have enough balance
119
+ const balance = await sdk.fetchGalaBalance();
120
+ if (parseFloat(balance.balance) < parseFloat(calculation.amount)) {
121
+ throw new Error('Insufficient GALA balance');
122
+ }
123
+
124
+ // Option 2: One-step graduation (convenience method)
125
+ const result = await sdk.graduateToken({
126
+ tokenName: 'dragnrkti',
127
+ slippageToleranceFactor: 0.01 // Optional: defaults to SDK config
128
+ });
129
+
130
+ console.log('Pool graduated!');
131
+ console.log('Transaction ID:', result.transactionId);
132
+ console.log('Total GALA spent:', result.inputAmount);
133
+ console.log('Tokens received:', result.outputAmount);
134
+ }
135
+ \`\`\`
136
+
137
+ **MCP Tool Equivalents:**
138
+ - \`gala_launchpad_calculate_buy_amount_for_graduation\`
139
+ - \`gala_launchpad_graduate_token\`
140
+ `,
141
+
142
+ 'fetch-pools': `
143
+ ## Fetching Pool Data with Advanced Methods
144
+
145
+ \`\`\`typescript
146
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
147
+
148
+ // 1. BASIC POOL FETCHING - With Pagination
149
+ async function basicPoolFetching() {
150
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
151
+
152
+ // Fetch recent pools with pagination
153
+ const pools = await sdk.fetchPools({
154
+ type: 'recent',
155
+ limit: 10,
156
+ page: 1
157
+ });
158
+
159
+ console.log(\`Found \${pools.total} pools, page \${pools.page} of \${pools.totalPages}\`);
160
+ pools.pools.forEach(pool => {
161
+ console.log(\`\${pool.tokenName}: \${pool.tokenSymbol}\`);
162
+ });
163
+ }
164
+
165
+ // 2. AUTO-PAGINATED FETCHING - Get ALL Pools
166
+ async function fetchAllPools() {
167
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
168
+
169
+ // Auto-paginated - returns all pools without manual pagination
170
+ const allPools = await sdk.fetchAllPools({
171
+ type: 'recent'
172
+ });
173
+
174
+ console.log(\`Total pools: \${allPools.pools.length}\`);
175
+ }
176
+
177
+ // 3. POOL DETAILS - Complete information
178
+ async function getPoolDetails(tokenName) {
179
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
180
+
181
+ const details = await sdk.fetchPoolDetails(tokenName);
182
+
183
+ console.log('Sale status:', details.saleStatus); // 'Ongoing' or 'Completed'
184
+ console.log('Base price:', details.basePrice);
185
+ console.log('Max supply:', details.maxSupply);
186
+ console.log('Remaining tokens:', details.sellingTokenQuantity);
187
+ }
188
+
189
+ // 4. POOL DETAILS FOR CALCULATIONS - Optimized for math
190
+ async function getOptimizedPoolDetails(tokenName) {
191
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
192
+
193
+ // Returns only fields needed for bonding curve calculations
194
+ const poolData = await sdk.fetchPoolDetailsForCalculation(tokenName);
195
+
196
+ console.log('Current supply:', poolData.currentSupply);
197
+ console.log('Remaining tokens:', poolData.remainingTokens);
198
+ console.log('Max supply:', poolData.maxSupply);
199
+ console.log('Reverse bonding curve max fee:', poolData.reverseBondingCurveMaxFeeFactor);
200
+ }
201
+
202
+ // 5. VOLUME & OHLCV DATA - Historical candlestick data
203
+ async function getVolumeData(tokenName) {
204
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
205
+
206
+ // Different resolutions: '1m', '5m', '15m', '1h', '4h', '1d'
207
+ const volumeData = await sdk.fetchVolumeData({
208
+ tokenName: tokenName,
209
+ from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // Last 7 days
210
+ to: new Date(),
211
+ resolution: '1h' // 1-hour candlesticks
212
+ });
213
+
214
+ volumeData.forEach(candle => {
215
+ console.log(\`\${candle.time}: O:\${candle.open} H:\${candle.high} L:\${candle.low} C:\${candle.close} V:\${candle.volume}\`);
216
+ });
217
+ }
218
+
219
+ // 6. SPOT PRICES - DEX tokens (GALA, SILK, MUSIC)
220
+ async function getDexTokenPrices() {
221
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
222
+
223
+ // Fetch prices for multiple DEX tokens
224
+ const prices = await sdk.fetchTokenSpotPrice(['GALA', 'SILK', 'MUSIC']);
225
+
226
+ console.log(\`GALA: \$\${prices.GALA}\`);
227
+ console.log(\`SILK: \$\${prices.SILK}\`);
228
+ console.log(\`MUSIC: \$\${prices.MUSIC}\`);
229
+ }
230
+
231
+ // 7. LAUNCHPAD TOKEN SPOT PRICES
232
+ async function getLaunchpadTokenPrice(tokenName) {
233
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
234
+
235
+ // Get USD spot price for a launchpad token (anime, woohoo, etc.)
236
+ const price = await sdk.fetchLaunchpadTokenSpotPrice(tokenName);
237
+
238
+ console.log(\`\${tokenName} price: \$\${price}\`);
239
+ }
240
+
241
+ // 8. RESOLVE UTILITY ADDRESSES
242
+ async function resolveAddresses(tokenName) {
243
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
244
+
245
+ // Get GalaChain vault address for token
246
+ const vaultAddress = await sdk.resolveVaultAddress(tokenName);
247
+ console.log(\`Vault address: \${vaultAddress}\`);
248
+
249
+ // Get TokenClassKey for token
250
+ const tokenClassKey = await sdk.resolveTokenClassKey(tokenName);
251
+ console.log(\`TokenClassKey: \${tokenClassKey}\`);
252
+ }
253
+
254
+ // 9. COMPLETE INVESTMENT ANALYSIS WORKFLOW
255
+ async function analyzeToken(tokenName) {
256
+ const sdk = createLaunchpadSDK({ wallet: 'your-private-key' });
257
+
258
+ // Get all token data in parallel
259
+ const [details, volumeData, distribution, badges] = await Promise.all([
260
+ sdk.fetchPoolDetails(tokenName),
261
+ sdk.fetchVolumeData({ tokenName, resolution: '1d' }),
262
+ sdk.fetchTokenDistribution(tokenName),
263
+ sdk.fetchTokenBadges(tokenName)
264
+ ]);
265
+
266
+ // Analyze status
267
+ console.log(\`Pool Status: \${details.saleStatus}\`);
268
+ console.log(\`Supply: \${details.currentSupply} / \${details.maxSupply}\`);
269
+
270
+ // Analyze volume trend
271
+ const volumes = volumeData.map(v => parseFloat(v.volume));
272
+ const avgVolume = volumes.reduce((a, b) => a + b, 0) / volumes.length;
273
+ console.log(\`Avg daily volume: \$\${avgVolume.toFixed(2)}\`);
274
+
275
+ // Analyze distribution
276
+ const top5Ownership = distribution.holders
277
+ .sort((a, b) => parseFloat(b.balance) - parseFloat(a.balance))
278
+ .slice(0, 5)
279
+ .reduce((sum, h) => sum + h.percentage, 0);
280
+ console.log(\`Top 5 holders: \${top5Ownership.toFixed(2)}%\`);
281
+
282
+ // Check badges
283
+ console.log(\`Badges: \${badges.join(', ')}\`);
284
+ }
285
+ \`\`\`
286
+
287
+ **MCP Tool Equivalents:**
288
+ - \`gala_launchpad_fetch_pools\` - Paginated pool list
289
+ - \`gala_launchpad_fetch_all_pools\` - Auto-paginated all pools
290
+ - \`gala_launchpad_fetch_pool_details\` - Complete pool information
291
+ - \`gala_launchpad_fetch_pool_details_for_calculation\` - Optimized for calculations
292
+ - \`gala_launchpad_fetch_volume_data\` - OHLCV candlestick data
293
+ - \`gala_launchpad_fetch_token_spot_price\` - DEX token prices (GALA, SILK, MUSIC)
294
+ - \`gala_launchpad_fetch_launchpad_token_spot_price\` - Launchpad token USD prices
295
+ - \`gala_launchpad_fetch_token_distribution\` - Token holder analysis
296
+ - \`gala_launchpad_fetch_token_badges\` - Achievement badges
297
+ - \`gala_launchpad_resolve_vault_address\` - Get vault address
298
+ - \`gala_launchpad_resolve_token_class_key\` - Get TokenClassKey
299
+ `,
300
+
301
+ 'balances': `
302
+ ## Checking Balances with SDK
303
+
304
+ \`\`\`typescript
305
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
306
+
307
+ async function checkBalances() {
308
+ const sdk = createLaunchpadSDK({
309
+ wallet: 'your-private-key'
310
+ });
311
+
312
+ // Check GALA balance
313
+ const galaBalance = await sdk.fetchGalaBalance();
314
+ console.log(\`GALA: \${galaBalance.balance}\`);
315
+ console.log(\`Decimals: \${galaBalance.decimals}\`);
316
+ console.log(\`Last updated: \${galaBalance.lastUpdated.toISOString()}\`);
317
+
318
+ // Check specific token balance
319
+ const tokenBalance = await sdk.fetchTokenBalance({
320
+ tokenName: 'dragnrkti',
321
+ address: sdk.getAddress()
322
+ });
323
+
324
+ console.log(\`Token: \${tokenBalance.quantity}\`);
325
+ console.log(\`USD value: $\${tokenBalance.holdingPriceUsd}\`);
326
+ console.log(\`GALA value: \${tokenBalance.holdingPriceGala}\`);
327
+
328
+ // Check all tokens held
329
+ const portfolio = await sdk.fetchTokensHeld({
330
+ address: sdk.getAddress(),
331
+ limit: 20
332
+ });
333
+
334
+ console.log(\`Holding \${portfolio.total} different tokens\`);
335
+ portfolio.tokens.forEach(token => {
336
+ console.log(\`\${token.name}: \${token.quantity}\`);
337
+ });
338
+
339
+ // Check tokens created by this wallet
340
+ const createdTokens = await sdk.fetchTokensCreated({
341
+ address: sdk.getAddress(),
342
+ limit: 10
343
+ });
344
+
345
+ console.log(\`Created \${createdTokens.total} tokens\`);
346
+ createdTokens.tokens.forEach(token => {
347
+ console.log(\` \${token.symbol}: \${token.name}\`);
348
+ });
349
+
350
+ // Get user profile
351
+ const profile = await sdk.fetchProfile();
352
+ console.log(\`Profile: \${profile.fullName}\`);
353
+
354
+ // Check profile of another user
355
+ const otherProfile = await sdk.fetchProfile('eth|0x...');
356
+ console.log(\`Other user: \${otherProfile.fullName}\`);
357
+ }
358
+ \`\`\`
359
+
360
+ **MCP Tool Equivalents:**
361
+ - \`gala_launchpad_fetch_gala_balance\`
362
+ - \`gala_launchpad_fetch_token_balance\`
363
+ - \`gala_launchpad_fetch_tokens_held\`
364
+ - \`gala_launchpad_fetch_tokens_created\`
365
+ - \`gala_launchpad_fetch_profile\`
366
+ `,
367
+
368
+ 'token-creation': `
369
+ ## Creating Tokens with SDK
370
+
371
+ \`\`\`typescript
372
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
373
+
374
+ async function launchToken() {
375
+ const sdk = createLaunchpadSDK({
376
+ wallet: 'your-private-key'
377
+ });
378
+
379
+ // 1. Check if name/symbol available
380
+ const nameAvailable = await sdk.isTokenNameAvailable('mytoken');
381
+ const symbolAvailable = await sdk.isTokenSymbolAvailable('MTK');
382
+
383
+ if (!nameAvailable || !symbolAvailable) {
384
+ throw new Error('Name or symbol already taken');
385
+ }
386
+
387
+ // 2. Check launch fee
388
+ const launchFee = await sdk.fetchLaunchTokenFee();
389
+ console.log(\`Launch fee: \${launchFee} GALA\`);
390
+
391
+ // 3. Upload token image (Node.js only)
392
+ const imageUpload = await sdk.uploadTokenImage({
393
+ tokenName: 'mytoken',
394
+ imagePath: '/path/to/image.png'
395
+ });
396
+
397
+ // 4. Launch the token
398
+ const result = await sdk.launchToken({
399
+ tokenName: 'mytoken',
400
+ tokenSymbol: 'MTK',
401
+ tokenDescription: 'My awesome token',
402
+ tokenImage: imageUpload.imageUrl,
403
+ websiteUrl: 'https://mytoken.com',
404
+ twitterUrl: 'https://twitter.com/mytoken',
405
+ preBuyQuantity: '100' // Optional: pre-buy with GALA
406
+ });
407
+
408
+ console.log('Token launched!');
409
+ console.log('Transaction ID:', result.transactionId);
410
+
411
+ // Get frontend URL
412
+ const url = sdk.getUrlByTokenName('mytoken');
413
+ console.log(\`View at: \${url}\`);
414
+ }
415
+ \`\`\`
416
+
417
+ **MCP Tool Equivalents:**
418
+ - \`gala_launchpad_check_token_name\`
419
+ - \`gala_launchpad_check_token_symbol\`
420
+ - \`gala_launchpad_fetch_launch_token_fee\`
421
+ - \`gala_launchpad_upload_token_image\`
422
+ - \`gala_launchpad_launch_token\`
423
+ - \`gala_launchpad_get_url_by_token_name\`
424
+ `,
425
+
426
+ 'multi-wallet': `
427
+ ## Multi-Wallet Support with SDK
428
+
429
+ \`\`\`typescript
430
+ import { createLaunchpadSDK, createWallet } from '@gala-chain/launchpad-sdk';
431
+
432
+ async function multiWalletExample() {
433
+ // Main SDK with your wallet
434
+ const sdk = createLaunchpadSDK({
435
+ wallet: 'your-main-private-key'
436
+ });
437
+
438
+ // Create a test wallet
439
+ const testWallet = createWallet();
440
+ console.log('Test wallet:', testWallet.address);
441
+
442
+ // 1. Fund test wallet from main wallet
443
+ await sdk.transferGala({
444
+ recipientAddress: testWallet.address,
445
+ amount: '1000'
446
+ });
447
+
448
+ // 2. Have test wallet buy tokens (using privateKey override)
449
+ const buyCalc = await sdk.calculateBuyAmount({
450
+ tokenName: 'dragnrkti',
451
+ amount: '100',
452
+ type: 'native'
453
+ });
454
+
455
+ const buyResult = await sdk.buy({
456
+ tokenName: 'dragnrkti',
457
+ amount: '100',
458
+ type: 'native',
459
+ expectedAmount: buyCalc.amount,
460
+ slippageToleranceFactor: 0.01,
461
+ privateKey: testWallet.privateKey // Override to use test wallet
462
+ });
463
+
464
+ console.log('Test wallet bought tokens');
465
+
466
+ // 3. Have test wallet post comment
467
+ await sdk.postComment({
468
+ tokenName: 'dragnrkti',
469
+ content: 'Great project!',
470
+ privateKey: testWallet.privateKey // Test wallet posts
471
+ });
472
+
473
+ // 4. Check balances for both wallets
474
+ const mainBalance = await sdk.fetchGalaBalance(); // Main wallet
475
+ const testBalance = await sdk.fetchGalaBalance(testWallet.address); // Test wallet
476
+
477
+ console.log(\`Main wallet: \${mainBalance.balance} GALA\`);
478
+ console.log(\`Test wallet: \${testBalance.balance} GALA\`);
479
+ }
480
+ \`\`\`
481
+
482
+ **Key Points:**
483
+ - All signing operations support \`privateKey\` parameter
484
+ - Creates temporary SDK instance internally
485
+ - Supports: buy, sell, launchToken, transfers, comments, profile updates
486
+ `,
487
+
488
+ 'transfers': `
489
+ ## Token Transfers with SDK
490
+
491
+ \`\`\`typescript
492
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
493
+
494
+ async function transferTokens() {
495
+ const sdk = createLaunchpadSDK({
496
+ wallet: 'your-private-key'
497
+ });
498
+
499
+ // Transfer GALA tokens
500
+ const galaTransfer = await sdk.transferGala({
501
+ recipientAddress: '0x1234...', // or 'eth|1234...'
502
+ amount: '100',
503
+ uniqueKey: 'galaconnect-operation-my-transfer-123' // Optional idempotency
504
+ });
505
+
506
+ console.log('GALA transfer ID:', galaTransfer.transactionId);
507
+ console.log('Status:', galaTransfer.status);
508
+
509
+ // Transfer launchpad tokens
510
+ const tokenTransfer = await sdk.transferToken({
511
+ to: 'eth|5678...',
512
+ tokenName: 'dragnrkti',
513
+ amount: '1000', // Token amount
514
+ uniqueKey: 'galaconnect-operation-token-456'
515
+ });
516
+
517
+ console.log('Token transfer ID:', tokenTransfer.transactionId);
518
+ }
519
+ \`\`\`
520
+
521
+ **Features:**
522
+ - EIP-712 signatures for security
523
+ - Supports both \`0x\` and \`eth|\` address formats
524
+ - Optional idempotency keys prevent duplicates
525
+ - Comprehensive validation
526
+
527
+ **MCP Tool Equivalents:**
528
+ - \`gala_launchpad_transfer_gala\`
529
+ - \`gala_launchpad_transfer_token\`
530
+ `,
531
+
532
+ 'error-handling': `
533
+ ## Error Handling with SDK
534
+
535
+ \`\`\`typescript
536
+ import {
537
+ createLaunchpadSDK,
538
+ ValidationError,
539
+ NetworkError,
540
+ TransactionError,
541
+ TokenNotFoundError
542
+ } from '@gala-chain/launchpad-sdk';
543
+
544
+ async function errorHandlingExample() {
545
+ const sdk = createLaunchpadSDK({
546
+ wallet: 'your-private-key'
547
+ });
548
+
549
+ try {
550
+ // Attempt trade
551
+ const result = await sdk.buy({
552
+ tokenName: 'dragnrkti',
553
+ amount: '100',
554
+ type: 'native',
555
+ expectedAmount: '5000',
556
+ slippageToleranceFactor: 0.01
557
+ });
558
+
559
+ console.log('Success:', result.transactionId);
560
+
561
+ } catch (error) {
562
+ if (error instanceof ValidationError) {
563
+ console.error('Invalid input:', error.message);
564
+ console.error('Field:', error.field);
565
+ console.error('Code:', error.code);
566
+
567
+ } else if (error instanceof TokenNotFoundError) {
568
+ console.error('Token does not exist:', error.tokenName);
569
+
570
+ } else if (error instanceof NetworkError) {
571
+ console.error('Network issue:', error.message);
572
+ console.error('Status code:', error.statusCode);
573
+
574
+ } else if (error instanceof TransactionError) {
575
+ console.error('Transaction failed:', error.message);
576
+ console.error('Transaction ID:', error.transactionId);
577
+
578
+ } else {
579
+ console.error('Unexpected error:', error);
580
+ }
581
+ }
582
+ }
583
+ \`\`\`
584
+
585
+ **Error Types:**
586
+ - \`ValidationError\` - Invalid input parameters
587
+ - \`NetworkError\` - HTTP/network failures
588
+ - \`TransactionError\` - Blockchain transaction failures
589
+ - \`TokenNotFoundError\` - Token doesn't exist
590
+ - \`ConfigurationError\` - SDK misconfiguration
591
+ - \`WebSocketError\` - Real-time connection issues
592
+ `,
593
+
594
+ 'installation': `
595
+ ## Installing and Importing SDK
596
+
597
+ ### NPM Installation
598
+
599
+ \`\`\`bash
600
+ # Install SDK
601
+ npm install @gala-chain/launchpad-sdk
602
+
603
+ # Install peer dependencies
604
+ npm install ethers@^6.15.0 @gala-chain/api@^2.4.3 @gala-chain/connect@^2.4.3 \\
605
+ socket.io-client@^4.8.1 axios@^1.12.2 bignumber.js@^9.1.2 zod@^3.25.76
606
+ \`\`\`
607
+
608
+ ### Import Patterns
609
+
610
+ \`\`\`typescript
611
+ // Main SDK class
612
+ import { LaunchpadSDK } from '@gala-chain/launchpad-sdk';
613
+
614
+ // Helper functions (recommended)
615
+ import {
616
+ createLaunchpadSDK,
617
+ createTestLaunchpadSDK,
618
+ createWallet,
619
+ validateWalletInput
620
+ } from '@gala-chain/launchpad-sdk';
621
+
622
+ // Error types
623
+ import {
624
+ ValidationError,
625
+ NetworkError,
626
+ TransactionError,
627
+ TokenNotFoundError
628
+ } from '@gala-chain/launchpad-sdk';
629
+
630
+ // Type definitions
631
+ import type {
632
+ PoolData,
633
+ TradeResult,
634
+ TokenBalanceInfo,
635
+ BuyTokenOptions,
636
+ SellTokenOptions
637
+ } from '@gala-chain/launchpad-sdk';
638
+ \`\`\`
639
+
640
+ ### Environment Configuration
641
+
642
+ \`\`\`typescript
643
+ // Development (default)
644
+ const sdk = createLaunchpadSDK({
645
+ wallet: 'your-private-key',
646
+ config: {
647
+ baseUrl: 'https://lpad-backend-dev1.defi.gala.com',
648
+ debug: true
649
+ }
650
+ });
651
+
652
+ // Production
653
+ const sdk = createLaunchpadSDK({
654
+ wallet: 'your-private-key',
655
+ config: {
656
+ baseUrl: 'https://lpad-backend-prod1.defi.gala.com',
657
+ debug: false,
658
+ timeout: 60000
659
+ }
660
+ });
661
+ \`\`\`
662
+ `,
663
+
664
+ 'local-calculations': `
665
+ ## Local Bonding Curve Calculations with SDK
666
+
667
+ \`\`\`typescript
668
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
669
+
670
+ async function localCalculationsExample() {
671
+ const sdk = createLaunchpadSDK({
672
+ wallet: 'your-private-key'
673
+ });
674
+
675
+ // ============================================================================
676
+ // LOCAL CALCULATIONS - Instant quotes without network calls
677
+ // ============================================================================
678
+
679
+ // 1. Buy calculation (local, instant)
680
+ const localBuy = await sdk.calculateBuyAmountLocal({
681
+ tokenName: 'dragnrkti',
682
+ amount: '100', // Spending 100 GALA
683
+ type: 'native' // 'native' = GALA amount, 'exact' = token amount
684
+ });
685
+
686
+ console.log('LOCAL Buy Quote (instant):');
687
+ console.log(' Tokens received:', localBuy.amount);
688
+ console.log(' Transaction fee:', localBuy.transactionFee);
689
+ console.log(' RBC Fee:', localBuy.reverseBondingCurveFee); // Always "0" for buys
690
+ console.log(' Gas fee:', localBuy.gasFee);
691
+
692
+ // 2. Sell calculation (local, requires pool details)
693
+ const poolDetails = await sdk.fetchPoolDetails('dragnrkti');
694
+
695
+ const localSell = await sdk.calculateSellAmountLocal({
696
+ tokenName: 'dragnrkti',
697
+ amount: '1000', // Selling 1000 tokens
698
+ type: 'exact',
699
+ // Required parameters from pool details:
700
+ maxSupply: poolDetails.maxSupply.toString(),
701
+ minFeePortion: poolDetails.reverseBondingCurveMinFeeFactor || 0,
702
+ maxFeePortion: poolDetails.reverseBondingCurveMaxFeeFactor || 0
703
+ });
704
+
705
+ console.log('LOCAL Sell Quote (instant):');
706
+ console.log(' GALA received:', localSell.amount);
707
+ console.log(' RBC Fee:', localSell.reverseBondingCurveFee);
708
+ console.log(' Transaction fee:', localSell.transactionFee);
709
+
710
+ // ============================================================================
711
+ // EXTERNAL CALCULATIONS - Real-time network queries (explicit)
712
+ // ============================================================================
713
+
714
+ // 3. External buy (explicit network call)
715
+ const externalBuy = await sdk.calculateBuyAmountExternal({
716
+ tokenName: 'dragnrkti',
717
+ amount: '100',
718
+ type: 'native'
719
+ });
720
+
721
+ console.log('EXTERNAL Buy Quote (network):');
722
+ console.log(' Tokens received:', externalBuy.amount);
723
+
724
+ // 4. External sell (explicit network call)
725
+ const externalSell = await sdk.calculateSellAmountExternal({
726
+ tokenName: 'dragnrkti',
727
+ amount: '1000',
728
+ type: 'exact'
729
+ });
730
+
731
+ console.log('EXTERNAL Sell Quote (network):');
732
+ console.log(' GALA received:', externalSell.amount);
733
+
734
+ // ============================================================================
735
+ // A/B COMPARISON - Verify local accuracy
736
+ // ============================================================================
737
+
738
+ const buyDiff = Math.abs(parseFloat(localBuy.amount) - parseFloat(externalBuy.amount));
739
+ const buyPct = (buyDiff / parseFloat(externalBuy.amount)) * 100;
740
+
741
+ console.log('Local vs External Accuracy:');
742
+ console.log(\` Buy difference: \${buyPct.toFixed(4)}% (should be <0.01%)\`);
743
+
744
+ // ============================================================================
745
+ // PERFORMANCE BENEFIT - Local is instant
746
+ // ============================================================================
747
+
748
+ console.time('Local calculation');
749
+ await sdk.calculateBuyAmountLocal({ tokenName: 'dragnrkti', amount: '100', type: 'native' });
750
+ console.timeEnd('Local calculation'); // ~0ms (instant)
751
+
752
+ console.time('External calculation');
753
+ await sdk.calculateBuyAmountExternal({ tokenName: 'dragnrkti', amount: '100', type: 'native' });
754
+ console.timeEnd('External calculation'); // ~200-500ms (network roundtrip)
755
+ }
756
+ \`\`\`
757
+
758
+ **Benefits of Local Calculations:**
759
+ - ✅ Instant quotes (no network delay)
760
+ - ✅ Offline support (no internet required)
761
+ - ✅ No API rate limits
762
+ - ✅ Perfect accuracy (<0.01% difference)
763
+ - ✅ Reduced server load
764
+
765
+ **When to Use:**
766
+ - Local: Price discovery, UI updates, offline scenarios
767
+ - External: Production trades (always verify before executing)
768
+
769
+ **MCP Tool Equivalents:**
770
+ - \`gala_launchpad_calculate_buy_amount_local\`
771
+ - \`gala_launchpad_calculate_buy_amount_external\`
772
+ - \`gala_launchpad_calculate_sell_amount_local\`
773
+ - \`gala_launchpad_calculate_sell_amount_external\`
774
+ `,
775
+
776
+ 'price-history': `
777
+ ## Historical Price Analysis with SDK
778
+
779
+ \`\`\`typescript
780
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
781
+
782
+ async function analyzePriceHistory() {
783
+ const sdk = createLaunchpadSDK({
784
+ wallet: 'your-private-key-or-mnemonic'
785
+ });
786
+
787
+ // Paginated price history
788
+ const history = await sdk.fetchPriceHistory({
789
+ tokenId: 'Token|Unit|GUSDC|eth:0x...',
790
+ from: new Date('2025-01-01'),
791
+ to: new Date('2025-01-31'),
792
+ sortOrder: 'DESC',
793
+ page: 1,
794
+ limit: 50
795
+ });
796
+
797
+ console.log(\`Found \${history.snapshots.length} snapshots\`);
798
+ console.log(\`Total available: \${history.total} (page \${history.page} of \${history.totalPages})\`);
799
+
800
+ // Auto-paginated complete history
801
+ const allHistory = await sdk.fetchAllPriceHistory({
802
+ tokenId: 'GWETH|Unit|none|none',
803
+ from: new Date('2024-01-01'),
804
+ sortOrder: 'ASC'
805
+ });
806
+
807
+ // Price analysis
808
+ const prices = allHistory.snapshots.map(s => parseFloat(s.price));
809
+ const avg = prices.reduce((a, b) => a + b, 0) / prices.length;
810
+ const variance = prices.reduce((sum, p) => sum + Math.pow(p - avg, 2), 0) / prices.length;
811
+ const volatility = Math.sqrt(variance);
812
+
813
+ console.log(\`Average: \$\${avg.toFixed(4)}, Volatility: \$\${volatility.toFixed(4)}\`);
814
+
815
+ // Data export (CSV)
816
+ const csv = ['timestamp,price'].concat(
817
+ allHistory.snapshots.map(s => \`\${s.timestamp.toISOString()},\${s.price}\`)
818
+ ).join('\\n');
819
+
820
+ console.log('CSV export:', csv.split('\\n').slice(0, 3).join('\\n'));
821
+ }
822
+ \`\`\`
823
+
824
+ **Key Methods:**
825
+ - \`fetchPriceHistory()\` - Paginated historical prices (max 50 per page)
826
+ - \`fetchAllPriceHistory()\` - Auto-paginated complete history (all snapshots)
827
+
828
+ **Response Fields:**
829
+ - \`price\` - Token price as decimal string
830
+ - \`timestamp\` - ISO 8601 timestamp
831
+ - \`tokenId\` - Token identifier (pipe-delimited)
832
+
833
+ **Use Cases:**
834
+ - Technical analysis and charting
835
+ - Volatility assessment
836
+ - Price trend identification
837
+ - Data export for analytics
838
+ - Backtesting strategies
839
+
840
+ **Token ID Formats:**
841
+ - String: \`Token|Unit|GUSDC|eth:0x...\`
842
+ - Object: \`{ collection, category, type, additionalKey }\`
843
+
844
+ **MCP Tool Equivalents:**
845
+ - \`gala_launchpad_fetch_price_history\` - Paginated
846
+ - \`gala_launchpad_fetch_all_price_history\` - Auto-paginated
847
+ `,
848
+
849
+ 'token-details': `
850
+ ## Token Details and Metadata with SDK
851
+
852
+ \`\`\`typescript
853
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
854
+
855
+ async function analyzeTokenDetails() {
856
+ const sdk = createLaunchpadSDK({
857
+ wallet: 'your-private-key-or-mnemonic'
858
+ });
859
+
860
+ // Fetch token metadata
861
+ const details = await sdk.fetchTokenDetails('Token|Unit|GUSDC|eth:0x...');
862
+
863
+ console.log('Token Information:');
864
+ console.log(\` Name: \${details.name}\`);
865
+ console.log(\` Symbol: \${details.symbol}\`);
866
+ console.log(\` Decimals: \${details.decimals}\`);
867
+ console.log(\` Verified: \${details.verified}\`);
868
+ console.log(\` Trading: \${details.tradingEnabled}\`);
869
+ console.log(\` Network: \${details.network}\`);
870
+ console.log(\` Image: \${details.image}\`);
871
+
872
+ // Pre-trading validation
873
+ async function validateBeforeTrade(tokenId: string) {
874
+ const token = await sdk.fetchTokenDetails(tokenId);
875
+
876
+ if (!token.verified) {
877
+ console.warn(\`⚠️ \${token.symbol} is NOT verified\`);
878
+ }
879
+
880
+ if (!token.tradingEnabled) {
881
+ throw new Error(\`Trading disabled for \${token.symbol}\`);
882
+ }
883
+
884
+ if (token.network !== 'ethereum') {
885
+ throw new Error(\`Wrong network: got \${token.network}\`);
886
+ }
887
+
888
+ return token;
889
+ }
890
+
891
+ // Batch token comparison
892
+ const tokens = ['GALA|Unit|none|none', 'Token|Unit|GUSDC|eth:0x...'];
893
+ const details_list = await Promise.all(
894
+ tokens.map(id => sdk.fetchTokenDetails(id).catch(() => null))
895
+ );
896
+
897
+ const verified = details_list.filter(t => t?.verified).length;
898
+ console.log(\`Verified tokens: \${verified}/\${tokens.length}\`);
899
+ }
900
+ \`\`\`
901
+
902
+ **Response Fields:**
903
+ - \`symbol\` - Token symbol (e.g., 'GUSDC')
904
+ - \`name\` - Full token name
905
+ - \`decimals\` - Decimal places
906
+ - \`verified\` - Verification status
907
+ - \`tradingEnabled\` - Trading availability
908
+ - \`network\` - Network name (e.g., 'ethereum')
909
+ - \`contractAddress\` - Smart contract address
910
+ - \`image\` - Token image URL
911
+ - \`chainId\` - Blockchain chain ID
912
+
913
+ **Use Cases:**
914
+ - Pre-trading validation and safety checks
915
+ - Display token metadata in UI
916
+ - Verify token authenticity
917
+ - Network compatibility checking
918
+
919
+ **Token ID Formats:**
920
+ - String: \`Token|Unit|GUSDC|eth:0x...\`
921
+ - Object: \`{ collection, category, type, additionalKey }\`
922
+
923
+ **MCP Tool Equivalent:** \`gala_launchpad_fetch_token_details\`
924
+ `,
925
+
926
+ 'profile-management': `
927
+ ## User Profile Management with SDK
928
+
929
+ \`\`\`typescript
930
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
931
+
932
+ async function manageUserProfiles() {
933
+ const sdk = createLaunchpadSDK({
934
+ wallet: 'your-private-key-or-mnemonic'
935
+ });
936
+
937
+ // Fetch current user profile
938
+ const myProfile = await sdk.fetchProfile();
939
+ console.log(\`Name: \${myProfile.fullName}\`);
940
+ console.log(\`Avatar: \${myProfile.profileImage}\`);
941
+
942
+ // Fetch another user's profile
943
+ const other = await sdk.fetchProfile('eth|0x...');
944
+ console.log(\`Other user: \${other.fullName}\`);
945
+
946
+ // Update profile
947
+ const updated = await sdk.updateProfile({
948
+ fullName: 'Satoshi Nakamoto',
949
+ profileImage: 'https://example.com/avatar.png',
950
+ address: sdk.getAddress()
951
+ });
952
+
953
+ console.log(\`Updated: \${updated.fullName}\`);
954
+
955
+ // Upload profile image (Node.js only)
956
+ const imgResult = await sdk.uploadProfileImage({
957
+ imagePath: '/path/to/avatar.png'
958
+ });
959
+
960
+ // Update with uploaded image
961
+ await sdk.updateProfile({
962
+ fullName: 'My Name',
963
+ profileImage: imgResult.imageUrl,
964
+ address: sdk.getAddress()
965
+ });
966
+
967
+ // Complete workflow: Update profile, then launch token
968
+ async function createTokenWithProfile() {
969
+ const avatar = await sdk.uploadProfileImage({
970
+ imagePath: '/path/to/pic.png'
971
+ });
972
+
973
+ await sdk.updateProfile({
974
+ fullName: 'Token Creator',
975
+ profileImage: avatar.imageUrl,
976
+ address: sdk.getAddress()
977
+ });
978
+
979
+ const logo = await sdk.uploadTokenImage({
980
+ tokenName: 'mytoken',
981
+ imagePath: '/path/to/logo.png'
982
+ });
983
+
984
+ const result = await sdk.launchToken({
985
+ tokenName: 'mytoken',
986
+ tokenSymbol: 'MTK',
987
+ tokenDescription: 'Awesome token',
988
+ tokenImage: logo.imageUrl,
989
+ websiteUrl: 'https://mytoken.com'
990
+ });
991
+
992
+ return result;
993
+ }
994
+
995
+ // Batch profile fetching
996
+ const addresses = ['eth|0xaddress1', 'eth|0xaddress2'];
997
+ const profiles = await Promise.all(
998
+ addresses.map(addr => sdk.fetchProfile(addr).catch(() => null))
999
+ );
1000
+
1001
+ console.log('Profiles:', profiles.filter(p => p).map(p => p.fullName));
1002
+ }
1003
+ \`\`\`
1004
+
1005
+ **Profile Methods:**
1006
+ - \`fetchProfile(address?)\` - Get user profile
1007
+ - \`updateProfile(data)\` - Update profile info
1008
+ - \`uploadProfileImage(options)\` - Upload avatar (Node.js)
1009
+
1010
+ **Profile Fields:**
1011
+ - \`fullName\` - Display name (max 100 chars)
1012
+ - \`profileImage\` - Avatar image URL
1013
+ - \`address\` - Wallet address
1014
+ - \`createdAt\` - Creation date
1015
+ - \`updatedAt\` - Update timestamp
1016
+
1017
+ **Use Cases:**
1018
+ - Display user profiles
1019
+ - Allow profile customization
1020
+ - Manage profile images
1021
+ - Token creator attribution
1022
+ - Multi-wallet profiles
1023
+
1024
+ **MCP Tool Equivalents:**
1025
+ - \`gala_launchpad_fetch_profile\`
1026
+ - \`gala_launchpad_update_profile\`
1027
+ - \`gala_launchpad_upload_profile_image\`
1028
+ `,
1029
+
1030
+ 'token-distribution': `
1031
+ ## Token Holder Distribution with SDK
1032
+
1033
+ \`\`\`typescript
1034
+ import { createLaunchpadSDK } from '@gala-chain/launchpad-sdk';
1035
+
1036
+ async function analyzeTokenDistribution() {
1037
+ const sdk = createLaunchpadSDK({
1038
+ wallet: 'your-private-key-or-mnemonic'
1039
+ });
1040
+
1041
+ // Fetch complete token distribution (all holders, non-paginated)
1042
+ const distribution = await sdk.fetchTokenDistribution('anime');
1043
+
1044
+ console.log(\`Total holders: \${distribution.totalHolders}\`);
1045
+ console.log(\`Total supply: \${distribution.totalSupply}\`);
1046
+ console.log(\`Last updated: \${distribution.lastUpdated.toISOString()}\`);
1047
+
1048
+ // Analyze top holders
1049
+ distribution.holders
1050
+ .sort((a, b) => parseFloat(b.balance) - parseFloat(a.balance))
1051
+ .slice(0, 5)
1052
+ .forEach((holder, index) => {
1053
+ console.log(\`#\${index + 1}: \${holder.address}\`);
1054
+ console.log(\` Balance: \${holder.balance}\`);
1055
+ console.log(\` Ownership: \${holder.percentage.toFixed(2)}%\`);
1056
+ });
1057
+
1058
+ // Check concentration risk (e.g., top 5 holders own >80%)
1059
+ const top5Ownership = distribution.holders
1060
+ .sort((a, b) => parseFloat(b.balance) - parseFloat(a.balance))
1061
+ .slice(0, 5)
1062
+ .reduce((sum, holder) => sum + holder.percentage, 0);
1063
+
1064
+ console.log(\`Top 5 holders control: \${top5Ownership.toFixed(2)}%\`);
1065
+
1066
+ // Find specific holder
1067
+ const myAddress = sdk.getAddress();
1068
+ const myHolding = distribution.holders.find(h => h.address === myAddress);
1069
+
1070
+ if (myHolding) {
1071
+ console.log(\`Your ownership: \${myHolding.percentage.toFixed(4)}%\`);
1072
+ console.log(\`Your balance: \${myHolding.balance}\`);
1073
+ }
1074
+
1075
+ // Calculate concentration metrics
1076
+ const giniCoefficient = calculateGini(distribution.holders);
1077
+ console.log(\`Gini coefficient: \${giniCoefficient.toFixed(4)}\`);
1078
+
1079
+ // Count whales (holders with >5%)
1080
+ const whales = distribution.holders.filter(h => h.percentage > 5);
1081
+ console.log(\`Whales (>5%): \${whales.length}\`);
1082
+ }
1083
+
1084
+ // Helper: Calculate Gini coefficient for wealth distribution
1085
+ function calculateGini(holders: Array<{balance: string}>) {
1086
+ const balances = holders.map(h => parseFloat(h.balance)).sort((a, b) => a - b);
1087
+ const n = balances.length;
1088
+ const sum = balances.reduce((a, b) => a + b, 0);
1089
+
1090
+ let numerator = 0;
1091
+ for (let i = 0; i < n; i++) {
1092
+ numerator += (2 * (i + 1) - n - 1) * balances[i];
1093
+ }
1094
+
1095
+ return numerator / (n * sum);
1096
+ }
1097
+ \`\`\`
1098
+
1099
+ **Key Characteristics:**
1100
+ - **Non-Paginated**: Returns ALL token holders in single response (no pagination)
1101
+ - **Complete Distribution**: Full holder list with addresses, balances, and ownership percentages
1102
+ - **BigNumber Precision**: Uses BigNumber.js for accurate percentage calculations
1103
+ - **Total Supply**: Computed from holder balances (sum of all holdings)
1104
+ - **Service Account Included**: Vault/service accounts appear in holder list
1105
+
1106
+ **Use Cases:**
1107
+ - Analyze token concentration risk
1108
+ - Identify whale holders
1109
+ - Track ownership changes over time
1110
+ - Generate holder reports
1111
+ - Calculate distribution metrics (Gini coefficient, etc.)
1112
+
1113
+ **MCP Tool Equivalent:** \`gala_launchpad_fetch_token_distribution\`
1114
+ `,
1115
+
1116
+ 'mcp-to-sdk-mapping': `
1117
+ ## MCP Tool to SDK Method Mapping
1118
+
1119
+ ### Trading Operations
1120
+ | MCP Tool | SDK Method | Notes |
1121
+ |----------|------------|-------|
1122
+ | \`gala_launchpad_calculate_buy_amount\` | \`sdk.calculateBuyAmount(options)\` | Get quote before buying |
1123
+ | \`gala_launchpad_calculate_buy_amount_local\` | \`sdk.calculateBuyAmountLocal(options)\` | Local instant quote (buy) |
1124
+ | \`gala_launchpad_calculate_buy_amount_external\` | \`sdk.calculateBuyAmountExternal(options)\` | Explicit network quote (buy) |
1125
+ | \`gala_launchpad_calculate_sell_amount\` | \`sdk.calculateSellAmount(options)\` | Get quote before selling |
1126
+ | \`gala_launchpad_calculate_sell_amount_local\` | \`sdk.calculateSellAmountLocal(options)\` | Local instant quote (sell) |
1127
+ | \`gala_launchpad_calculate_sell_amount_external\` | \`sdk.calculateSellAmountExternal(options)\` | Explicit network quote (sell) |
1128
+ | \`gala_launchpad_buy_tokens\` | \`sdk.buy(options)\` | Execute token purchase |
1129
+ | \`gala_launchpad_sell_tokens\` | \`sdk.sell(options)\` | Execute token sale |
1130
+ | \`gala_launchpad_calculate_buy_amount_for_graduation\` | \`sdk.calculateBuyAmountForGraduation(options)\` | Calculate graduation cost |
1131
+ | \`gala_launchpad_graduate_token\` | \`sdk.graduateToken(options)\` | One-step pool graduation |
1132
+ | \`gala_launchpad_fetch_trades\` | \`sdk.fetchTrades(options)\` | Get trade history |
1133
+ | \`gala_launchpad_get_bundler_transaction_result\` | \`sdk.getBundlerTransactionResult(txId)\` | Get transaction result |
1134
+
1135
+ ### Pool Management
1136
+ | MCP Tool | SDK Method | Notes |
1137
+ |----------|------------|-------|
1138
+ | \`gala_launchpad_fetch_pools\` | \`sdk.fetchPools(options)\` | List pools with filtering |
1139
+ | \`gala_launchpad_fetch_all_pools\` | \`sdk.fetchAllPools(options)\` | Auto-paginated all pools |
1140
+ | \`gala_launchpad_fetch_pool_details\` | \`sdk.fetchPoolDetails(tokenName)\` | Get specific pool data |
1141
+ | \`gala_launchpad_fetch_pool_details_for_calculation\` | \`sdk.fetchPoolDetailsForCalculation(tokenName)\` | Optimized for calculations |
1142
+ | \`gala_launchpad_fetch_token_distribution\` | \`sdk.fetchTokenDistribution(tokenName)\` | Holder distribution |
1143
+ | \`gala_launchpad_fetch_token_badges\` | \`sdk.fetchTokenBadges(tokenName)\` | Achievement badges |
1144
+ | \`gala_launchpad_fetch_volume_data\` | \`sdk.fetchVolumeData(options)\` | OHLCV candlestick data |
1145
+ | \`gala_launchpad_fetch_token_spot_price\` | \`sdk.fetchTokenSpotPrice(symbols)\` | DEX token spot prices |
1146
+ | \`gala_launchpad_fetch_launchpad_token_spot_price\` | \`sdk.fetchLaunchpadTokenSpotPrice(options)\` | Launchpad token price |
1147
+ | \`gala_launchpad_resolve_vault_address\` | \`sdk.resolveVaultAddress(tokenName)\` | Get vault address |
1148
+ | \`gala_launchpad_resolve_token_class_key\` | \`sdk.resolveTokenClassKey(tokenName)\` | Get TokenClassKey |
1149
+ | \`gala_launchpad_fetch_token_details\` | \`sdk.fetchTokenDetails(tokenId)\` | Comprehensive token metadata |
1150
+
1151
+ ### Price History & Analysis
1152
+ | MCP Tool | SDK Method | Notes |
1153
+ |----------|------------|-------|
1154
+ | \`gala_launchpad_fetch_price_history\` | \`sdk.fetchPriceHistory(options)\` | Paginated price snapshots |
1155
+ | \`gala_launchpad_fetch_all_price_history\` | \`sdk.fetchAllPriceHistory(options)\` | Auto-paginated all prices |
1156
+
1157
+ ### Balance & Portfolio
1158
+ | MCP Tool | SDK Method | Notes |
1159
+ |----------|------------|-------|
1160
+ | \`gala_launchpad_fetch_gala_balance\` | \`sdk.fetchGalaBalance(address?)\` | GALA balance |
1161
+ | \`gala_launchpad_fetch_token_balance\` | \`sdk.fetchTokenBalance(options)\` | Specific token balance |
1162
+ | \`gala_launchpad_fetch_tokens_held\` | \`sdk.fetchTokensHeld(options)\` | Portfolio holdings |
1163
+ | \`gala_launchpad_fetch_tokens_created\` | \`sdk.fetchTokensCreated(options)\` | Created tokens |
1164
+ | \`gala_launchpad_fetch_profile\` | \`sdk.fetchProfile(address?)\` | User profile |
1165
+ | \`gala_launchpad_update_profile\` | \`sdk.updateProfile(data)\` | Update profile |
1166
+ | \`gala_launchpad_upload_profile_image\` | \`sdk.uploadProfileImage(options)\` | Upload avatar |
1167
+
1168
+ ### Profile Management
1169
+ | MCP Tool | SDK Method | Notes |
1170
+ |----------|------------|-------|
1171
+ | \`gala_launchpad_fetch_profile\` | \`sdk.fetchProfile(address?)\` | Get user profile |
1172
+ | \`gala_launchpad_update_profile\` | \`sdk.updateProfile(data)\` | Update profile info |
1173
+ | \`gala_launchpad_upload_profile_image\` | \`sdk.uploadProfileImage(options)\` | Upload profile image |
1174
+
1175
+ ### Token Creation
1176
+ | MCP Tool | SDK Method | Notes |
1177
+ |----------|------------|-------|
1178
+ | \`gala_launchpad_fetch_launch_token_fee\` | \`sdk.fetchLaunchTokenFee()\` | Get launch cost |
1179
+ | \`gala_launchpad_check_token_name\` | \`sdk.isTokenNameAvailable(name)\` | Check name |
1180
+ | \`gala_launchpad_check_token_symbol\` | \`sdk.isTokenSymbolAvailable(symbol)\` | Check symbol |
1181
+ | \`gala_launchpad_launch_token\` | \`sdk.launchToken(data)\` | Create token |
1182
+ | \`gala_launchpad_upload_token_image\` | \`sdk.uploadTokenImage(options)\` | Upload image |
1183
+
1184
+ ### Transfers & Social
1185
+ | MCP Tool | SDK Method | Notes |
1186
+ |----------|------------|-------|
1187
+ | \`gala_launchpad_transfer_gala\` | \`sdk.transferGala(options)\` | Transfer GALA |
1188
+ | \`gala_launchpad_transfer_token\` | \`sdk.transferToken(options)\` | Transfer tokens |
1189
+ | \`gala_launchpad_post_comment\` | \`sdk.postComment(options)\` | Post comment |
1190
+ | \`gala_launchpad_fetch_comments\` | \`sdk.fetchComments(options)\` | Get comments |
1191
+
1192
+ ### Utilities
1193
+ | MCP Tool | SDK Method | Notes |
1194
+ |----------|------------|-------|
1195
+ | \`gala_launchpad_create_wallet\` | \`createWallet()\` | Generate wallet |
1196
+ | \`gala_launchpad_get_address\` | \`sdk.getAddress()\` | Get backend format |
1197
+ | \`gala_launchpad_get_ethereum_address\` | \`sdk.getEthereumAddress()\` | Get 0x format |
1198
+ | \`gala_launchpad_get_url_by_token_name\` | \`sdk.getUrlByTokenName(name)\` | Frontend URL |
1199
+ | \`gala_launchpad_is_token_graduated\` | \`sdk.isTokenGraduated(tokenName)\` | Check if pool completed |
1200
+
1201
+ **Key Difference:** MCP tools return \`{ success: true, data: {...} }\`, SDK methods return direct result objects.
1202
+ `,
1203
+ };
1204
+
1205
+ /**
1206
+ * SDK Usage Explanation Tool
1207
+ */
1208
+ export const explainSdkUsageTool: MCPTool = {
1209
+ name: 'gala_launchpad_explain_sdk_usage',
1210
+ description: `Get detailed SDK code examples and explanations for using the Gala Launchpad SDK directly.
1211
+
1212
+ This tool provides complete, working code examples showing how to use the SDK instead of MCP tools.
1213
+ Perfect for developers who want to integrate the SDK into their applications.
1214
+
1215
+ Available topics:
1216
+ - 'buy-tokens' - Complete buying workflow with calculation and execution
1217
+ - 'sell-tokens' - Complete selling workflow with slippage protection
1218
+ - 'pool-graduation' - Graduate a bonding curve pool
1219
+ - 'fetch-pools' - Query pool data and details
1220
+ - 'balances' - Check GALA and token balances
1221
+ - 'price-history' - Historical price analysis and technical analysis
1222
+ - 'token-details' - Comprehensive token metadata and validation
1223
+ - 'token-distribution' - Analyze token holder distribution and concentration
1224
+ - 'token-creation' - Launch new tokens
1225
+ - 'profile-management' - User profile management and customization
1226
+ - 'multi-wallet' - Use multiple wallets (privateKey override pattern)
1227
+ - 'transfers' - Transfer GALA and tokens between wallets
1228
+ - 'error-handling' - Handle errors and exceptions
1229
+ - 'installation' - Install and configure SDK
1230
+ - 'local-calculations' - Local vs external bonding curve calculations
1231
+ - 'mcp-to-sdk-mapping' - Complete mapping of MCP tools to SDK methods (56+ tools)
1232
+
1233
+ Returns runnable TypeScript code examples with explanations.`,
1234
+ inputSchema: {
1235
+ type: 'object',
1236
+ properties: {
1237
+ topic: {
1238
+ type: 'string',
1239
+ enum: [
1240
+ 'buy-tokens',
1241
+ 'sell-tokens',
1242
+ 'pool-graduation',
1243
+ 'fetch-pools',
1244
+ 'balances',
1245
+ 'price-history',
1246
+ 'token-details',
1247
+ 'token-distribution',
1248
+ 'token-creation',
1249
+ 'profile-management',
1250
+ 'multi-wallet',
1251
+ 'transfers',
1252
+ 'error-handling',
1253
+ 'installation',
1254
+ 'local-calculations',
1255
+ 'mcp-to-sdk-mapping',
1256
+ ],
1257
+ description: 'The SDK usage topic to explain',
1258
+ },
1259
+ },
1260
+ required: ['topic'],
1261
+ },
1262
+ handler: withErrorHandling(async (_sdk, args) => {
1263
+ const example = SDK_EXAMPLES[args.topic as keyof typeof SDK_EXAMPLES];
1264
+
1265
+ if (!example) {
1266
+ throw new Error(`Unknown topic: ${args.topic}`);
1267
+ }
1268
+
1269
+ return formatSuccess({
1270
+ topic: args.topic,
1271
+ explanation: example,
1272
+ sdkVersion: '3.19.0',
1273
+ packageName: '@gala-chain/launchpad-sdk',
1274
+ documentation: 'https://www.npmjs.com/package/@gala-chain/launchpad-sdk',
1275
+ });
1276
+ }),
1277
+ };