@sun-protocol/sun-cli 1.2.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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +579 -0
  3. package/bin/sun +2 -0
  4. package/dist/bin.d.ts +3 -0
  5. package/dist/bin.d.ts.map +1 -0
  6. package/dist/bin.js +83 -0
  7. package/dist/bin.js.map +1 -0
  8. package/dist/commands/contract.d.ts +3 -0
  9. package/dist/commands/contract.d.ts.map +1 -0
  10. package/dist/commands/contract.js +58 -0
  11. package/dist/commands/contract.js.map +1 -0
  12. package/dist/commands/farm.d.ts +3 -0
  13. package/dist/commands/farm.d.ts.map +1 -0
  14. package/dist/commands/farm.js +124 -0
  15. package/dist/commands/farm.js.map +1 -0
  16. package/dist/commands/liquidity.d.ts +3 -0
  17. package/dist/commands/liquidity.d.ts.map +1 -0
  18. package/dist/commands/liquidity.js +742 -0
  19. package/dist/commands/liquidity.js.map +1 -0
  20. package/dist/commands/pair.d.ts +3 -0
  21. package/dist/commands/pair.d.ts.map +1 -0
  22. package/dist/commands/pair.js +38 -0
  23. package/dist/commands/pair.js.map +1 -0
  24. package/dist/commands/pool.d.ts +3 -0
  25. package/dist/commands/pool.d.ts.map +1 -0
  26. package/dist/commands/pool.js +183 -0
  27. package/dist/commands/pool.js.map +1 -0
  28. package/dist/commands/position.d.ts +3 -0
  29. package/dist/commands/position.d.ts.map +1 -0
  30. package/dist/commands/position.js +86 -0
  31. package/dist/commands/position.js.map +1 -0
  32. package/dist/commands/price.d.ts +3 -0
  33. package/dist/commands/price.d.ts.map +1 -0
  34. package/dist/commands/price.js +60 -0
  35. package/dist/commands/price.js.map +1 -0
  36. package/dist/commands/protocol.d.ts +3 -0
  37. package/dist/commands/protocol.d.ts.map +1 -0
  38. package/dist/commands/protocol.js +151 -0
  39. package/dist/commands/protocol.js.map +1 -0
  40. package/dist/commands/sunpump.d.ts +3 -0
  41. package/dist/commands/sunpump.d.ts.map +1 -0
  42. package/dist/commands/sunpump.js +911 -0
  43. package/dist/commands/sunpump.js.map +1 -0
  44. package/dist/commands/swap.d.ts +3 -0
  45. package/dist/commands/swap.d.ts.map +1 -0
  46. package/dist/commands/swap.js +226 -0
  47. package/dist/commands/swap.js.map +1 -0
  48. package/dist/commands/token.d.ts +3 -0
  49. package/dist/commands/token.d.ts.map +1 -0
  50. package/dist/commands/token.js +73 -0
  51. package/dist/commands/token.js.map +1 -0
  52. package/dist/commands/tx.d.ts +3 -0
  53. package/dist/commands/tx.d.ts.map +1 -0
  54. package/dist/commands/tx.js +47 -0
  55. package/dist/commands/tx.js.map +1 -0
  56. package/dist/commands/wallet.d.ts +3 -0
  57. package/dist/commands/wallet.d.ts.map +1 -0
  58. package/dist/commands/wallet.js +52 -0
  59. package/dist/commands/wallet.js.map +1 -0
  60. package/dist/lib/command.d.ts +79 -0
  61. package/dist/lib/command.d.ts.map +1 -0
  62. package/dist/lib/command.js +203 -0
  63. package/dist/lib/command.js.map +1 -0
  64. package/dist/lib/confirm.d.ts +9 -0
  65. package/dist/lib/confirm.d.ts.map +1 -0
  66. package/dist/lib/confirm.js +84 -0
  67. package/dist/lib/confirm.js.map +1 -0
  68. package/dist/lib/context.d.ts +10 -0
  69. package/dist/lib/context.d.ts.map +1 -0
  70. package/dist/lib/context.js +49 -0
  71. package/dist/lib/context.js.map +1 -0
  72. package/dist/lib/output.d.ts +47 -0
  73. package/dist/lib/output.d.ts.map +1 -0
  74. package/dist/lib/output.js +389 -0
  75. package/dist/lib/output.js.map +1 -0
  76. package/dist/lib/sunpump.d.ts +143 -0
  77. package/dist/lib/sunpump.d.ts.map +1 -0
  78. package/dist/lib/sunpump.js +155 -0
  79. package/dist/lib/sunpump.js.map +1 -0
  80. package/dist/lib/tokens.d.ts +40 -0
  81. package/dist/lib/tokens.d.ts.map +1 -0
  82. package/dist/lib/tokens.js +113 -0
  83. package/dist/lib/tokens.js.map +1 -0
  84. package/dist/lib/wallet.d.ts +7 -0
  85. package/dist/lib/wallet.d.ts.map +1 -0
  86. package/dist/lib/wallet.js +97 -0
  87. package/dist/lib/wallet.js.map +1 -0
  88. package/package.json +69 -0
@@ -0,0 +1,911 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.registerSunpumpCommands = registerSunpumpCommands;
37
+ const command_1 = require("../lib/command");
38
+ const confirm_1 = require("../lib/confirm");
39
+ const context_1 = require("../lib/context");
40
+ const output_1 = require("../lib/output");
41
+ const sunpump_1 = require("../lib/sunpump");
42
+ function assertMainnet() {
43
+ const n = (0, context_1.getNetwork)();
44
+ if (n && n !== 'mainnet') {
45
+ throw new Error(`SunPump is only available on mainnet (got "${n}"). Drop --network or pass --network mainnet.`);
46
+ }
47
+ }
48
+ async function pumpAction(opts) {
49
+ try {
50
+ assertMainnet();
51
+ const client = (0, sunpump_1.getSunPump)();
52
+ const raw = await (0, output_1.withSpinner)(opts.spinnerLabel, () => opts.execute(client));
53
+ let data = raw;
54
+ let pagination;
55
+ if (opts.parseEnvelope !== false) {
56
+ const parsed = (0, command_1.parseApiResponse)(raw);
57
+ data = parsed.data;
58
+ pagination = parsed.pagination;
59
+ }
60
+ const final = opts.transform ? opts.transform(data) : data;
61
+ if (opts.detailFor && !(0, output_1.isJsonMode)()) {
62
+ const pairs = opts.detailFor(final);
63
+ if (pairs) {
64
+ (0, output_1.printKeyValue)(pairs);
65
+ if (pagination)
66
+ (0, output_1.printPaginationFooter)(pagination);
67
+ return;
68
+ }
69
+ }
70
+ (0, output_1.output)(final, opts.tableConfig);
71
+ if (pagination)
72
+ (0, output_1.printPaginationFooter)(pagination);
73
+ }
74
+ catch (err) {
75
+ (0, output_1.outputError)(opts.errorLabel, err);
76
+ }
77
+ }
78
+ function toIntOrUndef(v) {
79
+ if (v === undefined || v === null || v === '')
80
+ return undefined;
81
+ const n = Number(v);
82
+ return Number.isFinite(n) ? Math.trunc(n) : undefined;
83
+ }
84
+ // ---------------------------------------------------------------------------
85
+ // Shared table configs
86
+ // ---------------------------------------------------------------------------
87
+ function tokenPriceUsd(t) {
88
+ const usd = t.priceInUsd ?? t.tokenPriceUsd ?? t.price;
89
+ if (usd !== undefined && usd !== null && usd !== '')
90
+ return usd;
91
+ const trxPrice = Number(t.priceInTrx);
92
+ const trxUsdRaw = t.trxPriceInUsd;
93
+ if (Number.isFinite(trxPrice) &&
94
+ trxUsdRaw !== null &&
95
+ trxUsdRaw !== undefined &&
96
+ trxUsdRaw !== '') {
97
+ const trxUsd = Number(trxUsdRaw);
98
+ if (Number.isFinite(trxUsd) && trxUsd > 0)
99
+ return trxPrice * trxUsd;
100
+ }
101
+ const mcap = Number(t.marketCap ?? t.marketCapUsd);
102
+ const supply = Number(t.totalSupply);
103
+ if (Number.isFinite(mcap) && mcap > 0 && Number.isFinite(supply) && supply > 0) {
104
+ return mcap / supply;
105
+ }
106
+ return undefined;
107
+ }
108
+ const tokenTable = {
109
+ headers: ['Symbol', 'Name', 'Address', 'Price', 'MCap', 'Volume24h'],
110
+ toRow: (t) => [
111
+ t.symbol ?? '-',
112
+ t.name ?? '-',
113
+ t.contractAddress ?? t.tokenAddress ?? '-',
114
+ (0, output_1.formatUsd)(tokenPriceUsd(t)),
115
+ (0, output_1.formatUsd)(t.marketCap ?? t.mcap ?? t.marketCapUsd),
116
+ (0, output_1.formatUsd)(t.volume24Hr ?? t.volume24h ?? t.volumeUsd1d),
117
+ ],
118
+ };
119
+ const holderTable = {
120
+ headers: ['Holder', 'Type', 'Balance', 'Percent'],
121
+ toRow: (h) => {
122
+ const pctRaw = h.percent ?? h.percentage;
123
+ let pct = '-';
124
+ if (pctRaw !== undefined && pctRaw !== null && pctRaw !== '') {
125
+ const n = Number(pctRaw);
126
+ if (Number.isFinite(n)) {
127
+ // API returns percentage values both as fractions (token list endpoint, e.g. 1.95e-6 = 0.000195%)
128
+ // and as percent units (holders endpoint, e.g. 38.51 = 38.51%). Use magnitude heuristic.
129
+ const asPct = Math.abs(n) <= 1 ? n * 100 : n;
130
+ pct = `${asPct.toFixed(4)}%`;
131
+ }
132
+ }
133
+ return [
134
+ h.holderAddress ?? h.address ?? h.userAddress ?? '-',
135
+ h.holderType ?? '-',
136
+ h.decimals
137
+ ? (0, output_1.formatAmount)(h.amount ?? h.balance, h.decimals)
138
+ : fmtNum(h.balance ?? h.amount, 2),
139
+ pct,
140
+ ];
141
+ },
142
+ };
143
+ const txTable = {
144
+ headers: ['Time', 'Type', 'From → To', 'Volume', 'TxHash'],
145
+ toRow: (tx) => {
146
+ const fromSym = tx.fromTokenSymbol ?? tx.fromSymbol ?? tx.fromTokenAddress ?? '?';
147
+ const toSym = tx.toTokenSymbol ?? tx.toSymbol ?? tx.toTokenAddress ?? '?';
148
+ return [
149
+ (0, output_1.formatTime)(tx.txDateTime ?? tx.swapTime ?? tx.timestamp ?? tx.createdAt),
150
+ tx.swapTranType ?? tx.txnOrderType ?? tx.type ?? '-',
151
+ `${fromSym} → ${toSym}`,
152
+ (0, output_1.formatUsd)(tx.volumeInUsd ?? tx.amountUsd),
153
+ tx.txHash ?? tx.transactionHash ?? tx.txnHash ?? '-',
154
+ ];
155
+ },
156
+ };
157
+ function tokenDetail(t) {
158
+ if (!t || typeof t !== 'object')
159
+ return null;
160
+ const pairs = {};
161
+ const set = (k, v) => {
162
+ if (v !== undefined && v !== null && v !== '')
163
+ pairs[k] = v;
164
+ };
165
+ set('Symbol', t.symbol);
166
+ set('Name', t.name);
167
+ set('Description', t.description);
168
+ const statusBits = [];
169
+ if (t.status)
170
+ statusBits.push(String(t.status));
171
+ if (t.active === true)
172
+ statusBits.push('active');
173
+ if (t.pumpPercentage !== undefined && t.pumpPercentage !== null) {
174
+ statusBits.push(`pump ${Number(t.pumpPercentage).toFixed(2)}%`);
175
+ }
176
+ if (statusBits.length)
177
+ set('Status', statusBits.join(' · '));
178
+ set('Contract', t.contractAddress);
179
+ set('Owner', t.ownerAddress);
180
+ set('Swap Pool', t.swapPoolAddress);
181
+ set('Price (USD)', (0, output_1.formatUsd)(tokenPriceUsd(t)));
182
+ set('Price (TRX)', fmtNum(t.priceInTrx, 8));
183
+ if (t.priceChange24Hr !== undefined && t.priceChange24Hr !== null) {
184
+ const n = Number(t.priceChange24Hr);
185
+ const sign = n > 0 ? '+' : '';
186
+ set('24h Change', `${sign}${(0, output_1.formatPct)(n)}`);
187
+ }
188
+ set('Market Cap', (0, output_1.formatUsd)(t.marketCap ?? t.marketCapUsd));
189
+ set('24h Volume', (0, output_1.formatUsd)(t.volume24Hr ?? t.volume24h ?? t.volumeUsd1d));
190
+ if (t.holders !== undefined && t.holders !== null)
191
+ set('Holders', t.holders);
192
+ if (t.totalSupply !== undefined && t.totalSupply !== null) {
193
+ set('Total Supply', Number(t.totalSupply).toLocaleString('en-US'));
194
+ }
195
+ if (t.trxPriceInUsd !== undefined && t.trxPriceInUsd !== null) {
196
+ set('TRX/USD', (0, output_1.formatUsd)(t.trxPriceInUsd));
197
+ }
198
+ set('Created', (0, output_1.formatTime)(t.tokenCreatedInstant));
199
+ set('Launched', (0, output_1.formatTime)(t.tokenLaunchedInstant));
200
+ set('Website', t.websiteUrl);
201
+ set('Twitter', t.twitterUrl);
202
+ set('Telegram', t.telegramUrl);
203
+ if (t.listOn && typeof t.listOn === 'object') {
204
+ const cex = Object.entries(t.listOn)
205
+ .filter(([, url]) => typeof url === 'string' && url !== '')
206
+ .map(([name]) => name);
207
+ if (cex.length)
208
+ set('Listed On', cex.join(', '));
209
+ }
210
+ return pairs;
211
+ }
212
+ // Decimal string (e.g. "10.5") → integer string in base units, scaled by 10^decimals.
213
+ function decimalToBaseUnits(value, decimals) {
214
+ const trimmed = value.trim();
215
+ if (!/^-?\d+(\.\d+)?$/.test(trimmed)) {
216
+ throw new Error(`Invalid decimal amount: "${value}"`);
217
+ }
218
+ const negative = trimmed.startsWith('-');
219
+ const unsigned = negative ? trimmed.slice(1) : trimmed;
220
+ const [whole, frac = ''] = unsigned.split('.');
221
+ if (frac.length > decimals) {
222
+ throw new Error(`Amount "${value}" has more than ${decimals} decimal places (token precision limit).`);
223
+ }
224
+ const paddedFrac = (frac + '0'.repeat(decimals)).slice(0, decimals);
225
+ const scaled = BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(paddedFrac || '0');
226
+ return (negative ? -scaled : scaled).toString();
227
+ }
228
+ const trxToSun = (trx) => decimalToBaseUnits(trx, 6);
229
+ // Inverse: base-unit string → human-readable decimal.
230
+ function baseUnitsToDecimal(raw, decimals) {
231
+ const n = typeof raw === 'bigint' ? raw : BigInt(raw);
232
+ const negative = n < 0n;
233
+ const abs = negative ? -n : n;
234
+ const base = 10n ** BigInt(decimals);
235
+ const whole = (abs / base).toString();
236
+ const fracDigits = (abs % base).toString().padStart(decimals, '0').replace(/0+$/, '');
237
+ const out = fracDigits ? `${whole}.${fracDigits}` : whole;
238
+ return negative ? `-${out}` : out;
239
+ }
240
+ // SunKit's enum lists 0/1/2 but the contract uses extra states (e.g. 3 = launched-on-DEX).
241
+ // Map what we know; surface raw values verbatim otherwise.
242
+ const SUNPUMP_STATE_NAME = {
243
+ 0: 'NOT_EXIST',
244
+ 1: 'TRADING',
245
+ 2: 'READY_TO_LAUNCH',
246
+ 3: 'LAUNCHED',
247
+ };
248
+ function sunpumpStateLabel(state) {
249
+ if (state === undefined || state === null)
250
+ return '-';
251
+ const name = SUNPUMP_STATE_NAME[state];
252
+ return name ? `${name} (${state})` : `UNKNOWN (${state})`;
253
+ }
254
+ function fmtNum(v, digits = 6) {
255
+ if (v === undefined || v === null || v === '')
256
+ return '-';
257
+ const n = Number(v);
258
+ if (!Number.isFinite(n))
259
+ return '-';
260
+ if (n === 0)
261
+ return '0';
262
+ if (Math.abs(n) >= 1)
263
+ return n.toLocaleString(undefined, { maximumFractionDigits: digits });
264
+ return n.toPrecision(4);
265
+ }
266
+ const portfolioTable = {
267
+ headers: ['Symbol', 'Address', 'Balance', 'Price (TRX)', 'Value (TRX)', 'Percent'],
268
+ toRow: (t) => [
269
+ t.symbol ?? '-',
270
+ t.address ?? t.contractAddress ?? '-',
271
+ fmtNum(t.balance, 4),
272
+ fmtNum(t.priceInTrx, 8),
273
+ fmtNum(t.valueInTrx, 6),
274
+ t.percentage !== undefined && t.percentage !== null
275
+ ? `${(Number(t.percentage) * 100).toPrecision(4)}%`
276
+ : '-',
277
+ ],
278
+ };
279
+ // ---------------------------------------------------------------------------
280
+ // Command registration
281
+ // ---------------------------------------------------------------------------
282
+ function registerSunpumpCommands(program) {
283
+ const sp = program
284
+ .command('sunpump')
285
+ .description('SunPump endpoints (mainnet only: api-v2.sunpump.meme).')
286
+ .hook('preAction', () => {
287
+ assertMainnet();
288
+ });
289
+ // -------------------------- token group ----------------------------------
290
+ const token = sp.command('token').description('Token info, search, holders, ranking');
291
+ token
292
+ .command('list')
293
+ .description('List tokens with optional filters and pagination')
294
+ .option('--contract <address>', 'Filter by contract address')
295
+ .option('--owner <address>', 'Filter by owner address')
296
+ .option('--symbol <symbol>', 'Filter by symbol')
297
+ .option('--name <name>', 'Filter by name')
298
+ .option('--description <text>', 'Filter by description')
299
+ .option('--page <n>', 'Page number')
300
+ .option('--size <n>', 'Page size')
301
+ .option('--sort <field>', 'Sort field')
302
+ .action(async (opts) => {
303
+ await pumpAction({
304
+ spinnerLabel: 'Fetching tokens...',
305
+ errorLabel: 'Failed to fetch tokens',
306
+ execute: (c) => c.listTokens({
307
+ contractAddress: opts.contract,
308
+ ownerAddress: opts.owner,
309
+ symbol: opts.symbol,
310
+ name: opts.name,
311
+ description: opts.description,
312
+ page: toIntOrUndef(opts.page),
313
+ size: toIntOrUndef(opts.size),
314
+ sort: opts.sort,
315
+ }),
316
+ tableConfig: tokenTable,
317
+ });
318
+ });
319
+ token
320
+ .command('get <contractAddress>')
321
+ .description('Get token detail by contract address')
322
+ .action(async (contractAddress) => {
323
+ await pumpAction({
324
+ spinnerLabel: 'Fetching token...',
325
+ errorLabel: 'Failed to fetch token',
326
+ execute: (c) => c.getToken(contractAddress),
327
+ detailFor: tokenDetail,
328
+ });
329
+ });
330
+ token
331
+ .command('search <query>')
332
+ .description('Fuzzy search tokens')
333
+ .option('--on-sunswap', 'Only tokens listed on SunSwap', false)
334
+ .option('--page <n>', 'Page number')
335
+ .option('--size <n>', 'Page size')
336
+ .option('--sort <field>', 'Sort field')
337
+ .action(async (query, opts) => {
338
+ await pumpAction({
339
+ spinnerLabel: `Searching tokens for "${query}"...`,
340
+ errorLabel: 'Failed to search tokens',
341
+ execute: (c) => c.searchTokens({
342
+ query,
343
+ onSunSwap: opts.onSunswap || undefined,
344
+ page: toIntOrUndef(opts.page),
345
+ size: toIntOrUndef(opts.size),
346
+ sort: opts.sort,
347
+ }),
348
+ tableConfig: tokenTable,
349
+ });
350
+ });
351
+ token
352
+ .command('search-v2 <query>')
353
+ .description('Fuzzy search tokens (v2 with extra filters)')
354
+ .option('--on-sunswap', 'Only tokens listed on SunSwap')
355
+ .option('--dlive', 'Filter: DLive showing')
356
+ .option('--ai-helper', 'Filter: AI helper')
357
+ .option('--twitter-launch', 'Filter: Twitter launch')
358
+ .option('--sun-agent-launch', 'Filter: Sun agent launch')
359
+ .option('--page <n>', 'Page number')
360
+ .option('--size <n>', 'Page size')
361
+ .option('--sort <field>', 'Sort field')
362
+ .action(async (query, opts) => {
363
+ await pumpAction({
364
+ spinnerLabel: `Searching tokens (v2) for "${query}"...`,
365
+ errorLabel: 'Failed to search tokens',
366
+ execute: (c) => c.searchTokensV2({
367
+ query,
368
+ onSunSwap: opts.onSunswap || undefined,
369
+ filterDliveShowing: opts.dlive || undefined,
370
+ filterAiHelper: opts.aiHelper || undefined,
371
+ filterTwitterLaunch: opts.twitterLaunch || undefined,
372
+ filterSunAgentLaunch: opts.sunAgentLaunch || undefined,
373
+ page: toIntOrUndef(opts.page),
374
+ size: toIntOrUndef(opts.size),
375
+ sort: opts.sort,
376
+ }),
377
+ tableConfig: tokenTable,
378
+ });
379
+ });
380
+ token
381
+ .command('by-owner <ownerAddress>')
382
+ .description('List tokens created by a wallet')
383
+ .option('--page <n>', 'Page number')
384
+ .option('--size <n>', 'Page size')
385
+ .option('--sort <field>', 'Sort field')
386
+ .action(async (ownerAddress, opts) => {
387
+ await pumpAction({
388
+ spinnerLabel: 'Fetching tokens by owner...',
389
+ errorLabel: 'Failed to fetch tokens',
390
+ execute: (c) => c.tokensByOwner({
391
+ address: ownerAddress,
392
+ page: toIntOrUndef(opts.page),
393
+ size: toIntOrUndef(opts.size),
394
+ sort: opts.sort,
395
+ }),
396
+ tableConfig: tokenTable,
397
+ });
398
+ });
399
+ token
400
+ .command('holders <tokenAddress>')
401
+ .description('List holders of a token')
402
+ .option('--include-zero', 'Include zero-balance holders')
403
+ .option('--page <n>', 'Page number')
404
+ .option('--size <n>', 'Page size')
405
+ .option('--sort <field>', 'Sort field')
406
+ .action(async (tokenAddress, opts) => {
407
+ await pumpAction({
408
+ spinnerLabel: 'Fetching token holders...',
409
+ errorLabel: 'Failed to fetch holders',
410
+ execute: (c) => c.tokenHolders({
411
+ address: tokenAddress,
412
+ includeZeroBalance: opts.includeZero || undefined,
413
+ page: toIntOrUndef(opts.page),
414
+ size: toIntOrUndef(opts.size),
415
+ sort: opts.sort,
416
+ }),
417
+ tableConfig: holderTable,
418
+ });
419
+ });
420
+ token
421
+ .command('holders-v2 <tokenAddress>')
422
+ .description('List holders of a token (v2)')
423
+ .option('--include-zero', 'Include zero-balance holders')
424
+ .option('--page <n>', 'Page number')
425
+ .option('--size <n>', 'Page size')
426
+ .option('--sort <field>', 'Sort field')
427
+ .action(async (tokenAddress, opts) => {
428
+ await pumpAction({
429
+ spinnerLabel: 'Fetching token holders (v2)...',
430
+ errorLabel: 'Failed to fetch holders',
431
+ execute: (c) => c.tokenHoldersV2({
432
+ address: tokenAddress,
433
+ includeZeroBalance: opts.includeZero || undefined,
434
+ page: toIntOrUndef(opts.page),
435
+ size: toIntOrUndef(opts.size),
436
+ sort: opts.sort,
437
+ }),
438
+ tableConfig: holderTable,
439
+ });
440
+ });
441
+ token
442
+ .command('favors')
443
+ .description("List a user's favorite tokens (requires signed message)")
444
+ .requiredOption('--user-address <address>', 'User wallet address')
445
+ .requiredOption('--signature <sig>', 'Signature of signed-message')
446
+ .requiredOption('--signed-message <msg>', 'Signed message')
447
+ .option('--token-address <address>', 'Filter by token address')
448
+ .option('--page <n>', 'Page number')
449
+ .option('--size <n>', 'Page size')
450
+ .action(async (opts) => {
451
+ await pumpAction({
452
+ spinnerLabel: 'Fetching user favors...',
453
+ errorLabel: 'Failed to fetch favors',
454
+ execute: (c) => c.userFavors({
455
+ userAddress: opts.userAddress,
456
+ signature: opts.signature,
457
+ signedMessage: opts.signedMessage,
458
+ tokenAddress: opts.tokenAddress,
459
+ page: toIntOrUndef(opts.page),
460
+ size: toIntOrUndef(opts.size),
461
+ }),
462
+ tableConfig: tokenTable,
463
+ });
464
+ });
465
+ token
466
+ .command('ranking')
467
+ .description('Token ranking by type')
468
+ .requiredOption('--type <rankingType>', 'Ranking type: MARKET_CAP | VOLUME_24H | PRICE_CHANGE_24H')
469
+ .option('--size <n>', 'Number of entries')
470
+ .action(async (opts) => {
471
+ await pumpAction({
472
+ spinnerLabel: 'Fetching ranking...',
473
+ errorLabel: 'Failed to fetch ranking',
474
+ execute: (c) => c.ranking({ rankingType: opts.type, size: toIntOrUndef(opts.size) }),
475
+ tableConfig: tokenTable,
476
+ });
477
+ });
478
+ token
479
+ .command('king-of-hill')
480
+ .description('Get the current king-of-the-hill token')
481
+ .action(async () => {
482
+ await pumpAction({
483
+ spinnerLabel: 'Fetching king of hill...',
484
+ errorLabel: 'Failed to fetch king of hill',
485
+ execute: (c) => c.kingOfHill(),
486
+ tableConfig: tokenTable,
487
+ });
488
+ });
489
+ token
490
+ .command('pump-list')
491
+ .description('Get the SunPump token list (raw, no envelope)')
492
+ .action(async () => {
493
+ await pumpAction({
494
+ spinnerLabel: 'Fetching pump token list...',
495
+ errorLabel: 'Failed to fetch pump list',
496
+ execute: (c) => c.pumpTokenList(),
497
+ parseEnvelope: false,
498
+ });
499
+ });
500
+ // -------------------------- tx group -------------------------------------
501
+ const tx = sp.command('tx').description('Swap transactions');
502
+ const addTxFilterOptions = (cmd) => cmd
503
+ .option('--swap-type <type>', 'Swap type filter (BUY/SELL)')
504
+ .option('--pool <address>', 'Swap pool address')
505
+ .option('--tx-hash <hash>', 'Specific tx hash')
506
+ .option('--block <n>', 'Block number')
507
+ .option('--start-time <epoch>', 'Start time (epoch seconds)')
508
+ .option('--end-time <epoch>', 'End time (epoch seconds)')
509
+ .option('--page <n>', 'Page number')
510
+ .option('--size <n>', 'Page size')
511
+ .option('--sort <field>', 'Sort field');
512
+ addTxFilterOptions(tx.command('token <contractAddress>').description('Transactions for a token')).action(async (contractAddress, opts) => {
513
+ await pumpAction({
514
+ spinnerLabel: 'Fetching token transactions...',
515
+ errorLabel: 'Failed to fetch transactions',
516
+ execute: (c) => c.tokenTransactions(contractAddress, {
517
+ swapTranType: opts.swapType,
518
+ swapPoolAddress: opts.pool,
519
+ txHash: opts.txHash,
520
+ blockNum: toIntOrUndef(opts.block),
521
+ startTime: toIntOrUndef(opts.startTime),
522
+ endTime: toIntOrUndef(opts.endTime),
523
+ page: toIntOrUndef(opts.page),
524
+ size: toIntOrUndef(opts.size),
525
+ sort: opts.sort,
526
+ }),
527
+ tableConfig: txTable,
528
+ });
529
+ });
530
+ addTxFilterOptions(tx.command('user <ownerAddress>').description('Transactions for a wallet')).action(async (ownerAddress, opts) => {
531
+ await pumpAction({
532
+ spinnerLabel: 'Fetching user transactions...',
533
+ errorLabel: 'Failed to fetch transactions',
534
+ execute: (c) => c.userTransactions(ownerAddress, {
535
+ swapTranType: opts.swapType,
536
+ swapPoolAddress: opts.pool,
537
+ txHash: opts.txHash,
538
+ blockNum: toIntOrUndef(opts.block),
539
+ startTime: toIntOrUndef(opts.startTime),
540
+ endTime: toIntOrUndef(opts.endTime),
541
+ page: toIntOrUndef(opts.page),
542
+ size: toIntOrUndef(opts.size),
543
+ sort: opts.sort,
544
+ }),
545
+ tableConfig: txTable,
546
+ });
547
+ });
548
+ // -------------------------- portfolio ------------------------------------
549
+ sp.command('portfolio <walletAddress>')
550
+ .description('Get tokens held by a wallet (with TRX value filter)')
551
+ .option('--include-zero', 'Include zero-balance tokens')
552
+ .option('--min-trx <amount>', 'Minimum TRX value')
553
+ .option('--page <n>', 'Page number')
554
+ .option('--size <n>', 'Page size')
555
+ .option('--sort <field>', 'Sort field')
556
+ .action(async (walletAddress, opts) => {
557
+ await pumpAction({
558
+ spinnerLabel: 'Fetching portfolio...',
559
+ errorLabel: 'Failed to fetch portfolio',
560
+ execute: (c) => c.portfolio(walletAddress, {
561
+ includeZeroBalance: opts.includeZero || undefined,
562
+ trxAmountMin: toIntOrUndef(opts.minTrx),
563
+ page: toIntOrUndef(opts.page),
564
+ size: toIntOrUndef(opts.size),
565
+ sort: opts.sort,
566
+ }),
567
+ tableConfig: portfolioTable,
568
+ });
569
+ });
570
+ // -------------------------- launch (agent token launch) ------------------
571
+ sp.command('launch')
572
+ .description('Launch a new token via the SunPump agent endpoint (server-side creation, no wallet needed)')
573
+ .requiredOption('--name <name>', 'Token name')
574
+ .requiredOption('--symbol <symbol>', 'Token symbol')
575
+ .requiredOption('--description <text>', 'Token description')
576
+ .option('--image <path>', 'Logo image file (read and sent as base64)')
577
+ .option('--image-base64 <data>', 'Logo image as a raw base64 string (overrides --image)')
578
+ .option('--twitter-url <url>', 'Twitter URL')
579
+ .option('--telegram-url <url>', 'Telegram URL')
580
+ .option('--website-url <url>', 'Website URL')
581
+ .option('--tweet-username <name>', 'Tweet username to associate with the launch')
582
+ .action(async (opts) => {
583
+ let imageBase64 = opts.imageBase64;
584
+ let imageLabel = imageBase64 ? `base64 (${imageBase64.length} chars)` : undefined;
585
+ if (!imageBase64 && opts.image) {
586
+ try {
587
+ const { readFile } = await Promise.resolve().then(() => __importStar(require('fs/promises')));
588
+ const buf = await readFile(opts.image);
589
+ imageBase64 = buf.toString('base64');
590
+ imageLabel = `${opts.image} (${buf.length} bytes)`;
591
+ }
592
+ catch (err) {
593
+ (0, output_1.outputError)('Failed to read --image file', err);
594
+ return;
595
+ }
596
+ }
597
+ const params = {
598
+ name: opts.name,
599
+ symbol: opts.symbol,
600
+ description: opts.description,
601
+ imageBase64,
602
+ twitterUrl: opts.twitterUrl ?? '',
603
+ telegramUrl: opts.telegramUrl ?? '',
604
+ websiteUrl: opts.websiteUrl ?? '',
605
+ tweetUsername: opts.tweetUsername ?? '',
606
+ };
607
+ if ((0, command_1.isDryRun)()) {
608
+ (0, output_1.output)({
609
+ dryRun: true,
610
+ action: 'SunPump Agent Token Launch',
611
+ params: { ...params, imageBase64: imageLabel },
612
+ });
613
+ return;
614
+ }
615
+ (0, confirm_1.printSummary)('SunPump Agent Token Launch', {
616
+ Name: params.name,
617
+ Symbol: params.symbol,
618
+ Description: params.description,
619
+ Image: imageLabel,
620
+ Twitter: params.twitterUrl,
621
+ Telegram: params.telegramUrl,
622
+ Website: params.websiteUrl,
623
+ 'Tweet User': params.tweetUsername,
624
+ });
625
+ const confirmed = await (0, confirm_1.confirm)('Launch this token?');
626
+ if (!confirmed) {
627
+ if (!(0, output_1.isJsonMode)())
628
+ console.log('Cancelled.');
629
+ return;
630
+ }
631
+ try {
632
+ assertMainnet();
633
+ const client = (0, sunpump_1.getSunPump)();
634
+ const raw = await (0, output_1.withSpinner)('Launching token...', () => client.agentTokenLaunch(params));
635
+ const { data } = (0, command_1.parseApiResponse)(raw);
636
+ if ((0, output_1.isJsonMode)()) {
637
+ (0, output_1.output)(data);
638
+ return;
639
+ }
640
+ // Unlike the GET endpoints (plain epoch seconds), the launch endpoint
641
+ // serializes *Instant fields as epoch-millis / 1e6 (e.g. 1780476.327).
642
+ // Normalize to epoch seconds so tokenDetail/formatTime render correctly.
643
+ for (const k of ['tokenCreatedInstant', 'tokenLaunchedInstant', 'firstReachHillInstant']) {
644
+ const v = Number(data?.[k]);
645
+ if (Number.isFinite(v) && v > 0 && v < 1e8)
646
+ data[k] = v * 1000;
647
+ }
648
+ const pairs = tokenDetail(data) ?? {};
649
+ if (data?.createTxHash)
650
+ pairs['Create Tx'] = data.createTxHash;
651
+ if (data?.logoUrl)
652
+ pairs['Logo'] = data.logoUrl;
653
+ const chalk = (await Promise.resolve().then(() => __importStar(require('chalk')))).default;
654
+ console.log();
655
+ console.log(chalk.green('Token launched'));
656
+ (0, output_1.printKeyValue)(pairs);
657
+ }
658
+ catch (err) {
659
+ (0, output_1.outputError)('Launch failed', err);
660
+ // The server has been seen to return this opaque error when no logo
661
+ // image accompanies the launch — point at the likely fix.
662
+ if (!imageBase64 && String(err?.message ?? '').includes('Invoke third part error')) {
663
+ (0, output_1.info)('Hint: this error often means the launch lacked a logo — retry with --image <path>.');
664
+ }
665
+ }
666
+ });
667
+ // -------------------------- trade (buy/sell/quote/state) -----------------
668
+ sp.command('state <tokenAddress>')
669
+ .description('Show SunPump token state (0 NOT_EXIST, 1 TRADING, 2 READY_TO_LAUNCH, 3 LAUNCHED)')
670
+ .action(async (tokenAddress) => {
671
+ try {
672
+ const network = (0, context_1.getNetwork)();
673
+ const result = await (0, output_1.withSpinner)('Fetching token state...', async () => {
674
+ const kit = await (0, context_1.getKit)();
675
+ const state = await kit.getSunPumpTokenState(tokenAddress, network);
676
+ const info = await kit.getSunPumpTokenInfo(tokenAddress, network).catch(() => null);
677
+ return { state, info };
678
+ });
679
+ if ((0, output_1.isJsonMode)()) {
680
+ (0, output_1.output)({ ...result, stateName: sunpumpStateLabel(result.state) });
681
+ return;
682
+ }
683
+ const pairs = {
684
+ Token: result.info?.tokenAddress ?? tokenAddress,
685
+ State: sunpumpStateLabel(result.state),
686
+ Launched: result.info?.launched === true ? 'yes' : 'no',
687
+ };
688
+ if (result.info?.price !== undefined)
689
+ pairs['Price (raw)'] = String(result.info.price);
690
+ if (result.info?.trxReserve !== undefined) {
691
+ pairs['TRX Reserve'] = `${baseUnitsToDecimal(result.info.trxReserve, 6)} TRX`;
692
+ }
693
+ if (result.info?.tokenReserve !== undefined) {
694
+ pairs['Token Reserve'] = baseUnitsToDecimal(result.info.tokenReserve, 18);
695
+ }
696
+ (0, output_1.printKeyValue)(pairs);
697
+ }
698
+ catch (err) {
699
+ (0, output_1.outputError)('Failed to fetch state', err);
700
+ }
701
+ });
702
+ sp.command('quote-buy <tokenAddress>')
703
+ .description('Preview a SunPump buy without sending a transaction')
704
+ .requiredOption('--trx <amount>', 'TRX to spend (decimal, e.g. 10 or 1.5)')
705
+ .action(async (tokenAddress, opts) => {
706
+ let trxSun;
707
+ try {
708
+ trxSun = trxToSun(opts.trx);
709
+ }
710
+ catch (err) {
711
+ (0, output_1.outputError)('Invalid --trx', err);
712
+ return;
713
+ }
714
+ try {
715
+ const network = (0, context_1.getNetwork)();
716
+ const quote = await (0, output_1.withSpinner)('Fetching buy quote...', async () => {
717
+ const kit = await (0, context_1.getKit)();
718
+ return kit.sunpumpQuoteBuy(tokenAddress, trxSun, network);
719
+ });
720
+ if ((0, output_1.isJsonMode)()) {
721
+ (0, output_1.output)({ ...quote, tokenAddress, trxSun, trxIn: opts.trx });
722
+ return;
723
+ }
724
+ (0, output_1.printKeyValue)({
725
+ Token: tokenAddress,
726
+ 'TRX In': `${opts.trx} TRX`,
727
+ 'Tokens Out (expected)': baseUnitsToDecimal(quote.tokenAmount, 18),
728
+ Fee: `${baseUnitsToDecimal(quote.fee, 6)} TRX`,
729
+ });
730
+ }
731
+ catch (err) {
732
+ (0, output_1.outputError)('Failed to fetch quote', err);
733
+ }
734
+ });
735
+ sp.command('quote-sell <tokenAddress>')
736
+ .description('Preview a SunPump sell without sending a transaction')
737
+ .requiredOption('--amount <amount>', 'Token amount to sell (decimal)')
738
+ .option('--decimals <n>', 'Token decimals (default 18)', '18')
739
+ .action(async (tokenAddress, opts) => {
740
+ const decimals = Number(opts.decimals) || 18;
741
+ let tokenRaw;
742
+ try {
743
+ tokenRaw = decimalToBaseUnits(opts.amount, decimals);
744
+ }
745
+ catch (err) {
746
+ (0, output_1.outputError)('Invalid --amount', err);
747
+ return;
748
+ }
749
+ try {
750
+ const network = (0, context_1.getNetwork)();
751
+ const quote = await (0, output_1.withSpinner)('Fetching sell quote...', async () => {
752
+ const kit = await (0, context_1.getKit)();
753
+ return kit.sunpumpQuoteSell(tokenAddress, tokenRaw, network);
754
+ });
755
+ if ((0, output_1.isJsonMode)()) {
756
+ (0, output_1.output)({ ...quote, tokenAddress, tokenRaw, amountIn: opts.amount });
757
+ return;
758
+ }
759
+ (0, output_1.printKeyValue)({
760
+ Token: tokenAddress,
761
+ 'Tokens In': `${opts.amount}`,
762
+ 'TRX Out (expected)': `${baseUnitsToDecimal(quote.trxAmount, 6)} TRX`,
763
+ Fee: `${baseUnitsToDecimal(quote.fee, 6)} TRX`,
764
+ });
765
+ }
766
+ catch (err) {
767
+ (0, output_1.outputError)('Failed to fetch quote', err);
768
+ }
769
+ });
770
+ sp.command('buy <tokenAddress>')
771
+ .description('Buy a SunPump token with TRX (bonding-curve, pre-launch only)')
772
+ .requiredOption('--trx <amount>', 'TRX to spend (decimal, e.g. 10 or 1.5)')
773
+ .option('--slippage <n>', 'Slippage tolerance (decimal, e.g. 0.05 = 5%)', '0.05')
774
+ .option('--min-out <raw>', 'Minimum tokens out in raw base units (overrides slippage)')
775
+ .action(async (tokenAddress, opts) => {
776
+ let trxSun;
777
+ try {
778
+ trxSun = trxToSun(opts.trx);
779
+ }
780
+ catch (err) {
781
+ (0, output_1.outputError)('Invalid --trx', err);
782
+ return;
783
+ }
784
+ const slippage = parseFloat(opts.slippage);
785
+ const network = (0, context_1.getNetwork)();
786
+ const summary = {
787
+ Token: tokenAddress,
788
+ 'TRX In': `${opts.trx} TRX (${trxSun} Sun)`,
789
+ Slippage: `${(slippage * 100).toFixed(2)}%`,
790
+ Network: network,
791
+ };
792
+ try {
793
+ const quote = await (0, output_1.withSpinner)('Fetching buy quote...', async () => {
794
+ const kit = await (0, context_1.getKit)();
795
+ return kit.sunpumpQuoteBuy(tokenAddress, trxSun, network);
796
+ });
797
+ summary['Tokens Out (expected)'] = baseUnitsToDecimal(quote.tokenAmount, 18);
798
+ summary['Fee'] = `${baseUnitsToDecimal(quote.fee, 6)} TRX`;
799
+ }
800
+ catch {
801
+ // Quote is best-effort; the real call below will surface the error.
802
+ }
803
+ if (opts.minOut)
804
+ summary['Min Tokens Out (raw)'] = opts.minOut;
805
+ await (0, command_1.writeAction)({
806
+ title: 'SunPump Buy Preview',
807
+ summary,
808
+ confirmMsg: 'Execute this buy?',
809
+ spinnerLabel: 'Submitting buy...',
810
+ errorLabel: 'Buy failed',
811
+ execute: (kit) => kit.sunpumpBuy({
812
+ tokenAddress,
813
+ trxAmount: trxSun,
814
+ minTokenOut: opts.minOut,
815
+ slippage,
816
+ network,
817
+ }),
818
+ onSuccess: async (result) => {
819
+ if ((0, output_1.isJsonMode)())
820
+ return;
821
+ const chalk = (await Promise.resolve().then(() => __importStar(require('chalk')))).default;
822
+ console.log();
823
+ console.log(chalk.green('Buy executed'));
824
+ if (result.expectedTokens) {
825
+ console.log(` Expected: ${baseUnitsToDecimal(result.expectedTokens, 18)} tokens`);
826
+ }
827
+ if (result.minTokenOut) {
828
+ console.log(` Min Out: ${baseUnitsToDecimal(result.minTokenOut, 18)} tokens`);
829
+ }
830
+ if (result.txResult?.txid) {
831
+ console.log(` TxID: ${chalk.bold(result.txResult.txid)}`);
832
+ }
833
+ if (result.tronscanUrl) {
834
+ console.log(` Tronscan: ${chalk.underline(result.tronscanUrl)}`);
835
+ }
836
+ },
837
+ });
838
+ });
839
+ sp.command('sell <tokenAddress>')
840
+ .description('Sell a SunPump token for TRX (bonding-curve, pre-launch only)')
841
+ .requiredOption('--amount <amount>', 'Token amount to sell (decimal)')
842
+ .option('--decimals <n>', 'Token decimals (default 18)', '18')
843
+ .option('--slippage <n>', 'Slippage tolerance (decimal, e.g. 0.05 = 5%)', '0.05')
844
+ .option('--min-out <raw>', 'Minimum TRX out in Sun (overrides slippage)')
845
+ .action(async (tokenAddress, opts) => {
846
+ const decimals = Number(opts.decimals) || 18;
847
+ let tokenRaw;
848
+ try {
849
+ tokenRaw = decimalToBaseUnits(opts.amount, decimals);
850
+ }
851
+ catch (err) {
852
+ (0, output_1.outputError)('Invalid --amount', err);
853
+ return;
854
+ }
855
+ const slippage = parseFloat(opts.slippage);
856
+ const network = (0, context_1.getNetwork)();
857
+ const summary = {
858
+ Token: tokenAddress,
859
+ 'Tokens In': `${opts.amount} (${tokenRaw} raw)`,
860
+ Slippage: `${(slippage * 100).toFixed(2)}%`,
861
+ Network: network,
862
+ };
863
+ try {
864
+ const quote = await (0, output_1.withSpinner)('Fetching sell quote...', async () => {
865
+ const kit = await (0, context_1.getKit)();
866
+ return kit.sunpumpQuoteSell(tokenAddress, tokenRaw, network);
867
+ });
868
+ summary['TRX Out (expected)'] = `${baseUnitsToDecimal(quote.trxAmount, 6)} TRX`;
869
+ summary['Fee'] = `${baseUnitsToDecimal(quote.fee, 6)} TRX`;
870
+ }
871
+ catch {
872
+ // Best-effort.
873
+ }
874
+ if (opts.minOut)
875
+ summary['Min TRX Out (Sun)'] = opts.minOut;
876
+ await (0, command_1.writeAction)({
877
+ title: 'SunPump Sell Preview',
878
+ summary,
879
+ confirmMsg: 'Execute this sell?',
880
+ spinnerLabel: 'Submitting sell...',
881
+ errorLabel: 'Sell failed',
882
+ execute: (kit) => kit.sunpumpSell({
883
+ tokenAddress,
884
+ tokenAmount: tokenRaw,
885
+ minTrxOut: opts.minOut,
886
+ slippage,
887
+ network,
888
+ }),
889
+ onSuccess: async (result) => {
890
+ if ((0, output_1.isJsonMode)())
891
+ return;
892
+ const chalk = (await Promise.resolve().then(() => __importStar(require('chalk')))).default;
893
+ console.log();
894
+ console.log(chalk.green('Sell executed'));
895
+ if (result.expectedTrx) {
896
+ console.log(` Expected: ${baseUnitsToDecimal(result.expectedTrx, 6)} TRX`);
897
+ }
898
+ if (result.minTrxOut) {
899
+ console.log(` Min Out: ${baseUnitsToDecimal(result.minTrxOut, 6)} TRX`);
900
+ }
901
+ if (result.txResult?.txid) {
902
+ console.log(` TxID: ${chalk.bold(result.txResult.txid)}`);
903
+ }
904
+ if (result.tronscanUrl) {
905
+ console.log(` Tronscan: ${chalk.underline(result.tronscanUrl)}`);
906
+ }
907
+ },
908
+ });
909
+ });
910
+ }
911
+ //# sourceMappingURL=sunpump.js.map