solforge 0.2.0 → 0.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/docs/API.md +379 -0
  3. package/docs/CONFIGURATION.md +407 -0
  4. package/package.json +67 -45
  5. package/src/api-server-entry.ts +109 -0
  6. package/src/commands/add-program.ts +337 -0
  7. package/src/commands/init.ts +122 -0
  8. package/src/commands/list.ts +136 -0
  9. package/src/commands/mint.ts +288 -0
  10. package/src/commands/start.ts +877 -0
  11. package/src/commands/status.ts +99 -0
  12. package/src/commands/stop.ts +406 -0
  13. package/src/config/manager.ts +157 -0
  14. package/src/gui/public/build/main.css +1 -0
  15. package/src/gui/public/build/main.js +303 -0
  16. package/src/gui/public/build/main.js.txt +231 -0
  17. package/src/index.ts +188 -0
  18. package/src/services/api-server.ts +485 -0
  19. package/src/services/port-manager.ts +177 -0
  20. package/src/services/process-registry.ts +154 -0
  21. package/src/services/program-cloner.ts +317 -0
  22. package/src/services/token-cloner.ts +809 -0
  23. package/src/services/validator.ts +295 -0
  24. package/src/types/config.ts +110 -0
  25. package/src/utils/shell.ts +110 -0
  26. package/src/utils/token-loader.ts +115 -0
  27. package/.agi/agi.sqlite +0 -0
  28. package/.claude/settings.local.json +0 -9
  29. package/.github/workflows/release-binaries.yml +0 -133
  30. package/.tmp/.787ebcdbf7b8fde8-00000000.hm +0 -0
  31. package/.tmp/.bffe6efebdf8aedc-00000000.hm +0 -0
  32. package/AGENTS.md +0 -271
  33. package/CLAUDE.md +0 -106
  34. package/PROJECT_STRUCTURE.md +0 -124
  35. package/SOLANA_KIT_GUIDE.md +0 -251
  36. package/SOLFORGE.md +0 -119
  37. package/biome.json +0 -34
  38. package/bun.lock +0 -743
  39. package/drizzle/0000_friendly_millenium_guard.sql +0 -53
  40. package/drizzle/0001_stale_sentinels.sql +0 -2
  41. package/drizzle/meta/0000_snapshot.json +0 -329
  42. package/drizzle/meta/0001_snapshot.json +0 -345
  43. package/drizzle/meta/_journal.json +0 -20
  44. package/drizzle.config.ts +0 -12
  45. package/index.ts +0 -21
  46. package/mint.sh +0 -47
  47. package/postcss.config.js +0 -6
  48. package/rpc-server.ts.backup +0 -519
  49. package/sf.config.json +0 -38
  50. package/tailwind.config.js +0 -27
  51. package/test-client.ts +0 -120
  52. package/tmp/inspect-html.ts +0 -4
  53. package/tmp/response-test.ts +0 -5
  54. package/tmp/test-html.ts +0 -5
  55. package/tmp/test-server.ts +0 -13
  56. package/tsconfig.json +0 -29
@@ -0,0 +1,877 @@
1
+ import chalk from "chalk";
2
+ import ora from "ora";
3
+ import { spawn } from "child_process";
4
+ import { existsSync, readFileSync } from "fs";
5
+ import { join } from "path";
6
+ import { runCommand, checkSolanaTools } from "../utils/shell.js";
7
+ import { configManager } from "../config/manager.js";
8
+ import { TokenCloner } from "../services/token-cloner.js";
9
+ import { processRegistry } from "../services/process-registry.js";
10
+ import { portManager } from "../services/port-manager.js";
11
+
12
+ import type { Config, TokenConfig } from "../types/config.js";
13
+ import type { ClonedToken } from "../services/token-cloner.js";
14
+ import type { RunningValidator } from "../services/process-registry.js";
15
+
16
+ function generateValidatorId(name: string): string {
17
+ const timestamp = Date.now();
18
+ const randomSuffix = Math.random().toString(36).substring(2, 8);
19
+ const safeName = name.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase();
20
+ return `${safeName}-${timestamp}-${randomSuffix}`;
21
+ }
22
+
23
+ export async function startCommand(
24
+ debug: boolean = false,
25
+ network: boolean = false
26
+ ): Promise<void> {
27
+ // Check prerequisites
28
+ const tools = await checkSolanaTools();
29
+ if (!tools.solana) {
30
+ console.error(chalk.red("āŒ solana CLI not found"));
31
+ console.log(
32
+ chalk.yellow(
33
+ "šŸ’” Install it with: sh -c \"$(curl --proto '=https' --tlsv1.2 -sSfL https://solana-install.solana.workers.dev | bash)\""
34
+ )
35
+ );
36
+ process.exit(1);
37
+ }
38
+
39
+ // Load configuration
40
+ let config: Config;
41
+ try {
42
+ await configManager.load("./sf.config.json");
43
+ config = configManager.getConfig();
44
+ } catch (error) {
45
+ console.error(chalk.red("āŒ Failed to load sf.config.json"));
46
+ console.error(
47
+ chalk.red(error instanceof Error ? error.message : String(error))
48
+ );
49
+ console.log(
50
+ chalk.yellow("šŸ’” Run `solforge init` to create a configuration")
51
+ );
52
+ process.exit(1);
53
+ }
54
+
55
+ // Check if validator is already running on configured ports first
56
+ const checkResult = await runCommand(
57
+ "curl",
58
+ [
59
+ "-s",
60
+ "-X",
61
+ "POST",
62
+ `http://127.0.0.1:${config.localnet.port}`,
63
+ "-H",
64
+ "Content-Type: application/json",
65
+ "-d",
66
+ '{"jsonrpc":"2.0","id":1,"method":"getHealth"}',
67
+ ],
68
+ { silent: true, debug: false }
69
+ );
70
+
71
+ if (checkResult.success && checkResult.stdout.includes("ok")) {
72
+ console.log(chalk.yellow("āš ļø Validator is already running"));
73
+ console.log(
74
+ chalk.cyan(`🌐 RPC URL: http://127.0.0.1:${config.localnet.port}`)
75
+ );
76
+ console.log(
77
+ chalk.cyan(
78
+ `šŸ’° Faucet URL: http://127.0.0.1:${config.localnet.faucetPort}`
79
+ )
80
+ );
81
+
82
+ // Clone tokens if needed, even when validator is already running
83
+ let clonedTokens: ClonedToken[] = [];
84
+ if (config.tokens.length > 0) {
85
+ const tokenCloner = new TokenCloner();
86
+
87
+ // Check which tokens are already cloned and which need to be cloned
88
+ const { existingTokens, tokensToClone } = await checkExistingClonedTokens(
89
+ config.tokens,
90
+ tokenCloner
91
+ );
92
+
93
+ if (existingTokens.length > 0) {
94
+ console.log(
95
+ chalk.green(`šŸ“ Found ${existingTokens.length} already cloned tokens`)
96
+ );
97
+ if (debug) {
98
+ existingTokens.forEach((token: ClonedToken) => {
99
+ console.log(
100
+ chalk.gray(
101
+ ` āœ“ ${token.config.symbol} (${token.config.mainnetMint})`
102
+ )
103
+ );
104
+ });
105
+ }
106
+ clonedTokens.push(...existingTokens);
107
+ }
108
+
109
+ if (tokensToClone.length > 0) {
110
+ console.log(
111
+ chalk.yellow(
112
+ `šŸ“¦ Cloning ${tokensToClone.length} new tokens from mainnet...\n`
113
+ )
114
+ );
115
+ try {
116
+ const newlyClonedTokens = await tokenCloner.cloneTokens(
117
+ tokensToClone,
118
+ config.localnet.rpc,
119
+ debug
120
+ );
121
+ clonedTokens.push(...newlyClonedTokens);
122
+ console.log(
123
+ chalk.green(
124
+ `āœ… Successfully cloned ${newlyClonedTokens.length} new tokens\n`
125
+ )
126
+ );
127
+ } catch (error) {
128
+ console.error(chalk.red("āŒ Failed to clone tokens:"));
129
+ console.error(
130
+ chalk.red(error instanceof Error ? error.message : String(error))
131
+ );
132
+ console.log(
133
+ chalk.yellow(
134
+ "šŸ’” You can start without tokens by removing them from sf.config.json"
135
+ )
136
+ );
137
+ process.exit(1);
138
+ }
139
+ } else if (existingTokens.length > 0) {
140
+ console.log(
141
+ chalk.green("āœ… All tokens already cloned, skipping clone step\n")
142
+ );
143
+ }
144
+ }
145
+
146
+ // Airdrop SOL to mint authority if tokens were cloned (even when validator already running)
147
+ if (clonedTokens.length > 0) {
148
+ console.log(chalk.yellow("\nšŸ’ø Airdropping SOL to mint authority..."));
149
+ const rpcUrl = `http://127.0.0.1:${config.localnet.port}`;
150
+
151
+ try {
152
+ await airdropSolToMintAuthority(clonedTokens[0], rpcUrl, debug);
153
+ console.log(chalk.green("āœ… SOL airdropped successfully!"));
154
+ } catch (error) {
155
+ console.error(chalk.red("āŒ Failed to airdrop SOL:"));
156
+ console.error(
157
+ chalk.red(error instanceof Error ? error.message : String(error))
158
+ );
159
+ console.log(
160
+ chalk.yellow(
161
+ "šŸ’” You may need to manually airdrop SOL for fee payments"
162
+ )
163
+ );
164
+ }
165
+ }
166
+
167
+ // Still mint tokens if any were cloned
168
+ if (clonedTokens.length > 0) {
169
+ console.log(chalk.yellow("\nšŸ’° Minting tokens..."));
170
+ const tokenCloner = new TokenCloner();
171
+ const rpcUrl = `http://127.0.0.1:${config.localnet.port}`;
172
+
173
+ if (debug) {
174
+ console.log(
175
+ chalk.gray(`šŸ› Minting ${clonedTokens.length} tokens to recipients:`)
176
+ );
177
+ clonedTokens.forEach((token, index) => {
178
+ console.log(
179
+ chalk.gray(
180
+ ` ${index + 1}. ${token.config.symbol} (${
181
+ token.config.mainnetMint
182
+ }) - ${token.config.mintAmount} tokens`
183
+ )
184
+ );
185
+ });
186
+ console.log(chalk.gray(`🌐 Using RPC: ${rpcUrl}`));
187
+ }
188
+
189
+ try {
190
+ await tokenCloner.mintTokensToRecipients(clonedTokens, rpcUrl, debug);
191
+ console.log(chalk.green("āœ… Token minting completed!"));
192
+
193
+ if (debug) {
194
+ console.log(
195
+ chalk.gray(
196
+ "šŸ› All tokens have been minted to their respective recipients"
197
+ )
198
+ );
199
+ }
200
+ } catch (error) {
201
+ console.error(chalk.red("āŒ Failed to mint tokens:"));
202
+ console.error(
203
+ chalk.red(error instanceof Error ? error.message : String(error))
204
+ );
205
+ console.log(
206
+ chalk.yellow("šŸ’” Validator is still running, you can mint manually")
207
+ );
208
+ }
209
+ }
210
+ return;
211
+ }
212
+
213
+ // Generate unique ID for this validator instance
214
+ const validatorId = generateValidatorId(config.name);
215
+
216
+ // Get available ports (only if validator is not already running)
217
+ const ports = await portManager.getRecommendedPorts(config);
218
+ if (
219
+ ports.rpcPort !== config.localnet.port ||
220
+ ports.faucetPort !== config.localnet.faucetPort
221
+ ) {
222
+ console.log(
223
+ chalk.yellow(
224
+ `āš ļø Configured ports not available, using: RPC ${ports.rpcPort}, Faucet ${ports.faucetPort}`
225
+ )
226
+ );
227
+ // Update config with available ports
228
+ config.localnet.port = ports.rpcPort;
229
+ config.localnet.faucetPort = ports.faucetPort;
230
+ }
231
+
232
+ console.log(chalk.blue(`šŸš€ Starting ${config.name} (${validatorId})...\n`));
233
+ console.log(chalk.gray(`šŸ“” RPC Port: ${config.localnet.port}`));
234
+ console.log(chalk.gray(`šŸ’° Faucet Port: ${config.localnet.faucetPort}\n`));
235
+
236
+ // Programs will be cloned automatically by validator using --clone-program flags
237
+ if (config.programs.length > 0) {
238
+ console.log(
239
+ chalk.cyan(
240
+ `šŸ”§ Will clone ${config.programs.length} programs from mainnet during startup\n`
241
+ )
242
+ );
243
+ }
244
+
245
+ // Clone tokens after programs
246
+ let clonedTokens: ClonedToken[] = [];
247
+ if (config.tokens.length > 0) {
248
+ const tokenCloner = new TokenCloner();
249
+
250
+ // Check which tokens are already cloned and which need to be cloned
251
+ const { existingTokens, tokensToClone } = await checkExistingClonedTokens(
252
+ config.tokens,
253
+ tokenCloner
254
+ );
255
+
256
+ if (existingTokens.length > 0) {
257
+ console.log(
258
+ chalk.green(`šŸ“ Found ${existingTokens.length} already cloned tokens`)
259
+ );
260
+ if (debug) {
261
+ existingTokens.forEach((token: ClonedToken) => {
262
+ console.log(
263
+ chalk.gray(
264
+ ` āœ“ ${token.config.symbol} (${token.config.mainnetMint})`
265
+ )
266
+ );
267
+ });
268
+ }
269
+ clonedTokens.push(...existingTokens);
270
+ }
271
+
272
+ if (tokensToClone.length > 0) {
273
+ console.log(
274
+ chalk.yellow(
275
+ `šŸ“¦ Cloning ${tokensToClone.length} new tokens from mainnet...\n`
276
+ )
277
+ );
278
+ try {
279
+ const newlyClonedTokens = await tokenCloner.cloneTokens(
280
+ tokensToClone,
281
+ config.localnet.rpc,
282
+ debug
283
+ );
284
+ clonedTokens.push(...newlyClonedTokens);
285
+ console.log(
286
+ chalk.green(
287
+ `āœ… Successfully cloned ${newlyClonedTokens.length} new tokens\n`
288
+ )
289
+ );
290
+ } catch (error) {
291
+ console.error(chalk.red("āŒ Failed to clone tokens:"));
292
+ console.error(
293
+ chalk.red(error instanceof Error ? error.message : String(error))
294
+ );
295
+ console.log(
296
+ chalk.yellow(
297
+ "šŸ’” You can start without tokens by removing them from sf.config.json"
298
+ )
299
+ );
300
+ process.exit(1);
301
+ }
302
+ } else if (existingTokens.length > 0) {
303
+ console.log(
304
+ chalk.green("āœ… All tokens already cloned, skipping clone step\n")
305
+ );
306
+ }
307
+ }
308
+
309
+ // Build validator command arguments
310
+ const args = buildValidatorArgs(config, clonedTokens);
311
+
312
+ console.log(chalk.gray("Command to run:"));
313
+ console.log(chalk.gray(`solana-test-validator ${args.join(" ")}\n`));
314
+
315
+ if (debug) {
316
+ console.log(chalk.yellow("šŸ› Debug mode enabled"));
317
+ console.log(chalk.gray("Full command details:"));
318
+ console.log(chalk.gray(` Command: solana-test-validator`));
319
+ console.log(chalk.gray(` Arguments: ${JSON.stringify(args, null, 2)}`));
320
+ }
321
+
322
+ // Start the validator
323
+ const spinner = ora("Starting Solana test validator...").start();
324
+
325
+ try {
326
+ // Start validator in background
327
+ const validatorProcess = await startValidatorInBackground(
328
+ "solana-test-validator",
329
+ args,
330
+ debug
331
+ );
332
+
333
+ // Wait for validator to be ready
334
+ spinner.text = "Waiting for validator to be ready...";
335
+ await waitForValidatorReady(
336
+ `http://127.0.0.1:${config.localnet.port}`,
337
+ debug
338
+ );
339
+
340
+ // Find an available port for the API server
341
+ let apiServerPort = 3000;
342
+ while (!(await portManager.isPortAvailable(apiServerPort))) {
343
+ apiServerPort++;
344
+ if (apiServerPort > 3100) {
345
+ throw new Error("Could not find available port for API server");
346
+ }
347
+ }
348
+
349
+ // Start the API server as a background process
350
+ let apiServerPid: number | undefined;
351
+ let apiResult: { success: boolean; error?: string } = {
352
+ success: false,
353
+ error: "Not started",
354
+ };
355
+
356
+ try {
357
+ const currentDir = process.cwd();
358
+ const testpilotDir = join(__dirname, "..", "..");
359
+ const apiServerScript = join(testpilotDir, "src", "api-server-entry.ts");
360
+ const configPath =
361
+ configManager.getConfigPath() ?? join(currentDir, "sf.config.json");
362
+ const workDir = join(currentDir, ".solforge");
363
+
364
+ // Start API server in background using runCommand with nohup
365
+ const hostFlag = network ? ` --host "0.0.0.0"` : "";
366
+ const apiServerCommand = `nohup bun run "${apiServerScript}" --port ${apiServerPort} --config "${configPath}" --rpc-url "http://127.0.0.1:${config.localnet.port}" --faucet-url "http://127.0.0.1:${config.localnet.faucetPort}" --work-dir "${workDir}"${hostFlag} > /dev/null 2>&1 &`;
367
+
368
+ const startResult = await runCommand("sh", ["-c", apiServerCommand], {
369
+ silent: !debug,
370
+ debug: debug,
371
+ });
372
+
373
+ if (startResult.success) {
374
+ // Wait a moment for the API server to start
375
+ await new Promise((resolve) => setTimeout(resolve, 3000));
376
+
377
+ // Test if the API server is responding
378
+ try {
379
+ const healthCheckHost = network ? "0.0.0.0" : "127.0.0.1";
380
+ const response = await fetch(
381
+ `http://${healthCheckHost}:${apiServerPort}/api/health`
382
+ );
383
+ if (response.ok) {
384
+ apiResult = { success: true };
385
+ // Get the PID of the API server process
386
+ const pidResult = await runCommand(
387
+ "pgrep",
388
+ ["-f", `api-server-entry.*--port ${apiServerPort}`],
389
+ { silent: true, debug: false }
390
+ );
391
+ if (pidResult.success && pidResult.stdout.trim()) {
392
+ const pidLine = pidResult.stdout.trim().split("\n")[0];
393
+ if (pidLine) {
394
+ apiServerPid = parseInt(pidLine);
395
+ }
396
+ }
397
+ } else {
398
+ apiResult = {
399
+ success: false,
400
+ error: `Health check failed: ${response.status}`,
401
+ };
402
+ }
403
+ } catch (error) {
404
+ apiResult = {
405
+ success: false,
406
+ error: `Health check failed: ${
407
+ error instanceof Error ? error.message : String(error)
408
+ }`,
409
+ };
410
+ }
411
+ } else {
412
+ apiResult = {
413
+ success: false,
414
+ error: `Failed to start API server: ${
415
+ startResult.stderr || "Unknown error"
416
+ }`,
417
+ };
418
+ }
419
+ } catch (error) {
420
+ apiResult = {
421
+ success: false,
422
+ error: error instanceof Error ? error.message : String(error),
423
+ };
424
+ }
425
+
426
+ if (!apiResult.success) {
427
+ console.warn(
428
+ chalk.yellow("āš ļø Failed to start API server:", apiResult.error)
429
+ );
430
+ }
431
+
432
+ // Register the running validator
433
+ const runningValidator: RunningValidator = {
434
+ id: validatorId,
435
+ name: config.name,
436
+ pid: validatorProcess.pid!,
437
+ rpcPort: config.localnet.port,
438
+ faucetPort: config.localnet.faucetPort,
439
+ rpcUrl: `http://127.0.0.1:${config.localnet.port}`,
440
+ faucetUrl: `http://127.0.0.1:${config.localnet.faucetPort}`,
441
+ configPath: configManager.getConfigPath() || "./sf.config.json",
442
+ startTime: new Date(),
443
+ status: "running",
444
+ apiServerPort: apiResult.success ? apiServerPort : undefined,
445
+ apiServerUrl: apiResult.success
446
+ ? `http://${network ? "0.0.0.0" : "127.0.0.1"}:${apiServerPort}`
447
+ : undefined,
448
+ apiServerPid: apiResult.success ? apiServerPid : undefined,
449
+ };
450
+
451
+ processRegistry.register(runningValidator);
452
+
453
+ // Validator is now ready
454
+ spinner.succeed("Validator started successfully!");
455
+
456
+ console.log(chalk.green("āœ… Localnet is running!"));
457
+ console.log(chalk.gray(`šŸ†” Validator ID: ${validatorId}`));
458
+ console.log(
459
+ chalk.cyan(`🌐 RPC URL: http://127.0.0.1:${config.localnet.port}`)
460
+ );
461
+ console.log(
462
+ chalk.cyan(
463
+ `šŸ’° Faucet URL: http://127.0.0.1:${config.localnet.faucetPort}`
464
+ )
465
+ );
466
+ if (apiResult.success) {
467
+ const displayHost = network ? "0.0.0.0" : "127.0.0.1";
468
+ console.log(
469
+ chalk.cyan(`šŸš€ API Server: http://${displayHost}:${apiServerPort}/api`)
470
+ );
471
+ if (network) {
472
+ console.log(
473
+ chalk.yellow(
474
+ " 🌐 Network mode enabled - API server accessible from other devices"
475
+ )
476
+ );
477
+ }
478
+ }
479
+
480
+ // Airdrop SOL to mint authority if tokens were cloned
481
+ if (clonedTokens.length > 0) {
482
+ console.log(chalk.yellow("\nšŸ’ø Airdropping SOL to mint authority..."));
483
+ const rpcUrl = `http://127.0.0.1:${config.localnet.port}`;
484
+
485
+ try {
486
+ await airdropSolToMintAuthority(clonedTokens[0], rpcUrl, debug);
487
+ console.log(chalk.green("āœ… SOL airdropped successfully!"));
488
+ } catch (error) {
489
+ console.error(chalk.red("āŒ Failed to airdrop SOL:"));
490
+ console.error(
491
+ chalk.red(error instanceof Error ? error.message : String(error))
492
+ );
493
+ console.log(
494
+ chalk.yellow(
495
+ "šŸ’” You may need to manually airdrop SOL for fee payments"
496
+ )
497
+ );
498
+ }
499
+ }
500
+
501
+ // Mint tokens if any were cloned
502
+ if (clonedTokens.length > 0) {
503
+ console.log(chalk.yellow("\nšŸ’° Minting tokens..."));
504
+ const tokenCloner = new TokenCloner();
505
+ const rpcUrl = `http://127.0.0.1:${config.localnet.port}`;
506
+
507
+ if (debug) {
508
+ console.log(
509
+ chalk.gray(`šŸ› Minting ${clonedTokens.length} tokens to recipients:`)
510
+ );
511
+ clonedTokens.forEach((token, index) => {
512
+ console.log(
513
+ chalk.gray(
514
+ ` ${index + 1}. ${token.config.symbol} (${
515
+ token.config.mainnetMint
516
+ }) - ${token.config.mintAmount} tokens`
517
+ )
518
+ );
519
+ });
520
+ console.log(chalk.gray(`🌐 Using RPC: ${rpcUrl}`));
521
+ }
522
+
523
+ try {
524
+ await tokenCloner.mintTokensToRecipients(clonedTokens, rpcUrl, debug);
525
+ console.log(chalk.green("āœ… Token minting completed!"));
526
+
527
+ if (debug) {
528
+ console.log(
529
+ chalk.gray(
530
+ "šŸ› All tokens have been minted to their respective recipients"
531
+ )
532
+ );
533
+ }
534
+ } catch (error) {
535
+ console.error(chalk.red("āŒ Failed to mint tokens:"));
536
+ console.error(
537
+ chalk.red(error instanceof Error ? error.message : String(error))
538
+ );
539
+ console.log(
540
+ chalk.yellow("šŸ’” Validator is still running, you can mint manually")
541
+ );
542
+ }
543
+ }
544
+
545
+ if (config.tokens.length > 0) {
546
+ console.log(chalk.yellow("\nšŸŖ™ Cloned tokens:"));
547
+ config.tokens.forEach((token) => {
548
+ console.log(
549
+ chalk.gray(
550
+ ` - ${token.symbol}: ${token.mainnetMint} (${token.mintAmount} minted)`
551
+ )
552
+ );
553
+ });
554
+ }
555
+
556
+ if (config.programs.length > 0) {
557
+ console.log(chalk.yellow("\nšŸ“¦ Cloned programs:"));
558
+ config.programs.forEach((program) => {
559
+ const name =
560
+ program.name || program.mainnetProgramId.slice(0, 8) + "...";
561
+ console.log(chalk.gray(` - ${name}: ${program.mainnetProgramId}`));
562
+ });
563
+ }
564
+
565
+ console.log(chalk.blue("\nšŸ’” Tips:"));
566
+ console.log(
567
+ chalk.gray(" - Run `solforge list` to see all running validators")
568
+ );
569
+ console.log(
570
+ chalk.gray(" - Run `solforge status` to check validator status")
571
+ );
572
+ console.log(
573
+ chalk.gray(
574
+ ` - Run \`solforge stop ${validatorId}\` to stop this validator`
575
+ )
576
+ );
577
+ console.log(
578
+ chalk.gray(" - Run `solforge stop --all` to stop all validators")
579
+ );
580
+ if (apiResult.success) {
581
+ const endpointHost = network ? "0.0.0.0" : "127.0.0.1";
582
+ console.log(chalk.blue("\nšŸ”Œ API Endpoints:"));
583
+ console.log(
584
+ chalk.gray(
585
+ ` - GET http://${endpointHost}:${apiServerPort}/api/tokens - List cloned tokens`
586
+ )
587
+ );
588
+ console.log(
589
+ chalk.gray(
590
+ ` - GET http://${endpointHost}:${apiServerPort}/api/programs - List cloned programs`
591
+ )
592
+ );
593
+ console.log(
594
+ chalk.gray(
595
+ ` - POST http://${endpointHost}:${apiServerPort}/api/tokens/{mintAddress}/mint - Mint tokens`
596
+ )
597
+ );
598
+ console.log(
599
+ chalk.gray(
600
+ ` - POST http://${endpointHost}:${apiServerPort}/api/airdrop - Airdrop SOL`
601
+ )
602
+ );
603
+ console.log(
604
+ chalk.gray(
605
+ ` - GET http://${endpointHost}:${apiServerPort}/api/wallet/{address}/balances - Get balances`
606
+ )
607
+ );
608
+ }
609
+ } catch (error) {
610
+ spinner.fail("Failed to start validator");
611
+ console.error(chalk.red("āŒ Unexpected error:"));
612
+ console.error(
613
+ chalk.red(error instanceof Error ? error.message : String(error))
614
+ );
615
+ process.exit(1);
616
+ }
617
+ }
618
+
619
+ function buildValidatorArgs(
620
+ config: Config,
621
+ clonedTokens: ClonedToken[] = []
622
+ ): string[] {
623
+ const args: string[] = [];
624
+
625
+ // Basic configuration
626
+ args.push("--rpc-port", config.localnet.port.toString());
627
+ args.push("--faucet-port", config.localnet.faucetPort.toString());
628
+ args.push("--bind-address", config.localnet.bindAddress);
629
+
630
+ if (config.localnet.reset) {
631
+ args.push("--reset");
632
+ }
633
+
634
+ if (config.localnet.quiet) {
635
+ args.push("--quiet");
636
+ } else {
637
+ // Always use quiet mode to prevent log spam in background
638
+ args.push("--quiet");
639
+ }
640
+
641
+ // Add ledger size limit
642
+ args.push("--limit-ledger-size", config.localnet.limitLedgerSize.toString());
643
+
644
+ // Add cloned token accounts (using modified JSON files)
645
+ if (clonedTokens.length > 0) {
646
+ const tokenCloner = new TokenCloner();
647
+ const tokenArgs = tokenCloner.getValidatorArgs(clonedTokens);
648
+ args.push(...tokenArgs);
649
+ }
650
+
651
+ // Clone programs from mainnet using built-in validator flags
652
+ for (const program of config.programs) {
653
+ if (program.upgradeable) {
654
+ args.push("--clone-upgradeable-program", program.mainnetProgramId);
655
+ } else {
656
+ // Use --clone for regular programs (non-upgradeable)
657
+ args.push("--clone", program.mainnetProgramId);
658
+ }
659
+ }
660
+
661
+ // If we're cloning programs, specify the source cluster
662
+ if (config.programs.length > 0) {
663
+ args.push("--url", config.localnet.rpc);
664
+ }
665
+
666
+ return args;
667
+ }
668
+
669
+ /**
670
+ * Start the validator in the background
671
+ */
672
+ async function startValidatorInBackground(
673
+ command: string,
674
+ args: string[],
675
+ debug: boolean
676
+ ): Promise<{ pid: number }> {
677
+ return new Promise((resolve, reject) => {
678
+ if (debug) {
679
+ console.log(chalk.gray(`Starting ${command} in background...`));
680
+ console.log(chalk.gray(`Command: ${command} ${args.join(" ")}`));
681
+ }
682
+
683
+ const child = spawn(command, args, {
684
+ detached: true,
685
+ stdio: "ignore", // Always ignore stdio to ensure it runs in background
686
+ });
687
+
688
+ child.on("error", (error) => {
689
+ reject(new Error(`Failed to start validator: ${error.message}`));
690
+ });
691
+
692
+ // Give the validator a moment to start
693
+ setTimeout(() => {
694
+ if (child.pid) {
695
+ child.unref(); // Allow parent to exit without waiting for child
696
+ if (debug) {
697
+ console.log(
698
+ chalk.gray(`āœ… Validator started with PID: ${child.pid}`)
699
+ );
700
+ }
701
+ resolve({ pid: child.pid });
702
+ } else {
703
+ reject(new Error("Validator failed to start"));
704
+ }
705
+ }, 1000);
706
+ });
707
+ }
708
+
709
+ /**
710
+ * Wait for the validator to be ready by polling the RPC endpoint
711
+ */
712
+ async function waitForValidatorReady(
713
+ rpcUrl: string,
714
+ debug: boolean,
715
+ maxAttempts: number = 30
716
+ ): Promise<void> {
717
+ let lastError: string = "";
718
+
719
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
720
+ try {
721
+ if (debug) {
722
+ console.log(
723
+ chalk.gray(`Attempt ${attempt}/${maxAttempts}: Checking ${rpcUrl}`)
724
+ );
725
+ }
726
+
727
+ const result = await runCommand(
728
+ "curl",
729
+ [
730
+ "-s",
731
+ "-X",
732
+ "POST",
733
+ rpcUrl,
734
+ "-H",
735
+ "Content-Type: application/json",
736
+ "-d",
737
+ '{"jsonrpc":"2.0","id":1,"method":"getHealth"}',
738
+ ],
739
+ { silent: true, debug: false }
740
+ );
741
+
742
+ if (result.success && result.stdout.includes("ok")) {
743
+ if (debug) {
744
+ console.log(
745
+ chalk.green(`āœ… Validator is ready after ${attempt} attempts`)
746
+ );
747
+ }
748
+ return;
749
+ }
750
+
751
+ // Store the last error for better diagnostics
752
+ if (!result.success) {
753
+ lastError = result.stderr || "Unknown error";
754
+ }
755
+ } catch (error) {
756
+ lastError = error instanceof Error ? error.message : String(error);
757
+ }
758
+
759
+ if (attempt < maxAttempts) {
760
+ await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second
761
+ }
762
+ }
763
+
764
+ // Provide better error message
765
+ let errorMsg = `Validator failed to become ready after ${maxAttempts} attempts`;
766
+ if (lastError.includes("Connection refused")) {
767
+ errorMsg += `\nšŸ’” This usually means:\n - Port ${
768
+ rpcUrl.split(":")[2]
769
+ } is already in use\n - Run 'pkill -f solana-test-validator' to kill existing validators`;
770
+ } else if (lastError) {
771
+ errorMsg += `\nLast error: ${lastError}`;
772
+ }
773
+
774
+ throw new Error(errorMsg);
775
+ }
776
+
777
+ /**
778
+ * Airdrop SOL to the mint authority for fee payments
779
+ */
780
+ async function airdropSolToMintAuthority(
781
+ clonedToken: any,
782
+ rpcUrl: string,
783
+ debug: boolean = false
784
+ ): Promise<void> {
785
+ if (debug) {
786
+ console.log(
787
+ chalk.gray(`Airdropping 10 SOL to ${clonedToken.mintAuthority.publicKey}`)
788
+ );
789
+ }
790
+
791
+ const airdropResult = await runCommand(
792
+ "solana",
793
+ ["airdrop", "10", clonedToken.mintAuthority.publicKey, "--url", rpcUrl],
794
+ { silent: !debug, debug }
795
+ );
796
+
797
+ if (!airdropResult.success) {
798
+ throw new Error(
799
+ `Failed to airdrop SOL: ${airdropResult.stderr || airdropResult.stdout}`
800
+ );
801
+ }
802
+
803
+ if (debug) {
804
+ console.log(chalk.gray("SOL airdrop completed"));
805
+ }
806
+ }
807
+
808
+ /**
809
+ * Check for existing cloned tokens and return what's already cloned vs what needs to be cloned
810
+ */
811
+ async function checkExistingClonedTokens(
812
+ tokens: TokenConfig[],
813
+ tokenCloner: TokenCloner
814
+ ): Promise<{ existingTokens: ClonedToken[]; tokensToClone: TokenConfig[] }> {
815
+ const existingTokens: ClonedToken[] = [];
816
+ const tokensToClone: TokenConfig[] = [];
817
+ const workDir = ".solforge";
818
+
819
+ // Check for shared mint authority
820
+ const sharedMintAuthorityPath = join(workDir, "shared-mint-authority.json");
821
+ let sharedMintAuthority: { publicKey: string; secretKey: number[] } | null =
822
+ null;
823
+
824
+ if (existsSync(sharedMintAuthorityPath)) {
825
+ try {
826
+ const fileContent = JSON.parse(
827
+ readFileSync(sharedMintAuthorityPath, "utf8")
828
+ );
829
+
830
+ if (Array.isArray(fileContent)) {
831
+ // New format: file contains just the secret key array
832
+ const { Keypair } = await import("@solana/web3.js");
833
+ const keypair = Keypair.fromSecretKey(new Uint8Array(fileContent));
834
+ sharedMintAuthority = {
835
+ publicKey: keypair.publicKey.toBase58(),
836
+ secretKey: Array.from(keypair.secretKey),
837
+ };
838
+
839
+ // Check metadata for consistency
840
+ const metadataPath = join(workDir, "shared-mint-authority-meta.json");
841
+ if (existsSync(metadataPath)) {
842
+ const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
843
+ if (metadata.publicKey !== sharedMintAuthority.publicKey) {
844
+ sharedMintAuthority.publicKey = metadata.publicKey;
845
+ }
846
+ }
847
+ } else {
848
+ // Old format: file contains {publicKey, secretKey}
849
+ sharedMintAuthority = fileContent;
850
+ }
851
+ } catch (error) {
852
+ // If we can't read the shared mint authority, treat all tokens as needing to be cloned
853
+ sharedMintAuthority = null;
854
+ }
855
+ }
856
+
857
+ for (const token of tokens) {
858
+ const tokenDir = join(workDir, `token-${token.symbol.toLowerCase()}`);
859
+ const modifiedAccountPath = join(tokenDir, "modified.json");
860
+
861
+ // Check if this token has already been cloned
862
+ if (existsSync(modifiedAccountPath) && sharedMintAuthority) {
863
+ // Token appears to be already cloned
864
+ existingTokens.push({
865
+ config: token,
866
+ mintAuthorityPath: sharedMintAuthorityPath,
867
+ modifiedAccountPath,
868
+ mintAuthority: sharedMintAuthority,
869
+ });
870
+ } else {
871
+ // Token needs to be cloned
872
+ tokensToClone.push(token);
873
+ }
874
+ }
875
+
876
+ return { existingTokens, tokensToClone };
877
+ }