@0xobelisk/sui-cli 1.1.5 → 1.1.6

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.
@@ -6,115 +6,115 @@ import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
 
8
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
- }
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
20
  }
21
21
 
22
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
- }
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
34
  }
35
35
 
36
36
  export async function queryStorage({
37
- dubheConfig,
38
- schema,
39
- params,
40
- network,
41
- objectId,
42
- packageId,
43
- metadataFilePath,
37
+ dubheConfig,
38
+ schema,
39
+ params,
40
+ network,
41
+ objectId,
42
+ packageId,
43
+ metadataFilePath
44
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;
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
52
  }) {
53
- const privateKey = process.env.PRIVATE_KEY;
54
- if (!privateKey) {
55
- throw new DubheCliError(
56
- `Missing PRIVATE_KEY environment variable.
53
+ const privateKey = process.env.PRIVATE_KEY;
54
+ if (!privateKey) {
55
+ throw new DubheCliError(
56
+ `Missing PRIVATE_KEY environment variable.
57
57
  Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
58
58
  in your contracts directory to use the default sui private key.`
59
- );
60
- }
61
- const privateKeyFormat = validatePrivateKey(privateKey);
62
- if (privateKeyFormat === false) {
63
- throw new DubheCliError(`Please check your privateKey.`);
64
- }
65
-
66
- const path = process.cwd();
67
- const projectPath = `${path}/contracts/${dubheConfig.name}`;
68
-
69
- packageId = packageId || (await getOldPackageId(projectPath, network));
70
-
71
- objectId = objectId || (await getSchemaId(projectPath, network));
72
-
73
- let metadata;
74
- if (metadataFilePath) {
75
- metadata = await loadMetadataFromFile(metadataFilePath);
76
- } else {
77
- metadata = await loadMetadata(network, packageId);
78
- }
79
- if (!metadata) {
80
- throw new DubheCliError(
81
- `Metadata file not found. Please provide a metadata file path or set the packageId.`
82
- );
83
- }
84
-
85
- if (!dubheConfig.schemas[schema]) {
86
- throw new DubheCliError(
87
- `Schema "${schema}" not found in dubhe config. Available schemas: ${Object.keys(
88
- dubheConfig.schemas
89
- ).join(', ')}`
90
- );
91
- }
92
-
93
- const storageType = dubheConfig.schemas[schema];
94
-
95
- const processedParams = params || [];
96
- if (!validateParams(storageType, processedParams)) {
97
- throw new Error(
98
- `Invalid params count for ${storageType}. ` +
99
- `Expected: ${getExpectedParamsCount(storageType)}, ` +
100
- `Got: ${processedParams.length}`
101
- );
102
- }
103
-
104
- const dubhe = new Dubhe({
105
- secretKey: privateKeyFormat,
106
- networkType: network,
107
- packageId,
108
- metadata,
109
- });
110
- const result = await dubhe.parseState({
111
- schema,
112
- objectId,
113
- storageType,
114
- params: processedParams,
115
- });
116
-
117
- console.log(result);
59
+ );
60
+ }
61
+ const privateKeyFormat = validatePrivateKey(privateKey);
62
+ if (privateKeyFormat === false) {
63
+ throw new DubheCliError(`Please check your privateKey.`);
64
+ }
65
+
66
+ const path = process.cwd();
67
+ const projectPath = `${path}/contracts/${dubheConfig.name}`;
68
+
69
+ packageId = packageId || (await getOldPackageId(projectPath, network));
70
+
71
+ objectId = objectId || (await getSchemaId(projectPath, network));
72
+
73
+ let metadata;
74
+ if (metadataFilePath) {
75
+ metadata = await loadMetadataFromFile(metadataFilePath);
76
+ } else {
77
+ metadata = await loadMetadata(network, packageId);
78
+ }
79
+ if (!metadata) {
80
+ throw new DubheCliError(
81
+ `Metadata file not found. Please provide a metadata file path or set the packageId.`
82
+ );
83
+ }
84
+
85
+ if (!dubheConfig.schemas[schema]) {
86
+ throw new DubheCliError(
87
+ `Schema "${schema}" not found in dubhe config. Available schemas: ${Object.keys(
88
+ dubheConfig.schemas
89
+ ).join(', ')}`
90
+ );
91
+ }
92
+
93
+ const storageType = dubheConfig.schemas[schema];
94
+
95
+ const processedParams = params || [];
96
+ if (!validateParams(storageType, processedParams)) {
97
+ throw new Error(
98
+ `Invalid params count for ${storageType}. ` +
99
+ `Expected: ${getExpectedParamsCount(storageType)}, ` +
100
+ `Got: ${processedParams.length}`
101
+ );
102
+ }
103
+
104
+ const dubhe = new Dubhe({
105
+ secretKey: privateKeyFormat,
106
+ networkType: network,
107
+ packageId,
108
+ metadata
109
+ });
110
+ const result = await dubhe.parseState({
111
+ schema,
112
+ objectId,
113
+ storageType,
114
+ params: processedParams
115
+ });
116
+
117
+ console.log(result);
118
118
  }
119
119
 
120
120
  /**
@@ -125,31 +125,31 @@ in your contracts directory to use the default sui private key.`
125
125
  * @returns Constructed metadata object
126
126
  */
127
127
  export async function loadMetadataFromFile(metadataFilePath: string) {
128
- // Verify file extension is .json
129
- if (path.extname(metadataFilePath) !== '.json') {
130
- throw new Error('Metadata file must be in JSON format');
131
- }
132
-
133
- try {
134
- // Read JSON file content
135
- const rawData = fs.readFileSync(metadataFilePath, 'utf8');
136
- const jsonData = JSON.parse(rawData);
137
-
138
- // Validate JSON structure
139
- if (!jsonData || typeof jsonData !== 'object') {
140
- throw new Error('Invalid JSON format');
141
- }
142
-
143
- // Construct metadata structure
144
- const metadata = {
145
- ...jsonData,
146
- };
147
-
148
- return metadata;
149
- } catch (error) {
150
- if (error instanceof Error) {
151
- throw new Error(`Failed to read metadata file: ${error.message}`);
152
- }
153
- throw error;
154
- }
128
+ // Verify file extension is .json
129
+ if (path.extname(metadataFilePath) !== '.json') {
130
+ throw new Error('Metadata file must be in JSON format');
131
+ }
132
+
133
+ try {
134
+ // Read JSON file content
135
+ const rawData = fs.readFileSync(metadataFilePath, 'utf8');
136
+ const jsonData = JSON.parse(rawData);
137
+
138
+ // Validate JSON structure
139
+ if (!jsonData || typeof jsonData !== 'object') {
140
+ throw new Error('Invalid JSON format');
141
+ }
142
+
143
+ // Construct metadata structure
144
+ const metadata = {
145
+ ...jsonData
146
+ };
147
+
148
+ return metadata;
149
+ } catch (error) {
150
+ if (error instanceof Error) {
151
+ throw new Error(`Failed to read metadata file: ${error.message}`);
152
+ }
153
+ throw error;
154
+ }
155
155
  }
@@ -5,128 +5,116 @@ import { delay, DubheCliError, validatePrivateKey } from '../utils';
5
5
  import { Dubhe } from '@0xobelisk/sui-client';
6
6
 
7
7
  function isSuiStartRunning(): boolean {
8
- try {
9
- const cmd =
10
- process.platform === 'win32'
11
- ? `tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH`
12
- : 'pgrep -f "sui start"';
8
+ try {
9
+ const cmd =
10
+ process.platform === 'win32'
11
+ ? `tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH`
12
+ : 'pgrep -f "sui start"';
13
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) {
19
- return false;
20
- }
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) {
19
+ return false;
20
+ }
21
21
  }
22
22
 
23
23
  async function printAccounts() {
24
- // These private keys are used for testing purposes only, do not use them in production.
25
- const privateKeys = [
26
- 'suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v',
27
- 'suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s',
28
- 'suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc',
29
- 'suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c',
30
- 'suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57',
31
- 'suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c',
32
- ];
33
- console.log('📝Accounts');
34
- console.log('==========');
35
- privateKeys.forEach((privateKey, index) => {
36
- const dubhe = new Dubhe({ secretKey: privateKey });
37
- const keypair = dubhe.getSigner();
38
- spawn(
39
- 'curl',
40
- [
41
- '--location',
42
- '--request',
43
- 'POST',
44
- 'http://127.0.0.1:9123/gas',
45
- '--header',
46
- 'Content-Type: application/json',
47
- '--data-raw',
48
- `{"FixedAmountRequest": {"recipient": "${keypair.toSuiAddress()}"}}`,
49
- ],
50
- {
51
- env: { ...process.env },
52
- stdio: 'ignore',
53
- detached: true,
54
- }
55
- );
56
- console.log(
57
- ` ┌─ Account #${index}: ${keypair.toSuiAddress()}(1000 SUI)`
58
- );
59
- console.log(` └─ Private Key: ${privateKey}`);
60
- });
61
- console.log('==========');
62
- console.log(
63
- chalk.yellow(
64
- 'ℹ️ WARNING: These accounts, and their private keys, are publicly known.'
65
- )
66
- );
67
- console.log(
68
- chalk.yellow(
69
- 'Any funds sent to them on Mainnet or any other live network WILL BE LOST.'
70
- )
71
- );
24
+ // These private keys are used for testing purposes only, do not use them in production.
25
+ const privateKeys = [
26
+ 'suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v',
27
+ 'suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s',
28
+ 'suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc',
29
+ 'suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c',
30
+ 'suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57',
31
+ 'suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c'
32
+ ];
33
+ console.log('📝Accounts');
34
+ console.log('==========');
35
+ privateKeys.forEach((privateKey, index) => {
36
+ const dubhe = new Dubhe({ secretKey: privateKey });
37
+ const keypair = dubhe.getSigner();
38
+ spawn(
39
+ 'curl',
40
+ [
41
+ '--location',
42
+ '--request',
43
+ 'POST',
44
+ 'http://127.0.0.1:9123/gas',
45
+ '--header',
46
+ 'Content-Type: application/json',
47
+ '--data-raw',
48
+ `{"FixedAmountRequest": {"recipient": "${keypair.toSuiAddress()}"}}`
49
+ ],
50
+ {
51
+ env: { ...process.env },
52
+ stdio: 'ignore',
53
+ detached: true
54
+ }
55
+ );
56
+ console.log(` ┌─ Account #${index}: ${keypair.toSuiAddress()}(1000 SUI)`);
57
+ console.log(` └─ Private Key: ${privateKey}`);
58
+ });
59
+ console.log('==========');
60
+ console.log(
61
+ chalk.yellow('ℹ️ WARNING: These accounts, and their private keys, are publicly known.')
62
+ );
63
+ console.log(
64
+ chalk.yellow('Any funds sent to them on Mainnet or any other live network WILL BE LOST.')
65
+ );
72
66
  }
73
67
  export async function startLocalNode() {
74
- if (isSuiStartRunning()) {
75
- console.log(chalk.yellow('\n⚠️ Warning: Local Node Already Running'));
76
- console.log(chalk.yellow(' ├─ Cannot start a new instance'));
77
- console.log(
78
- chalk.yellow(' └─ Please stop the existing process first')
79
- );
80
- return;
81
- }
68
+ if (isSuiStartRunning()) {
69
+ console.log(chalk.yellow('\n⚠️ Warning: Local Node Already Running'));
70
+ console.log(chalk.yellow(' ├─ Cannot start a new instance'));
71
+ console.log(chalk.yellow(' └─ Please stop the existing process first'));
72
+ return;
73
+ }
82
74
 
83
- printDubhe();
84
- console.log('🚀 Starting Local Node...');
85
- try {
86
- const suiProcess = spawn(
87
- 'sui',
88
- ['start', '--with-faucet', '--force-regenesis'],
89
- {
90
- env: { ...process.env, RUST_LOG: 'off,sui_node=info' },
91
- stdio: 'ignore',
92
- detached: true,
93
- }
94
- );
75
+ printDubhe();
76
+ console.log('🚀 Starting Local Node...');
77
+ try {
78
+ const suiProcess = spawn('sui', ['start', '--with-faucet', '--force-regenesis'], {
79
+ env: { ...process.env, RUST_LOG: 'off,sui_node=info' },
80
+ stdio: 'ignore',
81
+ detached: true
82
+ });
95
83
 
96
- suiProcess.on('error', error => {
97
- console.error(chalk.red('\n❌ Failed to Start Local Node'));
98
- console.error(chalk.red(` └─ Error: ${error.message}`));
99
- });
100
- await delay(5000);
101
- console.log(' ├─ Faucet: Enabled');
102
- console.log(' └─ Force Regenesis: Yes');
103
- console.log(' └─ HTTP server: http://127.0.0.1:9000/');
104
- console.log(' └─ Faucet server: http://127.0.0.1:9123/');
84
+ suiProcess.on('error', (error) => {
85
+ console.error(chalk.red('\n❌ Failed to Start Local Node'));
86
+ console.error(chalk.red(` └─ Error: ${error.message}`));
87
+ });
88
+ await delay(5000);
89
+ console.log(' ├─ Faucet: Enabled');
90
+ console.log(' └─ Force Regenesis: Yes');
91
+ console.log(' └─ HTTP server: http://127.0.0.1:9000/');
92
+ console.log(' └─ Faucet server: http://127.0.0.1:9123/');
105
93
 
106
- await printAccounts();
94
+ await printAccounts();
107
95
 
108
- await delay(2000);
96
+ await delay(2000);
109
97
 
110
- const privateKeyFormat = validatePrivateKey(
111
- 'suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c'
112
- );
113
- if (privateKeyFormat === false) {
114
- throw new DubheCliError(`Please check your privateKey.`);
115
- }
98
+ const privateKeyFormat = validatePrivateKey(
99
+ 'suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c'
100
+ );
101
+ if (privateKeyFormat === false) {
102
+ throw new DubheCliError(`Please check your privateKey.`);
103
+ }
116
104
 
117
- console.log(chalk.green('🎉 Local environment is ready!'));
105
+ console.log(chalk.green('🎉 Local environment is ready!'));
118
106
 
119
- process.on('SIGINT', () => {
120
- console.log(chalk.yellow('\n🔔 Stopping Local Node...'));
121
- if (suiProcess) {
122
- suiProcess.kill();
123
- console.log(chalk.green('✅ Local Node Stopped'));
124
- }
125
- process.exit();
126
- });
127
- } catch (error: any) {
128
- console.error(chalk.red('\n❌ Failed to Start Local Node'));
129
- console.error(chalk.red(` └─ Error: ${error.message}`));
130
- process.exit(1);
131
- }
107
+ process.on('SIGINT', () => {
108
+ console.log(chalk.yellow('\n🔔 Stopping Local Node...'));
109
+ if (suiProcess) {
110
+ suiProcess.kill();
111
+ console.log(chalk.green('✅ Local Node Stopped'));
112
+ }
113
+ process.exit();
114
+ });
115
+ } catch (error: any) {
116
+ console.error(chalk.red('\n❌ Failed to Start Local Node'));
117
+ console.error(chalk.red(` └─ Error: ${error.message}`));
118
+ process.exit(1);
119
+ }
132
120
  }
@@ -5,66 +5,54 @@ import { DeploymentJsonType } from './utils';
5
5
  import { DubheConfig } from '@0xobelisk/sui-common';
6
6
 
7
7
  async function getDeploymentJson(
8
- projectPath: string,
9
- network: string
8
+ projectPath: string,
9
+ network: string
10
10
  ): Promise<DeploymentJsonType> {
11
- try {
12
- const data = await fsAsync.readFile(
13
- `${projectPath}/.history/sui_${network}/latest.json`,
14
- 'utf8'
15
- );
16
- return JSON.parse(data) as DeploymentJsonType;
17
- } catch (error) {
18
- throw new Error(
19
- `read .history/sui_${network}/latest.json failed. ${error}`
20
- );
21
- }
11
+ try {
12
+ const data = await fsAsync.readFile(
13
+ `${projectPath}/.history/sui_${network}/latest.json`,
14
+ 'utf8'
15
+ );
16
+ return JSON.parse(data) as DeploymentJsonType;
17
+ } catch (error) {
18
+ throw new Error(`read .history/sui_${network}/latest.json failed. ${error}`);
19
+ }
22
20
  }
23
21
 
24
- function storeConfig(
25
- network: string,
26
- packageId: string,
27
- schemaId: string,
28
- outputPath: string
29
- ) {
30
- let code = `type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
22
+ function storeConfig(network: string, packageId: string, schemaId: string, outputPath: string) {
23
+ let code = `type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
31
24
 
32
25
  export const NETWORK: NetworkType = '${network}';
33
26
  export const PACKAGE_ID = '${packageId}'
34
27
  export const SCHEMA_ID = '${schemaId}'
35
- `
28
+ `;
36
29
 
37
- // if (outputPath) {
38
- writeOutput(code, outputPath, 'storeConfig');
39
- // writeOutput(code, `${path}/src/chain/config.ts`, 'storeConfig');
40
- // }
30
+ // if (outputPath) {
31
+ writeOutput(code, outputPath, 'storeConfig');
32
+ // writeOutput(code, `${path}/src/chain/config.ts`, 'storeConfig');
33
+ // }
41
34
  }
42
35
 
43
36
  async function writeOutput(
44
- output: string,
45
- fullOutputPath: string,
46
- logPrefix?: string
37
+ output: string,
38
+ fullOutputPath: string,
39
+ logPrefix?: string
47
40
  ): Promise<void> {
48
- mkdirSync(dirname(fullOutputPath), { recursive: true });
41
+ mkdirSync(dirname(fullOutputPath), { recursive: true });
49
42
 
50
- writeFileSync(fullOutputPath, output);
51
- if (logPrefix !== undefined) {
52
- console.log(`${logPrefix}: ${fullOutputPath}`);
53
- }
43
+ writeFileSync(fullOutputPath, output);
44
+ if (logPrefix !== undefined) {
45
+ console.log(`${logPrefix}: ${fullOutputPath}`);
46
+ }
54
47
  }
55
48
 
56
49
  export async function storeConfigHandler(
57
- dubheConfig: DubheConfig,
58
- network: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
59
- outputPath: string
50
+ dubheConfig: DubheConfig,
51
+ network: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
52
+ outputPath: string
60
53
  ) {
61
- const path = process.cwd();
62
- const contractPath = `${path}/contracts/${dubheConfig.name}`;
63
- const deployment = await getDeploymentJson(contractPath, network);
64
- storeConfig(
65
- deployment.network,
66
- deployment.packageId,
67
- deployment.schemaId,
68
- outputPath
69
- );
54
+ const path = process.cwd();
55
+ const contractPath = `${path}/contracts/${dubheConfig.name}`;
56
+ const deployment = await getDeploymentJson(contractPath, network);
57
+ storeConfig(deployment.network, deployment.packageId, deployment.schemaId, outputPath);
70
58
  }