@0xobelisk/sui-cli 1.2.0-pre.11 → 1.2.0-pre.110

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 (38) hide show
  1. package/README.md +3 -3
  2. package/dist/dubhe.js +126 -49
  3. package/dist/dubhe.js.map +1 -1
  4. package/package.json +31 -19
  5. package/src/commands/build.ts +47 -16
  6. package/src/commands/call.ts +83 -83
  7. package/src/commands/checkBalance.ts +12 -5
  8. package/src/commands/configStore.ts +12 -4
  9. package/src/commands/convertJson.ts +70 -0
  10. package/src/commands/doctor.ts +1515 -0
  11. package/src/commands/faucet.ts +11 -7
  12. package/src/commands/generateKey.ts +3 -2
  13. package/src/commands/index.ts +16 -7
  14. package/src/commands/info.ts +55 -0
  15. package/src/commands/loadMetadata.ts +57 -0
  16. package/src/commands/localnode.ts +22 -6
  17. package/src/commands/publish.ts +21 -7
  18. package/src/commands/query.ts +101 -101
  19. package/src/commands/schemagen.ts +15 -4
  20. package/src/commands/shell.ts +198 -0
  21. package/src/commands/switchEnv.ts +26 -0
  22. package/src/commands/test.ts +54 -11
  23. package/src/commands/upgrade.ts +11 -4
  24. package/src/commands/wait.ts +333 -22
  25. package/src/commands/watch.ts +2 -1
  26. package/src/dubhe.ts +12 -4
  27. package/src/utils/axios-downloader.ts +116 -0
  28. package/src/utils/callHandler.ts +118 -118
  29. package/src/utils/constants.ts +5 -0
  30. package/src/utils/generateAccount.ts +1 -1
  31. package/src/utils/index.ts +4 -3
  32. package/src/utils/metadataHandler.ts +16 -0
  33. package/src/utils/publishHandler.ts +330 -293
  34. package/src/utils/queryStorage.ts +141 -141
  35. package/src/utils/startNode.ts +115 -16
  36. package/src/utils/storeConfig.ts +6 -12
  37. package/src/utils/upgradeHandler.ts +147 -86
  38. package/src/utils/utils.ts +771 -55
@@ -1,141 +1,141 @@
1
- import { loadMetadata } from '@0xobelisk/sui-client';
2
- import { DubheCliError } from './errors';
3
- import { getOldPackageId, getSchemaId, initializeDubhe } from './utils';
4
- import { DubheConfig } from '@0xobelisk/sui-common';
5
- import * as fs from 'fs';
6
- import * as path from 'path';
7
-
8
- function validateParams(storageType: string, params: any[]): boolean {
9
- const formatStorageType = storageType.split('<')[0].trim();
10
- switch (formatStorageType) {
11
- case 'StorageValue':
12
- return params.length === 0;
13
- case 'StorageMap':
14
- return params.length === 1;
15
- case 'StorageDoubleMap':
16
- return params.length === 2;
17
- default:
18
- return false;
19
- }
20
- }
21
-
22
- function getExpectedParamsCount(storageType: string): number {
23
- const formatStorageType = storageType.split('<')[0].trim();
24
- switch (formatStorageType) {
25
- case 'StorageValue':
26
- return 0;
27
- case 'StorageMap':
28
- return 1;
29
- case 'StorageDoubleMap':
30
- return 2;
31
- default:
32
- return 0;
33
- }
34
- }
35
-
36
- export async function queryStorage({
37
- dubheConfig,
38
- schema,
39
- params,
40
- network,
41
- objectId,
42
- packageId,
43
- metadataFilePath
44
- }: {
45
- dubheConfig: DubheConfig;
46
- schema: string;
47
- params?: any[];
48
- network: 'mainnet' | 'testnet' | 'devnet' | 'localnet';
49
- objectId?: string;
50
- packageId?: string;
51
- metadataFilePath?: string;
52
- }) {
53
- const path = process.cwd();
54
- const projectPath = `${path}/contracts/${dubheConfig.name}`;
55
-
56
- packageId = packageId || (await getOldPackageId(projectPath, network));
57
-
58
- objectId = objectId || (await getSchemaId(projectPath, network));
59
-
60
- let metadata;
61
- if (metadataFilePath) {
62
- metadata = await loadMetadataFromFile(metadataFilePath);
63
- } else {
64
- metadata = await loadMetadata(network, packageId);
65
- }
66
- if (!metadata) {
67
- throw new DubheCliError(
68
- `Metadata file not found. Please provide a metadata file path or set the packageId.`
69
- );
70
- }
71
-
72
- if (!dubheConfig.schemas[schema]) {
73
- throw new DubheCliError(
74
- `Schema "${schema}" not found in dubhe config. Available schemas: ${Object.keys(
75
- dubheConfig.schemas
76
- ).join(', ')}`
77
- );
78
- }
79
-
80
- const storageType = dubheConfig.schemas[schema];
81
-
82
- const processedParams = params || [];
83
- if (!validateParams(storageType, processedParams)) {
84
- throw new Error(
85
- `Invalid params count for ${storageType}. ` +
86
- `Expected: ${getExpectedParamsCount(storageType)}, ` +
87
- `Got: ${processedParams.length}`
88
- );
89
- }
90
-
91
- const dubhe = initializeDubhe({
92
- network,
93
- packageId,
94
- metadata
95
- });
96
- const result = await dubhe.parseState({
97
- schema,
98
- objectId,
99
- storageType,
100
- params: processedParams
101
- });
102
-
103
- console.log(result);
104
- }
105
-
106
- /**
107
- * Load metadata from a JSON file and construct the metadata structure
108
- * @param metadataFilePath Path to the metadata JSON file
109
- * @param network Network type
110
- * @param packageId Package ID
111
- * @returns Constructed metadata object
112
- */
113
- export async function loadMetadataFromFile(metadataFilePath: string) {
114
- // Verify file extension is .json
115
- if (path.extname(metadataFilePath) !== '.json') {
116
- throw new Error('Metadata file must be in JSON format');
117
- }
118
-
119
- try {
120
- // Read JSON file content
121
- const rawData = fs.readFileSync(metadataFilePath, 'utf8');
122
- const jsonData = JSON.parse(rawData);
123
-
124
- // Validate JSON structure
125
- if (!jsonData || typeof jsonData !== 'object') {
126
- throw new Error('Invalid JSON format');
127
- }
128
-
129
- // Construct metadata structure
130
- const metadata = {
131
- ...jsonData
132
- };
133
-
134
- return metadata;
135
- } catch (error) {
136
- if (error instanceof Error) {
137
- throw new Error(`Failed to read metadata file: ${error.message}`);
138
- }
139
- throw error;
140
- }
141
- }
1
+ // import { loadMetadata } from '@0xobelisk/sui-client';
2
+ // import { DubheCliError } from './errors';
3
+ // import { getOldPackageId, getSchemaId, initializeDubhe } from './utils';
4
+ // import { DubheConfig } from '@0xobelisk/sui-common';
5
+ // import * as fs from 'fs';
6
+ // import * as path from 'path';
7
+
8
+ // function validateParams(storageType: string, params: any[]): boolean {
9
+ // const formatStorageType = storageType.split('<')[0].trim();
10
+ // switch (formatStorageType) {
11
+ // case 'StorageValue':
12
+ // return params.length === 0;
13
+ // case 'StorageMap':
14
+ // return params.length === 1;
15
+ // case 'StorageDoubleMap':
16
+ // return params.length === 2;
17
+ // default:
18
+ // return false;
19
+ // }
20
+ // }
21
+
22
+ // function getExpectedParamsCount(storageType: string): number {
23
+ // const formatStorageType = storageType.split('<')[0].trim();
24
+ // switch (formatStorageType) {
25
+ // case 'StorageValue':
26
+ // return 0;
27
+ // case 'StorageMap':
28
+ // return 1;
29
+ // case 'StorageDoubleMap':
30
+ // return 2;
31
+ // default:
32
+ // return 0;
33
+ // }
34
+ // }
35
+
36
+ // export async function queryStorage({
37
+ // dubheConfig,
38
+ // schema,
39
+ // params,
40
+ // network,
41
+ // objectId,
42
+ // packageId,
43
+ // metadataFilePath
44
+ // }: {
45
+ // dubheConfig: DubheConfig;
46
+ // schema: string;
47
+ // params?: any[];
48
+ // network: 'mainnet' | 'testnet' | 'devnet' | 'localnet';
49
+ // objectId?: string;
50
+ // packageId?: string;
51
+ // metadataFilePath?: string;
52
+ // }) {
53
+ // const path = process.cwd();
54
+ // const projectPath = `${path}/src/${dubheConfig.name}`;
55
+
56
+ // packageId = packageId || (await getOldPackageId(projectPath, network));
57
+
58
+ // objectId = objectId || (await getSchemaId(projectPath, network));
59
+
60
+ // let metadata;
61
+ // if (metadataFilePath) {
62
+ // metadata = await loadMetadataFromFile(metadataFilePath);
63
+ // } else {
64
+ // metadata = await loadMetadata(network, packageId);
65
+ // }
66
+ // if (!metadata) {
67
+ // throw new DubheCliError(
68
+ // `Metadata file not found. Please provide a metadata file path or set the packageId.`
69
+ // );
70
+ // }
71
+
72
+ // if (!dubheConfig.schemas[schema]) {
73
+ // throw new DubheCliError(
74
+ // `Schema "${schema}" not found in dubhe config. Available schemas: ${Object.keys(
75
+ // dubheConfig.schemas
76
+ // ).join(', ')}`
77
+ // );
78
+ // }
79
+
80
+ // const storageType = dubheConfig.schemas[schema];
81
+
82
+ // const processedParams = params || [];
83
+ // if (!validateParams(storageType, processedParams)) {
84
+ // throw new Error(
85
+ // `Invalid params count for ${storageType}. ` +
86
+ // `Expected: ${getExpectedParamsCount(storageType)}, ` +
87
+ // `Got: ${processedParams.length}`
88
+ // );
89
+ // }
90
+
91
+ // const dubhe = initializeDubhe({
92
+ // network,
93
+ // packageId,
94
+ // metadata
95
+ // });
96
+ // const result = await dubhe.parseState({
97
+ // schema,
98
+ // objectId,
99
+ // storageType,
100
+ // params: processedParams
101
+ // });
102
+
103
+ // console.log(result);
104
+ // }
105
+
106
+ // /**
107
+ // * Load metadata from a JSON file and construct the metadata structure
108
+ // * @param metadataFilePath Path to the metadata JSON file
109
+ // * @param network Network type
110
+ // * @param packageId Package ID
111
+ // * @returns Constructed metadata object
112
+ // */
113
+ // export async function loadMetadataFromFile(metadataFilePath: string) {
114
+ // // Verify file extension is .json
115
+ // if (path.extname(metadataFilePath) !== '.json') {
116
+ // throw new Error('Metadata file must be in JSON format');
117
+ // }
118
+
119
+ // try {
120
+ // // Read JSON file content
121
+ // const rawData = fs.readFileSync(metadataFilePath, 'utf8');
122
+ // const jsonData = JSON.parse(rawData);
123
+
124
+ // // Validate JSON structure
125
+ // if (!jsonData || typeof jsonData !== 'object') {
126
+ // throw new Error('Invalid JSON format');
127
+ // }
128
+
129
+ // // Construct metadata structure
130
+ // const metadata = {
131
+ // ...jsonData
132
+ // };
133
+
134
+ // return metadata;
135
+ // } catch (error) {
136
+ // if (error instanceof Error) {
137
+ // throw new Error(`Failed to read metadata file: ${error.message}`);
138
+ // }
139
+ // throw error;
140
+ // }
141
+ // }
@@ -3,19 +3,105 @@ import chalk from 'chalk';
3
3
  import { printDubhe } from './printDubhe';
4
4
  import { delay, DubheCliError, validatePrivateKey } from '../utils';
5
5
  import { Dubhe } from '@0xobelisk/sui-client';
6
+ import * as fs from 'fs';
7
+
8
+ export function stopLocalNode(): void {
9
+ console.log(chalk.yellow('🔔 Stopping existing Local Node...'));
10
+
11
+ let processStopped = false;
12
+
13
+ if (process.platform === 'win32') {
14
+ // Windows: Kill all sui.exe processes
15
+ try {
16
+ execSync('taskkill /F /IM sui.exe', { stdio: 'ignore' });
17
+ processStopped = true;
18
+ } catch (_error) {
19
+ // Process not found
20
+ }
21
+ } else {
22
+ // Unix-like systems: Try multiple patterns to find sui processes
23
+ const patterns = [
24
+ 'sui start', // Exact match
25
+ 'sui.*start', // Pattern with any flags
26
+ '^sui', // Any sui command
27
+ 'sui.*--with-faucet' // Match our specific startup pattern
28
+ ];
29
+
30
+ for (const pattern of patterns) {
31
+ try {
32
+ const result = execSync(`pgrep -f "${pattern}"`, { stdio: 'pipe' }).toString().trim();
33
+ if (result) {
34
+ const pids = result.split('\n').filter((pid) => pid);
35
+ console.log(chalk.cyan(` ├─ Found ${pids.length} process(es) matching "${pattern}"`));
36
+
37
+ pids.forEach((pid) => {
38
+ try {
39
+ // First try graceful termination
40
+ execSync(`kill -TERM ${pid}`, { stdio: 'ignore' });
41
+ console.log(chalk.cyan(` ├─ Sent SIGTERM to process ${pid}`));
42
+ } catch (_error) {
43
+ // If graceful termination fails, force kill
44
+ try {
45
+ execSync(`kill -KILL ${pid}`, { stdio: 'ignore' });
46
+ console.log(chalk.cyan(` ├─ Force killed process ${pid}`));
47
+ } catch (_killError) {
48
+ console.log(chalk.gray(` ├─ Process ${pid} already terminated`));
49
+ }
50
+ }
51
+ });
52
+ processStopped = true;
53
+ break; // Stop after first successful pattern match
54
+ }
55
+ } catch (_error) {
56
+ // This pattern didn't match any processes, continue to next pattern
57
+ continue;
58
+ }
59
+ }
60
+ }
61
+
62
+ if (processStopped) {
63
+ console.log(chalk.green(' └─ Local Node stopped successfully'));
64
+ } else {
65
+ console.log(chalk.gray(' └─ No running Local Node found'));
66
+ }
67
+ }
68
+
69
+ export function removeDirectory(dirPath: string): void {
70
+ try {
71
+ if (fs.existsSync(dirPath)) {
72
+ console.log(chalk.yellow(`🗑️ Removing directory: ${dirPath}`));
73
+ fs.rmSync(dirPath, { recursive: true, force: true });
74
+ console.log(chalk.green(' └─ Directory removed successfully'));
75
+ } else {
76
+ console.log(chalk.gray(` └─ Directory ${dirPath} does not exist`));
77
+ }
78
+ } catch (error: any) {
79
+ console.error(chalk.red(` └─ Error removing directory: ${error.message}`));
80
+ }
81
+ }
6
82
 
7
83
  function isSuiStartRunning(): boolean {
8
84
  try {
9
- const cmd =
10
- process.platform === 'win32'
11
- ? `tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH`
12
- : 'pgrep -f "sui start"';
13
-
14
- const result = execSync(cmd).toString().trim();
15
- return process.platform === 'win32'
16
- ? result.toLowerCase().includes('sui.exe')
17
- : result.length > 0;
18
- } catch (error) {
85
+ if (process.platform === 'win32') {
86
+ const result = execSync(`tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH`).toString().trim();
87
+ return result.toLowerCase().includes('sui.exe');
88
+ } else {
89
+ // Try multiple patterns to detect running sui processes
90
+ const patterns = ['sui start', 'sui.*start', '^sui', 'sui.*--with-faucet'];
91
+
92
+ for (const pattern of patterns) {
93
+ try {
94
+ const result = execSync(`pgrep -f "${pattern}"`, { stdio: 'pipe' }).toString().trim();
95
+ if (result && result.length > 0) {
96
+ return true;
97
+ }
98
+ } catch (_error) {
99
+ continue;
100
+ }
101
+ }
102
+ return false;
103
+ }
104
+ } catch (_error) {
19
105
  return false;
20
106
  }
21
107
  }
@@ -78,8 +164,15 @@ function handleProcessSignals(suiProcess: ReturnType<typeof spawn> | null) {
78
164
  process.on('SIGTERM', cleanup);
79
165
  }
80
166
 
81
- export async function startLocalNode() {
82
- if (isSuiStartRunning()) {
167
+ export async function startLocalNode(data_dir: string, force?: boolean) {
168
+ if (force) {
169
+ console.log(chalk.cyan('\n🔄 Force mode enabled'));
170
+ stopLocalNode();
171
+ console.log(chalk.yellow(' ├─ Waiting for processes to terminate...'));
172
+ await delay(3000); // Wait longer for process to fully stop
173
+ removeDirectory(data_dir);
174
+ console.log('');
175
+ } else if (isSuiStartRunning()) {
83
176
  console.log(chalk.yellow('\n⚠️ Warning: Local Node Already Running'));
84
177
  console.log(chalk.yellow(' ├─ Cannot start a new instance'));
85
178
  console.log(chalk.yellow(' └─ Please stop the existing process first'));
@@ -90,7 +183,13 @@ export async function startLocalNode() {
90
183
  console.log('🚀 Starting Local Node...');
91
184
  let suiProcess: ReturnType<typeof spawn> | null = null;
92
185
  try {
93
- suiProcess = spawn('sui', ['start', '--with-faucet', '--force-regenesis'], {
186
+ const args = ['start', '--with-faucet'];
187
+ if (force) {
188
+ args.push('--force-regenesis');
189
+ }
190
+ args.push('--data-ingestion-dir', data_dir);
191
+
192
+ suiProcess = spawn('sui', args, {
94
193
  env: { ...process.env, RUST_LOG: 'off,sui_node=info' },
95
194
  stdio: 'ignore'
96
195
  });
@@ -101,8 +200,8 @@ export async function startLocalNode() {
101
200
  });
102
201
  await delay(5000);
103
202
  console.log(' ├─ Faucet: Enabled');
104
- console.log(' └─ Force Regenesis: Yes');
105
- console.log(' └─ HTTP server: http://127.0.0.1:9000/');
203
+ console.log(` ├─ Force Regenesis: ${force ? 'Yes' : 'No'}`);
204
+ console.log(' ├─ RPC server: http://127.0.0.1:9000/');
106
205
  console.log(' └─ Faucet server: http://127.0.0.1:9123/');
107
206
 
108
207
  await printAccounts();
@@ -131,4 +230,4 @@ export async function startLocalNode() {
131
230
  }
132
231
  process.exit(1);
133
232
  }
134
- }
233
+ }
@@ -1,21 +1,15 @@
1
1
  import { mkdirSync, writeFileSync } from 'fs';
2
2
  import { dirname } from 'path';
3
3
  import { DubheConfig } from '@0xobelisk/sui-common';
4
- import { getDeploymentJson, getDubheSchemaId } from './utils';
4
+ import { getDeploymentJson, getDubheDappHub } from './utils';
5
5
 
6
- async function storeConfig(
7
- network: string,
8
- packageId: string,
9
- schemaId: string,
10
- outputPath: string
11
- ) {
12
- const dubheSchemaId = await getDubheSchemaId(network);
6
+ async function storeConfig(network: string, packageId: string, outputPath: string) {
7
+ const dubheDappHub = await getDubheDappHub(network);
13
8
  let code = `type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
14
9
 
15
10
  export const NETWORK: NetworkType = '${network}';
16
11
  export const PACKAGE_ID = '${packageId}';
17
- export const SCHEMA_ID = '${schemaId}';
18
- export const DUBHE_SCHEMA_ID = '${dubheSchemaId}';
12
+ export const DUBHE_SCHEMA_ID = '${dubheDappHub}';
19
13
  `;
20
14
 
21
15
  writeOutput(code, outputPath, 'storeConfig');
@@ -40,7 +34,7 @@ export async function storeConfigHandler(
40
34
  outputPath: string
41
35
  ) {
42
36
  const path = process.cwd();
43
- const contractPath = `${path}/contracts/${dubheConfig.name}`;
37
+ const contractPath = `${path}/src/${dubheConfig.name}`;
44
38
  const deployment = await getDeploymentJson(contractPath, network);
45
- await storeConfig(deployment.network, deployment.packageId, deployment.schemaId, outputPath);
39
+ await storeConfig(deployment.network, deployment.packageId, outputPath);
46
40
  }