solforge 0.1.0

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.
@@ -0,0 +1,337 @@
1
+ import chalk from "chalk";
2
+ import inquirer from "inquirer";
3
+ import { existsSync } from "fs";
4
+ import { configManager } from "../config/manager.js";
5
+ import { ProgramCloner } from "../services/program-cloner.js";
6
+ import { processRegistry } from "../services/process-registry.js";
7
+ import type { ProgramConfig } from "../types/config.js";
8
+
9
+ export async function addProgramCommand(
10
+ options: {
11
+ name?: string;
12
+ programId?: string;
13
+ interactive?: boolean;
14
+ } = {}
15
+ ): Promise<void> {
16
+ console.log(chalk.blue("šŸ“¦ Adding program to configuration...\n"));
17
+
18
+ // Check if config exists
19
+ if (!existsSync("./sf.config.json")) {
20
+ console.error(chalk.red("āŒ No sf.config.json found in current directory"));
21
+ console.log(chalk.yellow("šŸ’” Run `solforge init` to create one"));
22
+ return;
23
+ }
24
+
25
+ // Load current config
26
+ try {
27
+ await configManager.load("./sf.config.json");
28
+ } catch (error) {
29
+ console.error(chalk.red("āŒ Failed to load sf.config.json"));
30
+ console.error(
31
+ chalk.red(error instanceof Error ? error.message : String(error))
32
+ );
33
+ return;
34
+ }
35
+
36
+ const config = configManager.getConfig();
37
+
38
+ // Get program details
39
+ let programId: string;
40
+ let programName: string | undefined;
41
+ let upgradeable: boolean = false;
42
+
43
+ if (options.interactive !== false && !options.programId) {
44
+ // Interactive mode - show common programs + custom option
45
+ const { programChoice } = await inquirer.prompt([
46
+ {
47
+ type: "list",
48
+ name: "programChoice",
49
+ message: "Select a program to add:",
50
+ choices: [
51
+ {
52
+ name: "Token Metadata Program",
53
+ value: {
54
+ id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s",
55
+ name: "Token Metadata",
56
+ upgradeable: true,
57
+ },
58
+ },
59
+ {
60
+ name: "Associated Token Account Program",
61
+ value: {
62
+ id: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",
63
+ name: "Associated Token Account",
64
+ upgradeable: false,
65
+ },
66
+ },
67
+ {
68
+ name: "System Program",
69
+ value: {
70
+ id: "11111111111111111111111111111112",
71
+ name: "System Program",
72
+ upgradeable: false,
73
+ },
74
+ },
75
+ {
76
+ name: "Token Program",
77
+ value: {
78
+ id: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
79
+ name: "Token Program",
80
+ upgradeable: false,
81
+ },
82
+ },
83
+ {
84
+ name: "Token Program 2022",
85
+ value: {
86
+ id: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",
87
+ name: "Token Program 2022",
88
+ upgradeable: true,
89
+ },
90
+ },
91
+ {
92
+ name: "Rent Sysvar",
93
+ value: {
94
+ id: "SysvarRent111111111111111111111111111111111",
95
+ name: "Rent Sysvar",
96
+ upgradeable: false,
97
+ },
98
+ },
99
+ {
100
+ name: "Clock Sysvar",
101
+ value: {
102
+ id: "SysvarC1ock11111111111111111111111111111111",
103
+ name: "Clock Sysvar",
104
+ upgradeable: false,
105
+ },
106
+ },
107
+ {
108
+ name: "Jupiter V6 Program",
109
+ value: {
110
+ id: "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",
111
+ name: "Jupiter V6",
112
+ upgradeable: true,
113
+ },
114
+ },
115
+ {
116
+ name: "Raydium AMM Program",
117
+ value: {
118
+ id: "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8",
119
+ name: "Raydium AMM",
120
+ upgradeable: false,
121
+ },
122
+ },
123
+ {
124
+ name: "Serum DEX Program",
125
+ value: {
126
+ id: "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin",
127
+ name: "Serum DEX",
128
+ upgradeable: false,
129
+ },
130
+ },
131
+ {
132
+ name: "Custom (enter program ID manually)",
133
+ value: "custom",
134
+ },
135
+ ],
136
+ },
137
+ ]);
138
+
139
+ if (programChoice === "custom") {
140
+ const answers = await inquirer.prompt([
141
+ {
142
+ type: "input",
143
+ name: "programId",
144
+ message: "Enter program ID:",
145
+ validate: (input) =>
146
+ input.trim().length > 0 || "Program ID is required",
147
+ },
148
+ {
149
+ type: "input",
150
+ name: "name",
151
+ message: "Enter program name (optional):",
152
+ default: "",
153
+ },
154
+ {
155
+ type: "confirm",
156
+ name: "upgradeable",
157
+ message: "Is this an upgradeable program?",
158
+ default: false,
159
+ },
160
+ ]);
161
+
162
+ programId = answers.programId;
163
+ programName = answers.name || undefined;
164
+ upgradeable = answers.upgradeable;
165
+ } else {
166
+ programId = programChoice.id;
167
+ programName = programChoice.name;
168
+ upgradeable = programChoice.upgradeable;
169
+ }
170
+ } else {
171
+ // Non-interactive mode
172
+ if (!options.programId) {
173
+ console.error(chalk.red("āŒ Program ID is required"));
174
+ console.log(
175
+ chalk.gray(
176
+ "šŸ’” Use --program-id flag, or run without flags for interactive mode"
177
+ )
178
+ );
179
+ return;
180
+ }
181
+
182
+ programId = options.programId;
183
+ programName = options.name;
184
+ // Default to false for CLI, could add --upgradeable flag later
185
+ upgradeable = false;
186
+ }
187
+
188
+ try {
189
+ // Check if program already exists in config
190
+ const existingProgram = config.programs.find(
191
+ (p) => p.mainnetProgramId === programId
192
+ );
193
+ if (existingProgram) {
194
+ console.log(
195
+ chalk.yellow(`āš ļø Program ${programId} already exists in configuration`)
196
+ );
197
+ console.log(chalk.gray(` Name: ${existingProgram.name || "unnamed"}`));
198
+ return;
199
+ }
200
+
201
+ // Verify program exists on mainnet first
202
+ console.log(chalk.gray("šŸ” Verifying program exists on mainnet..."));
203
+ const programCloner = new ProgramCloner();
204
+ const programInfo = await programCloner.getProgramInfo(
205
+ programId,
206
+ "mainnet-beta"
207
+ );
208
+
209
+ if (!programInfo.exists) {
210
+ console.error(chalk.red(`āŒ Program ${programId} not found on mainnet`));
211
+ return;
212
+ }
213
+
214
+ if (!programInfo.executable) {
215
+ console.error(chalk.red(`āŒ ${programId} is not an executable program`));
216
+ return;
217
+ }
218
+
219
+ console.log(
220
+ chalk.gray(` āœ“ Found executable program (${programInfo.size} bytes)`)
221
+ );
222
+
223
+ // Create new program config
224
+ const newProgram: ProgramConfig = {
225
+ name: programName,
226
+ mainnetProgramId: programId,
227
+ upgradeable: upgradeable,
228
+ cluster: "mainnet-beta",
229
+ dependencies: [],
230
+ };
231
+
232
+ // Add to config
233
+ config.programs.push(newProgram);
234
+
235
+ // Save updated config
236
+ await configManager.save("./sf.config.json");
237
+
238
+ console.log(
239
+ chalk.green(
240
+ `\nāœ… Successfully added ${programName || programId} to configuration!`
241
+ )
242
+ );
243
+ console.log(chalk.cyan(`šŸ“ Updated sf.config.json`));
244
+ console.log(chalk.gray(` Program ID: ${programId}`));
245
+ console.log(chalk.gray(` Upgradeable: ${upgradeable ? "Yes" : "No"}`));
246
+
247
+ // Check if there are running validators
248
+ await processRegistry.cleanup();
249
+ const validators = processRegistry.getRunning();
250
+
251
+ if (validators.length > 0) {
252
+ console.log(
253
+ chalk.yellow(`\nāš ļø Found ${validators.length} running validator(s)`)
254
+ );
255
+ console.log(
256
+ chalk.gray("šŸ’” Programs are added to genesis config and require RESET")
257
+ );
258
+ console.log(chalk.red(" āš ļø RESET will WIPE all ledger data!"));
259
+ console.log(
260
+ chalk.gray(
261
+ ` 1. Stop validators using "${config.name}": solforge stop <validator-id>`
262
+ )
263
+ );
264
+ console.log(chalk.gray(" 2. Start with reset: solforge start"));
265
+
266
+ const { shouldRestart } = await inquirer.prompt([
267
+ {
268
+ type: "confirm",
269
+ name: "shouldRestart",
270
+ message: "āš ļø Reset validators now? (This will WIPE all ledger data)",
271
+ default: false,
272
+ },
273
+ ]);
274
+
275
+ if (shouldRestart) {
276
+ console.log(chalk.yellow("\nšŸ”„ Resetting validators..."));
277
+ console.log(chalk.red("āš ļø This will delete all ledger data!"));
278
+
279
+ // Import the commands we need
280
+ const { stopCommand } = await import("./stop.js");
281
+ const { startCommand } = await import("./start.js");
282
+
283
+ // Get current config for modifications
284
+ const currentConfig = configManager.getConfig();
285
+
286
+ // Stop validators that use this config
287
+ const configName = currentConfig.name;
288
+ const matchingValidators = validators.filter((v) =>
289
+ v.name.startsWith(configName)
290
+ );
291
+
292
+ if (matchingValidators.length > 0) {
293
+ console.log(
294
+ chalk.gray(
295
+ `šŸ›‘ Stopping ${matchingValidators.length} validator(s) using config "${configName}"...`
296
+ )
297
+ );
298
+
299
+ for (const validator of matchingValidators) {
300
+ await stopCommand(validator.id, {});
301
+ }
302
+ }
303
+
304
+ // Wait a moment for clean shutdown
305
+ await new Promise((resolve) => setTimeout(resolve, 2000));
306
+
307
+ // Temporarily enable reset for this start
308
+ const originalReset = currentConfig.localnet.reset;
309
+ currentConfig.localnet.reset = true;
310
+
311
+ console.log(
312
+ chalk.cyan(
313
+ "šŸš€ Starting validator with reset to apply program changes..."
314
+ )
315
+ );
316
+
317
+ // Start new validator (will reset due to config)
318
+ await startCommand(false);
319
+
320
+ // Restore original reset setting
321
+ currentConfig.localnet.reset = originalReset;
322
+ await configManager.save("./sf.config.json");
323
+ }
324
+ } else {
325
+ console.log(
326
+ chalk.gray(
327
+ "\nšŸ’” Start a validator to use the new program: solforge start"
328
+ )
329
+ );
330
+ }
331
+ } catch (error) {
332
+ console.error(chalk.red("āŒ Failed to add program:"));
333
+ console.error(
334
+ chalk.red(` ${error instanceof Error ? error.message : String(error)}`)
335
+ );
336
+ }
337
+ }
@@ -0,0 +1,122 @@
1
+ import { writeFileSync, existsSync } from "fs";
2
+ import { resolve } from "path";
3
+ import chalk from "chalk";
4
+ import inquirer from "inquirer";
5
+ import type { Config } from "../types/config.js";
6
+
7
+ const defaultConfig: Config = {
8
+ name: "my-localnet",
9
+ description: "Local Solana development environment",
10
+ tokens: [
11
+ {
12
+ symbol: "USDC",
13
+ mainnetMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
14
+ recipients: [],
15
+ mintAmount: 1000000,
16
+ cloneMetadata: true,
17
+ },
18
+ ],
19
+ programs: [],
20
+ localnet: {
21
+ airdropAmount: 100,
22
+ faucetAccounts: [],
23
+ port: 8899,
24
+ faucetPort: 9900,
25
+ reset: true,
26
+ logLevel: "info",
27
+ bindAddress: "127.0.0.1",
28
+ quiet: false,
29
+ rpc: "https://mainnet.helius-rpc.com/?api-key=3a3b84ef-2985-4543-9d67-535eb707b6ec",
30
+ limitLedgerSize: 100000,
31
+ },
32
+ };
33
+
34
+ export async function initCommand(): Promise<void> {
35
+ const configPath = resolve(process.cwd(), "sf.config.json");
36
+
37
+ // Check if config already exists
38
+ if (existsSync(configPath)) {
39
+ const { overwrite } = await inquirer.prompt([
40
+ {
41
+ type: "confirm",
42
+ name: "overwrite",
43
+ message: "sf.config.json already exists. Overwrite?",
44
+ default: false,
45
+ },
46
+ ]);
47
+
48
+ if (!overwrite) {
49
+ console.log(chalk.yellow("āš ļø Initialization cancelled"));
50
+ return;
51
+ }
52
+ }
53
+
54
+ // Gather basic configuration
55
+ const answers = await inquirer.prompt([
56
+ {
57
+ type: "input",
58
+ name: "name",
59
+ message: "Project name:",
60
+ default: "my-localnet",
61
+ },
62
+ {
63
+ type: "input",
64
+ name: "description",
65
+ message: "Description:",
66
+ default: "Local Solana development environment",
67
+ },
68
+ {
69
+ type: "number",
70
+ name: "port",
71
+ message: "RPC port:",
72
+ default: 8899,
73
+ },
74
+ {
75
+ type: "confirm",
76
+ name: "includeUsdc",
77
+ message: "Include USDC token?",
78
+ default: true,
79
+ },
80
+ ]);
81
+
82
+ // Build config
83
+ const config: Config = {
84
+ ...defaultConfig,
85
+ name: answers.name,
86
+ description: answers.description,
87
+ localnet: {
88
+ ...defaultConfig.localnet,
89
+ port: answers.port,
90
+ },
91
+ };
92
+
93
+ if (!answers.includeUsdc) {
94
+ config.tokens = [];
95
+ }
96
+
97
+ try {
98
+ // Write config file
99
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
100
+
101
+ console.log(chalk.green("āœ… sf.config.json created successfully!"));
102
+ console.log(chalk.gray(`šŸ“„ Config saved to: ${configPath}`));
103
+ console.log();
104
+ console.log(chalk.blue("Next steps:"));
105
+ console.log(
106
+ chalk.gray("1. Edit sf.config.json to add your tokens and programs")
107
+ );
108
+ console.log(chalk.gray("2. Run `solforge start` to launch your localnet"));
109
+ console.log();
110
+ console.log(
111
+ chalk.yellow(
112
+ "šŸ’” Tip: Check configs/example.sf.config.json for more examples"
113
+ )
114
+ );
115
+ } catch (error) {
116
+ console.error(chalk.red("āŒ Failed to create sf.config.json"));
117
+ console.error(
118
+ chalk.red(error instanceof Error ? error.message : String(error))
119
+ );
120
+ process.exit(1);
121
+ }
122
+ }
@@ -0,0 +1,136 @@
1
+ import chalk from "chalk";
2
+ import { processRegistry } from "../services/process-registry.js";
3
+ import type { RunningValidator } from "../services/process-registry.js";
4
+
5
+ export async function listCommand(): Promise<void> {
6
+ console.log(chalk.blue("šŸ“‹ Listing running validators...\n"));
7
+
8
+ // Clean up dead processes first
9
+ await processRegistry.cleanup();
10
+
11
+ const validators = processRegistry.getRunning();
12
+
13
+ if (validators.length === 0) {
14
+ console.log(chalk.yellow("āš ļø No running validators found"));
15
+ console.log(chalk.gray("šŸ’” Use `solforge start` to start a validator"));
16
+ return;
17
+ }
18
+
19
+ // Verify each validator is actually still running
20
+ const activeValidators: RunningValidator[] = [];
21
+ for (const validator of validators) {
22
+ const isRunning = await processRegistry.isProcessRunning(validator.pid);
23
+ if (isRunning) {
24
+ activeValidators.push({ ...validator, status: "running" });
25
+ } else {
26
+ processRegistry.updateStatus(validator.id, "stopped");
27
+ }
28
+ }
29
+
30
+ if (activeValidators.length === 0) {
31
+ console.log(
32
+ chalk.yellow(
33
+ "āš ļø No active validators found (all processes have stopped)"
34
+ )
35
+ );
36
+ console.log(chalk.gray("šŸ’” Use `solforge start` to start a validator"));
37
+ return;
38
+ }
39
+
40
+ console.log(
41
+ chalk.green(
42
+ `āœ… Found ${activeValidators.length} running validator${
43
+ activeValidators.length > 1 ? "s" : ""
44
+ }\n`
45
+ )
46
+ );
47
+
48
+ // Display validators in a table format
49
+ displayValidatorsTable(activeValidators);
50
+
51
+ console.log(
52
+ chalk.gray("\nšŸ’” Use `solforge stop <id>` to stop a specific validator")
53
+ );
54
+ console.log(
55
+ chalk.gray("šŸ’” Use `solforge stop --all` to stop all validators")
56
+ );
57
+ }
58
+
59
+ function displayValidatorsTable(validators: RunningValidator[]): void {
60
+ // Calculate column widths
61
+ const maxIdWidth = Math.max(2, ...validators.map((v) => v.id.length));
62
+ const maxNameWidth = Math.max(4, ...validators.map((v) => v.name.length));
63
+ const maxPidWidth = Math.max(
64
+ 3,
65
+ ...validators.map((v) => v.pid.toString().length)
66
+ );
67
+ const maxPortWidth = 9; // "8899/9900" format
68
+ const maxUptimeWidth = 7;
69
+
70
+ // Header
71
+ const header =
72
+ chalk.bold("ID".padEnd(maxIdWidth)) +
73
+ " | " +
74
+ chalk.bold("Name".padEnd(maxNameWidth)) +
75
+ " | " +
76
+ chalk.bold("PID".padEnd(maxPidWidth)) +
77
+ " | " +
78
+ chalk.bold("RPC/Faucet".padEnd(maxPortWidth)) +
79
+ " | " +
80
+ chalk.bold("Uptime".padEnd(maxUptimeWidth)) +
81
+ " | " +
82
+ chalk.bold("Status");
83
+
84
+ console.log(header);
85
+ console.log("-".repeat(header.length - 20)); // Subtract ANSI codes length
86
+
87
+ // Rows
88
+ validators.forEach((validator) => {
89
+ const uptime = formatUptime(validator.startTime);
90
+ const ports = `${validator.rpcPort}/${validator.faucetPort}`;
91
+ const status =
92
+ validator.status === "running" ? chalk.green("ā—") : chalk.red("ā—");
93
+
94
+ const row =
95
+ validator.id.padEnd(maxIdWidth) +
96
+ " | " +
97
+ validator.name.padEnd(maxNameWidth) +
98
+ " | " +
99
+ validator.pid.toString().padEnd(maxPidWidth) +
100
+ " | " +
101
+ ports.padEnd(maxPortWidth) +
102
+ " | " +
103
+ uptime.padEnd(maxUptimeWidth) +
104
+ " | " +
105
+ status;
106
+
107
+ console.log(row);
108
+ });
109
+
110
+ console.log(); // Empty line
111
+
112
+ // URLs section
113
+ console.log(chalk.cyan("🌐 Connection URLs:"));
114
+ validators.forEach((validator) => {
115
+ console.log(chalk.gray(` ${validator.name} (${validator.id}):`));
116
+ console.log(chalk.gray(` RPC: ${validator.rpcUrl}`));
117
+ console.log(chalk.gray(` Faucet: ${validator.faucetUrl}`));
118
+ });
119
+ }
120
+
121
+ function formatUptime(startTime: Date): string {
122
+ const now = new Date();
123
+ const uptimeMs = now.getTime() - startTime.getTime();
124
+ const uptimeSeconds = Math.floor(uptimeMs / 1000);
125
+
126
+ if (uptimeSeconds < 60) {
127
+ return `${uptimeSeconds}s`;
128
+ } else if (uptimeSeconds < 3600) {
129
+ const minutes = Math.floor(uptimeSeconds / 60);
130
+ return `${minutes}m`;
131
+ } else {
132
+ const hours = Math.floor(uptimeSeconds / 3600);
133
+ const minutes = Math.floor((uptimeSeconds % 3600) / 60);
134
+ return `${hours}h${minutes}m`;
135
+ }
136
+ }