genlayer 0.0.30 → 0.0.32-beta.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.
@@ -2,7 +2,7 @@ import * as fs from "fs";
2
2
  import * as dotenv from "dotenv";
3
3
  import * as path from "path";
4
4
 
5
- import {rpcClient} from "@/lib/clients/jsonRpcClient";
5
+ import {rpcClient} from "../clients/jsonRpcClient";
6
6
  import {
7
7
  DEFAULT_REPO_GH_URL,
8
8
  DOCKER_IMAGES_AND_CONTAINERS_NAME_PREFIX,
@@ -13,7 +13,7 @@ import {
13
13
  STARTING_TIMEOUT_ATTEMPTS,
14
14
  AI_PROVIDERS_CONFIG,
15
15
  AiProviders,
16
- } from "@/lib/config/simulator";
16
+ } from "../config/simulator";
17
17
  import {
18
18
  checkCommand,
19
19
  getHomeDirectory,
@@ -24,242 +24,253 @@ import {
24
24
  removeDockerContainer,
25
25
  listDockerImages,
26
26
  removeDockerImage,
27
- } from "@/lib/clients/system";
27
+ } from "../clients/system";
28
28
  import {MissingRequirementError} from "../errors/missingRequirement";
29
29
 
30
- // Private helper functions
31
- export function getSimulatorLocation(): string {
32
- return path.join(getHomeDirectory(), "genlayer-simulator");
33
- }
34
-
35
- export function readEnvConfigValue(key: string): string {
36
- const simulatorLocation = getSimulatorLocation();
37
- const envFilePath = path.join(simulatorLocation, ".env");
38
- // Transform the config string to object
39
- const envConfig = dotenv.parse(fs.readFileSync(envFilePath, "utf8"));
40
- return envConfig[key];
41
- }
30
+ import {
31
+ ISimulatorService,
32
+ DownloadSimulatorResultType,
33
+ WaitForSimulatorToBeReadyResultType,
34
+ InitializeDatabaseResultType,
35
+ } from "../interfaces/ISimulatorService";
42
36
 
43
37
  function sleep(millliseconds: number): Promise<void> {
44
38
  return new Promise(resolve => setTimeout(resolve, millliseconds));
45
39
  }
46
40
 
47
- function addConfigToEnvFile(newConfig: Record<string, string>): void {
48
- const simulatorLocation = getSimulatorLocation();
49
- const envFilePath = path.join(simulatorLocation, ".env");
41
+ export class SimulatorService implements ISimulatorService {
42
+ public getSimulatorLocation(): string {
43
+ return path.join(getHomeDirectory(), "genlayer-simulator");
44
+ }
50
45
 
51
- // Create a backup of the original .env file
52
- fs.writeFileSync(`${envFilePath}.bak`, fs.readFileSync(envFilePath));
46
+ public readEnvConfigValue(key: string): string {
47
+ const simulatorLocation = this.getSimulatorLocation();
48
+ const envFilePath = path.join(simulatorLocation, ".env");
49
+ // Transform the config string to object
50
+ const envConfig = dotenv.parse(fs.readFileSync(envFilePath, "utf8"));
51
+ return envConfig[key];
52
+ }
53
53
 
54
- // Transform the config string to object
55
- const envConfig = dotenv.parse(fs.readFileSync(envFilePath, "utf8"));
56
- Object.keys(newConfig).forEach(key => {
57
- envConfig[key] = newConfig[key];
58
- });
54
+ public addConfigToEnvFile(newConfig: Record<string, string>): void {
55
+ const simulatorLocation = this.getSimulatorLocation();
56
+ const envFilePath = path.join(simulatorLocation, ".env");
59
57
 
60
- // Transform the updated config object back into a string
61
- const updatedConfig = Object.keys(envConfig)
62
- .map(key => {
63
- return `${key}=${envConfig[key]}`;
64
- })
65
- .join("\n");
58
+ // Create a backup of the original .env file
59
+ fs.writeFileSync(`${envFilePath}.bak`, fs.readFileSync(envFilePath));
66
60
 
67
- // Write the new .env file
68
- fs.writeFileSync(envFilePath, updatedConfig);
69
- }
61
+ // Transform the config string to object
62
+ const envConfig = dotenv.parse(fs.readFileSync(envFilePath, "utf8"));
63
+ Object.keys(newConfig).forEach(key => {
64
+ envConfig[key] = newConfig[key];
65
+ });
70
66
 
71
- // Public functions
72
- export async function checkRequirements(): Promise<Record<string, boolean>> {
73
- const requirementsInstalled = {
74
- git: false,
75
- docker: false,
76
- };
77
-
78
- try {
79
- await checkCommand("git --version", "git");
80
- requirementsInstalled.git = true;
81
- } catch (error) {
82
- if (!(error instanceof MissingRequirementError)) {
83
- throw error;
84
- }
85
- }
86
- try {
87
- await checkCommand("docker --version", "docker");
88
- requirementsInstalled.docker = true;
89
- } catch (error: any) {
90
- if (!(error instanceof MissingRequirementError)) {
91
- throw error;
92
- }
67
+ // Transform the updated config object back into a string
68
+ const updatedConfig = Object.keys(envConfig)
69
+ .map(key => {
70
+ return `${key}=${envConfig[key]}`;
71
+ })
72
+ .join("\n");
73
+
74
+ // Write the new .env file
75
+ fs.writeFileSync(envFilePath, updatedConfig);
93
76
  }
94
77
 
95
- if (requirementsInstalled.docker) {
78
+ public async checkRequirements(): Promise<Record<string, boolean>> {
79
+ const requirementsInstalled = {
80
+ git: false,
81
+ docker: false,
82
+ };
83
+
96
84
  try {
97
- await checkCommand("docker ps", "docker");
85
+ await checkCommand("git --version", "git");
86
+ requirementsInstalled.git = true;
87
+ } catch (error) {
88
+ if (!(error instanceof MissingRequirementError)) {
89
+ throw error;
90
+ }
91
+ }
92
+ try {
93
+ await checkCommand("docker --version", "docker");
94
+ requirementsInstalled.docker = true;
98
95
  } catch (error: any) {
99
- await executeCommand(DEFAULT_RUN_DOCKER_COMMAND);
96
+ if (!(error instanceof MissingRequirementError)) {
97
+ throw error;
98
+ }
99
+ }
100
+
101
+ if (requirementsInstalled.docker) {
102
+ try {
103
+ await checkCommand("docker ps", "docker");
104
+ } catch (error: any) {
105
+ await executeCommand(DEFAULT_RUN_DOCKER_COMMAND);
106
+ }
100
107
  }
108
+
109
+ return requirementsInstalled;
101
110
  }
102
111
 
103
- return requirementsInstalled;
104
- }
112
+ public async downloadSimulator(branch: string = "main"): Promise<DownloadSimulatorResultType> {
113
+ const simulatorLocation = this.getSimulatorLocation();
105
114
 
106
- type DownloadSimulatorResultType = {
107
- wasInstalled: boolean;
108
- };
109
-
110
- export async function downloadSimulator(): Promise<DownloadSimulatorResultType> {
111
- const simulatorLocation = getSimulatorLocation();
112
-
113
- try {
114
- const gitCommand = `git clone ${DEFAULT_REPO_GH_URL} ${simulatorLocation}`;
115
- const cmdsByPlatform = {darwin: gitCommand, win32: gitCommand, linux: gitCommand};
116
- await executeCommand(cmdsByPlatform, "git");
117
- } catch (error: any) {
118
- const simulatorLocationExists = fs.existsSync(simulatorLocation);
119
- if (simulatorLocationExists) {
120
- return {wasInstalled: true};
115
+ try {
116
+ const gitCommand = `git clone -b ${branch} ${DEFAULT_REPO_GH_URL} ${simulatorLocation}`;
117
+ const cmdsByPlatform = {darwin: gitCommand, win32: gitCommand, linux: gitCommand};
118
+ await executeCommand(cmdsByPlatform, "git");
119
+ } catch (error: any) {
120
+ const simulatorLocationExists = fs.existsSync(simulatorLocation);
121
+ if (simulatorLocationExists) {
122
+ return {wasInstalled: true};
123
+ }
124
+ throw error;
121
125
  }
122
- throw error;
126
+ return {wasInstalled: false};
123
127
  }
124
- return {wasInstalled: false};
125
- }
126
128
 
127
- export async function updateSimulator(): Promise<DownloadSimulatorResultType> {
128
- const simulatorLocation = getSimulatorLocation();
129
- const gitCommand = `git -C "${simulatorLocation}" pull`;
130
- const cmdsByPlatform = {darwin: gitCommand, win32: gitCommand, linux: gitCommand};
131
- await executeCommand(cmdsByPlatform, "git");
132
- return {wasInstalled: false};
133
- }
129
+ public async updateSimulator(branch: string = "main"): Promise<boolean> {
130
+ const simulatorLocation = this.getSimulatorLocation();
131
+ const gitCleanCommand = `git -C "${simulatorLocation}" clean -f`;
132
+ const cleanCmdsByPlatform = {darwin: gitCleanCommand, win32: gitCleanCommand, linux: gitCleanCommand};
133
+ await executeCommand(cleanCmdsByPlatform, "git");
134
+
135
+ const gitFetchCommand = `git -C "${simulatorLocation}" fetch`;
136
+ const fetchCmdsByPlatform = {darwin: gitFetchCommand, win32: gitFetchCommand, linux: gitFetchCommand};
137
+ await executeCommand(fetchCmdsByPlatform, "git");
138
+
139
+ const gitCheckoutCommand = `git -C "${simulatorLocation}" checkout ${branch}`;
140
+ const checkoutCmdsByPlatform = {
141
+ darwin: gitCheckoutCommand,
142
+ win32: gitCheckoutCommand,
143
+ linux: gitCheckoutCommand,
144
+ };
145
+ await executeCommand(checkoutCmdsByPlatform, "git");
134
146
 
135
- export async function pullOllamaModel(): Promise<boolean> {
136
- const simulatorLocation = getSimulatorLocation();
137
- const cmdsByPlatform = DEFAULT_PULL_OLLAMA_COMMAND(simulatorLocation);
138
- await executeCommand(cmdsByPlatform);
139
- return true;
140
- }
147
+ const gitPullCommand = `git -C "${simulatorLocation}" pull`;
148
+ const pullCmdsByPlatform = {darwin: gitPullCommand, win32: gitPullCommand, linux: gitPullCommand};
149
+ await executeCommand(pullCmdsByPlatform, "git");
150
+ return true;
151
+ }
141
152
 
142
- export async function configSimulator(newConfig: Record<string, string>): Promise<boolean> {
143
- const simulatorLocation = getSimulatorLocation();
144
- const envExample = path.join(simulatorLocation, ".env.example");
145
- const envFilePath = path.join(simulatorLocation, ".env");
146
- fs.copyFileSync(envExample, envFilePath);
147
- addConfigToEnvFile(newConfig);
148
- return true;
149
- }
153
+ public async pullOllamaModel(): Promise<boolean> {
154
+ const simulatorLocation = this.getSimulatorLocation();
155
+ const cmdsByPlatform = DEFAULT_PULL_OLLAMA_COMMAND(simulatorLocation);
156
+ await executeCommand(cmdsByPlatform);
157
+ return true;
158
+ }
150
159
 
151
- export function runSimulator(): Promise<{stdout: string; stderr: string}> {
152
- const simulatorLocation = getSimulatorLocation();
153
- const commandsByPlatform = DEFAULT_RUN_SIMULATOR_COMMAND(simulatorLocation);
154
- return executeCommand(commandsByPlatform);
155
- }
160
+ public async configSimulator(newConfig: Record<string, string>): Promise<boolean> {
161
+ const simulatorLocation = this.getSimulatorLocation();
162
+ const envExample = path.join(simulatorLocation, ".env.example");
163
+ const envFilePath = path.join(simulatorLocation, ".env");
164
+ fs.copyFileSync(envExample, envFilePath);
165
+ this.addConfigToEnvFile(newConfig);
166
+ return true;
167
+ }
156
168
 
157
- type WaitForSimulatorToBeReadyResultType = {
158
- initialized: boolean;
159
- errorCode?: "TIMEOUT" | "ERROR";
160
- errorMessage?: string;
161
- };
162
-
163
- export async function waitForSimulatorToBeReady(
164
- retries: number = STARTING_TIMEOUT_ATTEMPTS,
165
- ): Promise<WaitForSimulatorToBeReadyResultType> {
166
- console.log("Waiting for the simulator to start up...");
167
- try {
168
- const response = await rpcClient.request({method: "ping", params: []});
169
- if (response && response.result.status === "OK") {
170
- return {initialized: true};
171
- }
172
- if (retries > 0) {
173
- await sleep(STARTING_TIMEOUT_WAIT_CYLCE);
174
- return waitForSimulatorToBeReady(retries - 1);
175
- }
176
- } catch (error: any) {
177
- if (
178
- (error.name === "FetchError" ||
179
- error.message.includes("ECONNRESET") ||
180
- error.message.includes("ECONNREFUSED") ||
181
- error.message.includes("socket hang up")) &&
182
- retries > 0
183
- ) {
184
- await sleep(STARTING_TIMEOUT_WAIT_CYLCE * 2);
185
- return waitForSimulatorToBeReady(retries - 1);
186
- }
187
- return {initialized: false, errorCode: "ERROR", errorMessage: error.message};
169
+ public runSimulator(): Promise<{stdout: string; stderr: string}> {
170
+ const simulatorLocation = this.getSimulatorLocation();
171
+ const commandsByPlatform = DEFAULT_RUN_SIMULATOR_COMMAND(simulatorLocation);
172
+ return executeCommand(commandsByPlatform);
188
173
  }
189
174
 
190
- return {initialized: false, errorCode: "TIMEOUT"};
191
- }
175
+ public async waitForSimulatorToBeReady(
176
+ retries: number = STARTING_TIMEOUT_ATTEMPTS,
177
+ ): Promise<WaitForSimulatorToBeReadyResultType> {
178
+ console.log("Waiting for the simulator to start up...");
179
+ try {
180
+ const response = await rpcClient.request({method: "ping", params: []});
181
+ if (response && response.result.status === "OK") {
182
+ return {initialized: true};
183
+ }
184
+ if (retries > 0) {
185
+ await sleep(STARTING_TIMEOUT_WAIT_CYLCE);
186
+ return this.waitForSimulatorToBeReady(retries - 1);
187
+ }
188
+ } catch (error: any) {
189
+ if (
190
+ (error.name === "FetchError" ||
191
+ error.message.includes("Fetch Error") ||
192
+ error.message.includes("ECONNRESET") ||
193
+ error.message.includes("ECONNREFUSED") ||
194
+ error.message.includes("socket hang up")) &&
195
+ retries > 0
196
+ ) {
197
+ await sleep(STARTING_TIMEOUT_WAIT_CYLCE * 2);
198
+ return this.waitForSimulatorToBeReady(retries - 1);
199
+ }
200
+ return {initialized: false, errorCode: "ERROR", errorMessage: error.message};
201
+ }
192
202
 
193
- export function clearAccountsAndTransactionsDatabase(): Promise<any> {
194
- return rpcClient.request({method: "clear_account_and_transactions_tables", params: []});
195
- }
203
+ return {initialized: false, errorCode: "TIMEOUT"};
204
+ }
196
205
 
197
- type InitializeDatabaseResultType = {
198
- createResponse: any;
199
- tablesResponse: any;
200
- };
206
+ public clearAccountsAndTransactionsDatabase(): Promise<any> {
207
+ return rpcClient.request({method: "clear_account_and_transactions_tables", params: []});
208
+ }
201
209
 
202
- export async function initializeDatabase(): Promise<InitializeDatabaseResultType> {
203
- const createResponse = await rpcClient.request({method: "create_db", params: []});
204
- const tablesResponse = await rpcClient.request({method: "create_tables", params: []});
205
- return {createResponse, tablesResponse};
206
- }
210
+ public async initializeDatabase(): Promise<InitializeDatabaseResultType> {
211
+ const createResponse = await rpcClient.request({method: "create_db", params: []});
212
+ const tablesResponse = await rpcClient.request({method: "create_tables", params: []});
213
+ return {createResponse, tablesResponse};
214
+ }
207
215
 
208
- export function createRandomValidators(numValidators: number, llmProviders: AiProviders[]): Promise<any> {
209
- return rpcClient.request({
210
- method: "create_random_validators",
211
- params: [numValidators, 1, 10, llmProviders],
212
- });
213
- }
216
+ public createRandomValidators(numValidators: number, llmProviders: AiProviders[]): Promise<any> {
217
+ return rpcClient.request({
218
+ method: "create_random_validators",
219
+ params: [numValidators, 1, 10, llmProviders],
220
+ });
221
+ }
214
222
 
215
- export function deleteAllValidators(): Promise<any> {
216
- return rpcClient.request({method: "delete_all_validators", params: []});
217
- }
223
+ public deleteAllValidators(): Promise<any> {
224
+ return rpcClient.request({method: "delete_all_validators", params: []});
225
+ }
218
226
 
219
- export function getAiProvidersOptions(withHint: boolean = true): Array<{name: string; value: string}> {
220
- return Object.values(AI_PROVIDERS_CONFIG).map(providerConfig => {
221
- return {
222
- name: `${providerConfig.name}${withHint ? ` ${providerConfig.hint}` : ""}`,
223
- value: providerConfig.cliOptionValue,
224
- };
225
- });
226
- }
227
+ public getAiProvidersOptions(withHint: boolean = true): Array<{name: string; value: string}> {
228
+ return Object.values(AI_PROVIDERS_CONFIG).map(providerConfig => {
229
+ return {
230
+ name: `${providerConfig.name}${withHint ? ` ${providerConfig.hint}` : ""}`,
231
+ value: providerConfig.cliOptionValue,
232
+ };
233
+ });
234
+ }
227
235
 
228
- export function getFrontendUrl(): string {
229
- const frontendPort = readEnvConfigValue("FRONTEND_PORT");
230
- return `http://localhost:${frontendPort}`;
231
- }
236
+ public getFrontendUrl(): string {
237
+ const frontendPort = this.readEnvConfigValue("FRONTEND_PORT");
238
+ return `http://localhost:${frontendPort}`;
239
+ }
232
240
 
233
- export async function openFrontend(): Promise<boolean> {
234
- await openUrl(getFrontendUrl());
235
- return true;
236
- }
241
+ public async openFrontend(): Promise<boolean> {
242
+ await openUrl(this.getFrontendUrl());
243
+ return true;
244
+ }
237
245
 
238
- export async function resetDockerContainers(): Promise<boolean> {
239
- const containers = await listDockerContainers();
240
- const genlayerContainers = containers.filter((container: string) =>
241
- container.startsWith(DOCKER_IMAGES_AND_CONTAINERS_NAME_PREFIX),
242
- );
243
- const containersStopPromises = genlayerContainers.map((container: string) =>
244
- stopDockerContainer(container),
245
- );
246
- await Promise.all(containersStopPromises);
247
-
248
- const containersRemovePromises = genlayerContainers.map((container: string) =>
249
- removeDockerContainer(container),
250
- );
251
- await Promise.all(containersRemovePromises);
252
-
253
- return true;
254
- }
246
+ public async resetDockerContainers(): Promise<boolean> {
247
+ const containers = await listDockerContainers();
248
+ const genlayerContainers = containers.filter((container: string) =>
249
+ container.startsWith(DOCKER_IMAGES_AND_CONTAINERS_NAME_PREFIX),
250
+ );
251
+ const containersStopPromises = genlayerContainers.map((container: string) =>
252
+ stopDockerContainer(container),
253
+ );
254
+ await Promise.all(containersStopPromises);
255
+
256
+ const containersRemovePromises = genlayerContainers.map((container: string) =>
257
+ removeDockerContainer(container),
258
+ );
259
+ await Promise.all(containersRemovePromises);
260
+
261
+ return true;
262
+ }
255
263
 
256
- export async function resetDockerImages(): Promise<boolean> {
257
- const images = await listDockerImages();
258
- const genlayerImages = images.filter((image: string) =>
259
- image.startsWith(DOCKER_IMAGES_AND_CONTAINERS_NAME_PREFIX),
260
- );
261
- const imagesRemovePromises = genlayerImages.map((image: string) => removeDockerImage(image));
262
- await Promise.all(imagesRemovePromises);
264
+ public async resetDockerImages(): Promise<boolean> {
265
+ const images = await listDockerImages();
266
+ const genlayerImages = images.filter((image: string) =>
267
+ image.startsWith(DOCKER_IMAGES_AND_CONTAINERS_NAME_PREFIX),
268
+ );
269
+ const imagesRemovePromises = genlayerImages.map((image: string) => removeDockerImage(image));
270
+ await Promise.all(imagesRemovePromises);
263
271
 
264
- return true;
272
+ return true;
273
+ }
265
274
  }
275
+
276
+ export default new SimulatorService();
@@ -0,0 +1 @@
1
+ declare module "node-fetch";