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,155 @@
1
+ import { writeFileSync, readFileSync, existsSync } from "fs";
2
+ import { join } from "path";
3
+ import { homedir } from "os";
4
+ import type { Config } from "../types/config.js";
5
+
6
+ export interface RunningValidator {
7
+ id: string;
8
+ name: string;
9
+ pid: number;
10
+ rpcPort: number;
11
+ faucetPort: number;
12
+ rpcUrl: string;
13
+ faucetUrl: string;
14
+ configPath: string;
15
+ startTime: Date;
16
+ status: "running" | "stopped" | "error";
17
+ }
18
+
19
+ export class ProcessRegistry {
20
+ private registryPath: string;
21
+
22
+ constructor() {
23
+ // Store registry in user's home directory
24
+ this.registryPath = join(
25
+ homedir(),
26
+ ".solforge",
27
+ "running-validators.json"
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Get all running validators
33
+ */
34
+ getRunning(): RunningValidator[] {
35
+ if (!existsSync(this.registryPath)) {
36
+ return [];
37
+ }
38
+
39
+ try {
40
+ const content = readFileSync(this.registryPath, "utf-8");
41
+ const validators = JSON.parse(content) as RunningValidator[];
42
+
43
+ // Convert startTime strings back to Date objects
44
+ return validators.map((v) => ({
45
+ ...v,
46
+ startTime: new Date(v.startTime),
47
+ }));
48
+ } catch {
49
+ return [];
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Register a new running validator
55
+ */
56
+ register(validator: RunningValidator): void {
57
+ const validators = this.getRunning();
58
+
59
+ // Remove any existing entry with the same ID
60
+ const updated = validators.filter((v) => v.id !== validator.id);
61
+ updated.push(validator);
62
+
63
+ this.save(updated);
64
+ }
65
+
66
+ /**
67
+ * Unregister a validator
68
+ */
69
+ unregister(id: string): void {
70
+ const validators = this.getRunning();
71
+ const updated = validators.filter((v) => v.id !== id);
72
+ this.save(updated);
73
+ }
74
+
75
+ /**
76
+ * Update validator status
77
+ */
78
+ updateStatus(id: string, status: RunningValidator["status"]): void {
79
+ const validators = this.getRunning();
80
+ const validator = validators.find((v) => v.id === id);
81
+
82
+ if (validator) {
83
+ validator.status = status;
84
+ this.save(validators);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Get validator by ID
90
+ */
91
+ getById(id: string): RunningValidator | undefined {
92
+ return this.getRunning().find((v) => v.id === id);
93
+ }
94
+
95
+ /**
96
+ * Get validator by PID
97
+ */
98
+ getByPid(pid: number): RunningValidator | undefined {
99
+ return this.getRunning().find((v) => v.pid === pid);
100
+ }
101
+
102
+ /**
103
+ * Get validator by port
104
+ */
105
+ getByPort(port: number): RunningValidator | undefined {
106
+ return this.getRunning().find(
107
+ (v) => v.rpcPort === port || v.faucetPort === port
108
+ );
109
+ }
110
+
111
+ /**
112
+ * Check if a process is actually running
113
+ */
114
+ async isProcessRunning(pid: number): Promise<boolean> {
115
+ try {
116
+ // Send signal 0 to check if process exists
117
+ process.kill(pid, 0);
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Clean up dead processes from registry
126
+ */
127
+ async cleanup(): Promise<void> {
128
+ const validators = this.getRunning();
129
+ const active: RunningValidator[] = [];
130
+
131
+ for (const validator of validators) {
132
+ if (await this.isProcessRunning(validator.pid)) {
133
+ active.push(validator);
134
+ }
135
+ }
136
+
137
+ this.save(active);
138
+ }
139
+
140
+ /**
141
+ * Save validators to registry file
142
+ */
143
+ private save(validators: RunningValidator[]): void {
144
+ // Ensure directory exists
145
+ const dir = join(homedir(), ".solforge");
146
+ if (!existsSync(dir)) {
147
+ require("fs").mkdirSync(dir, { recursive: true });
148
+ }
149
+
150
+ writeFileSync(this.registryPath, JSON.stringify(validators, null, 2));
151
+ }
152
+ }
153
+
154
+ // Singleton instance
155
+ export const processRegistry = new ProcessRegistry();
@@ -0,0 +1,317 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
2
+ import { join } from "path";
3
+ import chalk from "chalk";
4
+ import { Connection, PublicKey } from "@solana/web3.js";
5
+ import { runCommand } from "../utils/shell.js";
6
+ import type { ProgramConfig } from "../types/config.js";
7
+
8
+ export class ProgramCloner {
9
+ private workDir: string;
10
+
11
+ constructor(workDir: string = ".solforge") {
12
+ this.workDir = workDir;
13
+ }
14
+
15
+ /**
16
+ * Clone programs for validator startup (saved as .so files)
17
+ */
18
+ async clonePrograms(
19
+ programs: ProgramConfig[],
20
+ targetCluster: string = "mainnet-beta"
21
+ ): Promise<
22
+ Array<{
23
+ success: boolean;
24
+ program: ProgramConfig;
25
+ error?: string;
26
+ filePath?: string;
27
+ }>
28
+ > {
29
+ console.log(chalk.cyan("\nšŸ”§ Cloning programs from mainnet..."));
30
+
31
+ if (!existsSync(this.workDir)) {
32
+ mkdirSync(this.workDir, { recursive: true });
33
+ }
34
+
35
+ const programsDir = join(this.workDir, "programs");
36
+ if (!existsSync(programsDir)) {
37
+ mkdirSync(programsDir, { recursive: true });
38
+ }
39
+
40
+ const results = [];
41
+
42
+ for (const program of programs) {
43
+ console.log(
44
+ chalk.gray(
45
+ ` šŸ“¦ Processing ${program.name || program.mainnetProgramId}...`
46
+ )
47
+ );
48
+
49
+ try {
50
+ // Clone dependencies first
51
+ if (program.dependencies && program.dependencies.length > 0) {
52
+ console.log(
53
+ chalk.gray(
54
+ ` šŸ“š Cloning ${program.dependencies.length} dependencies...`
55
+ )
56
+ );
57
+ for (const depId of program.dependencies) {
58
+ await this.cloneSingleProgram(depId, programsDir, targetCluster);
59
+ }
60
+ }
61
+
62
+ // Clone the main program
63
+ const result = await this.cloneSingleProgram(
64
+ program.mainnetProgramId,
65
+ programsDir,
66
+ targetCluster,
67
+ program.name
68
+ );
69
+
70
+ results.push({
71
+ success: true,
72
+ program,
73
+ filePath: result.filePath,
74
+ });
75
+
76
+ console.log(chalk.gray(` āœ“ Cloned to ${result.filePath}`));
77
+ } catch (error) {
78
+ console.error(
79
+ chalk.red(` āŒ Failed to clone ${program.mainnetProgramId}`)
80
+ );
81
+ console.error(
82
+ chalk.red(
83
+ ` ${error instanceof Error ? error.message : String(error)}`
84
+ )
85
+ );
86
+
87
+ results.push({
88
+ success: false,
89
+ program,
90
+ error: error instanceof Error ? error.message : String(error),
91
+ });
92
+ }
93
+ }
94
+
95
+ const successful = results.filter((r) => r.success).length;
96
+ console.log(
97
+ chalk.cyan(`\nāœ… Cloned ${successful}/${programs.length} programs`)
98
+ );
99
+
100
+ return results;
101
+ }
102
+
103
+ /**
104
+ * Clone a single program from mainnet
105
+ */
106
+ private async cloneSingleProgram(
107
+ programId: string,
108
+ outputDir: string,
109
+ cluster: string = "mainnet-beta",
110
+ name?: string
111
+ ): Promise<{ filePath: string }> {
112
+ const fileName = name
113
+ ? `${name.toLowerCase().replace(/\s+/g, "-")}.so`
114
+ : `${programId}.so`;
115
+ const outputPath = join(outputDir, fileName);
116
+
117
+ // Skip if already exists
118
+ if (existsSync(outputPath)) {
119
+ return { filePath: outputPath };
120
+ }
121
+
122
+ // Use solana account command to fetch program data
123
+ const rpcUrl = this.getClusterUrl(cluster);
124
+ const accountResult = await runCommand(
125
+ "solana",
126
+ ["account", programId, "--output", "json", "--url", rpcUrl],
127
+ { silent: true }
128
+ );
129
+
130
+ if (!accountResult.success) {
131
+ throw new Error(
132
+ `Failed to fetch program account: ${accountResult.stderr}`
133
+ );
134
+ }
135
+
136
+ try {
137
+ const accountData = JSON.parse(accountResult.stdout);
138
+ const programData = accountData.account.data;
139
+
140
+ if (!programData || programData[1] !== "base64") {
141
+ throw new Error("Invalid program data format");
142
+ }
143
+
144
+ // Decode base64 program data
145
+ const binaryData = Buffer.from(programData[0], "base64");
146
+
147
+ // Write as .so file
148
+ writeFileSync(outputPath, binaryData);
149
+
150
+ return { filePath: outputPath };
151
+ } catch (error) {
152
+ throw new Error(
153
+ `Failed to process program data: ${
154
+ error instanceof Error ? error.message : String(error)
155
+ }`
156
+ );
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Generate validator arguments for cloned programs
162
+ */
163
+ generateValidatorArgs(
164
+ clonedPrograms: Array<{
165
+ success: boolean;
166
+ program: ProgramConfig;
167
+ filePath?: string;
168
+ }>
169
+ ): string[] {
170
+ const args: string[] = [];
171
+
172
+ for (const result of clonedPrograms) {
173
+ if (result.success && result.filePath) {
174
+ args.push("--bpf-program");
175
+ args.push(result.program.mainnetProgramId);
176
+ args.push(result.filePath);
177
+ }
178
+ }
179
+
180
+ return args;
181
+ }
182
+
183
+ /**
184
+ * Deploy program to running validator (hot deployment)
185
+ */
186
+ async deployToRunningValidator(
187
+ programId: string,
188
+ rpcUrl: string,
189
+ name?: string
190
+ ): Promise<{ success: boolean; deployedAddress?: string; error?: string }> {
191
+ try {
192
+ console.log(
193
+ chalk.cyan(`\nšŸš€ Hot deploying program ${name || programId}...`)
194
+ );
195
+
196
+ // First, clone the program if we don't have it
197
+ const programsDir = join(this.workDir, "programs");
198
+ if (!existsSync(programsDir)) {
199
+ mkdirSync(programsDir, { recursive: true });
200
+ }
201
+
202
+ const cloneResult = await this.cloneSingleProgram(
203
+ programId,
204
+ programsDir,
205
+ "mainnet-beta",
206
+ name
207
+ );
208
+
209
+ // Deploy to running validator using solana program deploy
210
+ console.log(chalk.gray(" šŸ“¤ Deploying to validator..."));
211
+
212
+ const deployResult = await runCommand(
213
+ "solana",
214
+ [
215
+ "program",
216
+ "deploy",
217
+ cloneResult.filePath,
218
+ "--program-id",
219
+ programId,
220
+ "--url",
221
+ rpcUrl,
222
+ ],
223
+ { silent: false }
224
+ );
225
+
226
+ if (!deployResult.success) {
227
+ return {
228
+ success: false,
229
+ error: `Deployment failed: ${
230
+ deployResult.stderr || deployResult.stdout
231
+ }`,
232
+ };
233
+ }
234
+
235
+ console.log(
236
+ chalk.green(` āœ… Successfully deployed ${name || programId}`)
237
+ );
238
+
239
+ return {
240
+ success: true,
241
+ deployedAddress: programId,
242
+ };
243
+ } catch (error) {
244
+ return {
245
+ success: false,
246
+ error: error instanceof Error ? error.message : String(error),
247
+ };
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Get cluster RPC URL
253
+ */
254
+ private getClusterUrl(cluster: string): string {
255
+ switch (cluster) {
256
+ case "mainnet-beta":
257
+ return "https://api.mainnet-beta.solana.com";
258
+ case "devnet":
259
+ return "https://api.devnet.solana.com";
260
+ case "testnet":
261
+ return "https://api.testnet.solana.com";
262
+ default:
263
+ return cluster; // Assume it's a custom URL
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Verify program exists on cluster
269
+ */
270
+ async verifyProgram(
271
+ programId: string,
272
+ cluster: string = "mainnet-beta"
273
+ ): Promise<boolean> {
274
+ try {
275
+ const connection = new Connection(this.getClusterUrl(cluster));
276
+ const programAccount = await connection.getAccountInfo(
277
+ new PublicKey(programId)
278
+ );
279
+ return programAccount !== null && programAccount.executable;
280
+ } catch {
281
+ return false;
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Get program info from cluster
287
+ */
288
+ async getProgramInfo(
289
+ programId: string,
290
+ cluster: string = "mainnet-beta"
291
+ ): Promise<{
292
+ exists: boolean;
293
+ executable?: boolean;
294
+ owner?: string;
295
+ size?: number;
296
+ }> {
297
+ try {
298
+ const connection = new Connection(this.getClusterUrl(cluster));
299
+ const programAccount = await connection.getAccountInfo(
300
+ new PublicKey(programId)
301
+ );
302
+
303
+ if (!programAccount) {
304
+ return { exists: false };
305
+ }
306
+
307
+ return {
308
+ exists: true,
309
+ executable: programAccount.executable,
310
+ owner: programAccount.owner.toBase58(),
311
+ size: programAccount.data.length,
312
+ };
313
+ } catch (error) {
314
+ return { exists: false };
315
+ }
316
+ }
317
+ }