@0xobelisk/sui-cli 1.2.0-pre.11 → 1.2.0-pre.112
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.
- package/README.md +3 -3
- package/dist/dubhe.js +126 -49
- package/dist/dubhe.js.map +1 -1
- package/package.json +31 -19
- package/src/commands/build.ts +47 -16
- package/src/commands/call.ts +83 -83
- package/src/commands/checkBalance.ts +12 -5
- package/src/commands/configStore.ts +12 -4
- package/src/commands/convertJson.ts +70 -0
- package/src/commands/doctor.ts +1515 -0
- package/src/commands/faucet.ts +11 -7
- package/src/commands/generateKey.ts +3 -2
- package/src/commands/index.ts +16 -7
- package/src/commands/info.ts +55 -0
- package/src/commands/loadMetadata.ts +57 -0
- package/src/commands/localnode.ts +22 -6
- package/src/commands/publish.ts +21 -7
- package/src/commands/query.ts +101 -101
- package/src/commands/schemagen.ts +15 -4
- package/src/commands/shell.ts +198 -0
- package/src/commands/switchEnv.ts +26 -0
- package/src/commands/test.ts +54 -11
- package/src/commands/upgrade.ts +11 -4
- package/src/commands/wait.ts +333 -22
- package/src/commands/watch.ts +2 -1
- package/src/dubhe.ts +12 -4
- package/src/utils/axios-downloader.ts +116 -0
- package/src/utils/callHandler.ts +118 -118
- package/src/utils/constants.ts +5 -0
- package/src/utils/generateAccount.ts +1 -1
- package/src/utils/index.ts +4 -3
- package/src/utils/metadataHandler.ts +16 -0
- package/src/utils/publishHandler.ts +327 -293
- package/src/utils/queryStorage.ts +141 -141
- package/src/utils/startNode.ts +115 -16
- package/src/utils/storeConfig.ts +6 -12
- package/src/utils/upgradeHandler.ts +139 -86
- package/src/utils/utils.ts +712 -55
package/src/utils/utils.ts
CHANGED
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
import * as fsAsync from 'fs/promises';
|
|
2
2
|
import { mkdirSync, writeFileSync } from 'fs';
|
|
3
|
-
import { dirname } from 'path';
|
|
3
|
+
import { dirname, join as pathJoin } from 'path';
|
|
4
4
|
import { SUI_PRIVATE_KEY_PREFIX } from '@mysten/sui/cryptography';
|
|
5
5
|
import { FsIibError } from './errors';
|
|
6
6
|
import * as fs from 'fs';
|
|
7
7
|
import chalk from 'chalk';
|
|
8
8
|
import { spawn } from 'child_process';
|
|
9
|
-
import { Dubhe, NetworkType, SuiMoveNormalizedModules } from '@0xobelisk/sui-client';
|
|
9
|
+
import { Dubhe, NetworkType, SuiMoveNormalizedModules, loadMetadata } from '@0xobelisk/sui-client';
|
|
10
10
|
import { DubheCliError } from './errors';
|
|
11
|
-
import
|
|
11
|
+
import { Component, MoveType, DubheConfig } from '@0xobelisk/sui-common';
|
|
12
|
+
import { TESTNET_DUBHE_HUB_OBJECT_ID, TESTNET_ORIGINAL_DUBHE_PACKAGE_ID } from './constants';
|
|
12
13
|
|
|
13
14
|
export type DeploymentJsonType = {
|
|
14
15
|
projectName: string;
|
|
15
16
|
network: 'mainnet' | 'testnet' | 'devnet' | 'localnet';
|
|
17
|
+
startCheckpoint: string;
|
|
16
18
|
packageId: string;
|
|
17
|
-
|
|
19
|
+
dappHub: string;
|
|
18
20
|
upgradeCap: string;
|
|
19
21
|
version: number;
|
|
20
|
-
|
|
22
|
+
resources: Record<string, Component | MoveType>;
|
|
23
|
+
enums?: Record<string, string[]>;
|
|
21
24
|
};
|
|
22
25
|
|
|
23
26
|
export function validatePrivateKey(privateKey: string): false | string {
|
|
@@ -76,43 +79,60 @@ export async function getDeploymentJson(
|
|
|
76
79
|
}
|
|
77
80
|
}
|
|
78
81
|
|
|
79
|
-
export async function
|
|
82
|
+
export async function getDeploymentDappHub(projectPath: string, network: string): Promise<string> {
|
|
80
83
|
try {
|
|
81
84
|
const data = await fsAsync.readFile(
|
|
82
85
|
`${projectPath}/.history/sui_${network}/latest.json`,
|
|
83
86
|
'utf8'
|
|
84
87
|
);
|
|
85
88
|
const deployment = JSON.parse(data) as DeploymentJsonType;
|
|
86
|
-
return deployment.
|
|
87
|
-
} catch (
|
|
89
|
+
return deployment.dappHub;
|
|
90
|
+
} catch (_error) {
|
|
88
91
|
return '';
|
|
89
92
|
}
|
|
90
93
|
}
|
|
91
94
|
|
|
92
|
-
export async function
|
|
95
|
+
export async function getDubheDappHub(network: string) {
|
|
93
96
|
const path = process.cwd();
|
|
94
|
-
const contractPath = `${path}/
|
|
97
|
+
const contractPath = `${path}/src/dubhe`;
|
|
95
98
|
|
|
96
99
|
switch (network) {
|
|
97
100
|
case 'mainnet':
|
|
98
|
-
return
|
|
101
|
+
return TESTNET_DUBHE_HUB_OBJECT_ID;
|
|
99
102
|
case 'testnet':
|
|
100
|
-
return
|
|
103
|
+
return TESTNET_DUBHE_HUB_OBJECT_ID;
|
|
101
104
|
case 'devnet':
|
|
102
|
-
return
|
|
105
|
+
return TESTNET_DUBHE_HUB_OBJECT_ID;
|
|
103
106
|
case 'localnet':
|
|
104
|
-
return await
|
|
107
|
+
return await getDeploymentDappHub(contractPath, 'localnet');
|
|
105
108
|
default:
|
|
106
109
|
throw new Error(`Invalid network: ${network}`);
|
|
107
110
|
}
|
|
108
111
|
}
|
|
109
112
|
|
|
110
|
-
export async function
|
|
113
|
+
export async function getOriginalDubhePackageId(network: string) {
|
|
114
|
+
const path = process.cwd();
|
|
115
|
+
const contractPath = `${path}/src/dubhe`;
|
|
116
|
+
|
|
117
|
+
switch (network) {
|
|
118
|
+
case 'mainnet':
|
|
119
|
+
return TESTNET_ORIGINAL_DUBHE_PACKAGE_ID;
|
|
120
|
+
case 'testnet':
|
|
121
|
+
return TESTNET_ORIGINAL_DUBHE_PACKAGE_ID;
|
|
122
|
+
case 'devnet':
|
|
123
|
+
return TESTNET_ORIGINAL_DUBHE_PACKAGE_ID;
|
|
124
|
+
case 'localnet':
|
|
125
|
+
return await getOldPackageId(contractPath, network);
|
|
126
|
+
default:
|
|
127
|
+
throw new Error(`Invalid network: ${network}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export async function getOnchainResources(
|
|
111
131
|
projectPath: string,
|
|
112
132
|
network: string
|
|
113
|
-
): Promise<Record<string,
|
|
133
|
+
): Promise<Record<string, Component | MoveType>> {
|
|
114
134
|
const deployment = await getDeploymentJson(projectPath, network);
|
|
115
|
-
return deployment.
|
|
135
|
+
return deployment.resources;
|
|
116
136
|
}
|
|
117
137
|
|
|
118
138
|
export async function getVersion(projectPath: string, network: string): Promise<number> {
|
|
@@ -133,9 +153,9 @@ export async function getOldPackageId(projectPath: string, network: string): Pro
|
|
|
133
153
|
return deployment.packageId;
|
|
134
154
|
}
|
|
135
155
|
|
|
136
|
-
export async function
|
|
156
|
+
export async function getDappHub(projectPath: string, network: string): Promise<string> {
|
|
137
157
|
const deployment = await getDeploymentJson(projectPath, network);
|
|
138
|
-
return deployment.
|
|
158
|
+
return deployment.dappHub;
|
|
139
159
|
}
|
|
140
160
|
|
|
141
161
|
export async function getUpgradeCap(projectPath: string, network: string): Promise<string> {
|
|
@@ -143,34 +163,71 @@ export async function getUpgradeCap(projectPath: string, network: string): Promi
|
|
|
143
163
|
return deployment.upgradeCap;
|
|
144
164
|
}
|
|
145
165
|
|
|
146
|
-
export function
|
|
166
|
+
export async function getStartCheckpoint(projectPath: string, network: string): Promise<string> {
|
|
167
|
+
const deployment = await getDeploymentJson(projectPath, network);
|
|
168
|
+
return deployment.startCheckpoint;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function saveContractData(
|
|
147
172
|
projectName: string,
|
|
148
173
|
network: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
|
|
174
|
+
startCheckpoint: string,
|
|
149
175
|
packageId: string,
|
|
150
|
-
|
|
176
|
+
dappHub: string,
|
|
151
177
|
upgradeCap: string,
|
|
152
178
|
version: number,
|
|
153
|
-
|
|
179
|
+
resources: Record<string, Component | MoveType>,
|
|
180
|
+
enums?: Record<string, string[]>
|
|
154
181
|
) {
|
|
155
182
|
const DeploymentData: DeploymentJsonType = {
|
|
156
183
|
projectName,
|
|
157
184
|
network,
|
|
185
|
+
startCheckpoint,
|
|
158
186
|
packageId,
|
|
159
|
-
|
|
160
|
-
schemas,
|
|
187
|
+
dappHub,
|
|
161
188
|
upgradeCap,
|
|
162
|
-
version
|
|
189
|
+
version,
|
|
190
|
+
resources,
|
|
191
|
+
enums
|
|
163
192
|
};
|
|
164
193
|
|
|
165
194
|
const path = process.cwd();
|
|
166
195
|
const storeDeploymentData = JSON.stringify(DeploymentData, null, 2);
|
|
167
|
-
writeOutput(
|
|
196
|
+
await writeOutput(
|
|
168
197
|
storeDeploymentData,
|
|
169
|
-
`${path}/
|
|
198
|
+
`${path}/src/${projectName}/.history/sui_${network}/latest.json`,
|
|
170
199
|
'Update deploy log'
|
|
171
200
|
);
|
|
172
201
|
}
|
|
173
202
|
|
|
203
|
+
export async function saveMetadata(
|
|
204
|
+
projectName: string,
|
|
205
|
+
network: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
|
|
206
|
+
packageId: string
|
|
207
|
+
) {
|
|
208
|
+
const path = process.cwd();
|
|
209
|
+
|
|
210
|
+
// Save metadata files
|
|
211
|
+
try {
|
|
212
|
+
const metadata = await loadMetadata(network, packageId);
|
|
213
|
+
if (metadata) {
|
|
214
|
+
const metadataJson = JSON.stringify(metadata, null, 2);
|
|
215
|
+
|
|
216
|
+
// Save packageId-specific metadata file
|
|
217
|
+
await writeOutput(
|
|
218
|
+
metadataJson,
|
|
219
|
+
`${path}/src/${projectName}/.history/sui_${network}/${packageId}.json`,
|
|
220
|
+
'Save package metadata'
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
// Save latest metadata.json
|
|
224
|
+
await writeOutput(metadataJson, `${path}/metadata.json`, 'Save latest metadata');
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
console.warn(chalk.yellow(`Warning: Failed to save metadata: ${error}`));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
174
231
|
export async function writeOutput(
|
|
175
232
|
output: string,
|
|
176
233
|
fullOutputPath: string,
|
|
@@ -184,55 +241,486 @@ export async function writeOutput(
|
|
|
184
241
|
}
|
|
185
242
|
}
|
|
186
243
|
|
|
187
|
-
function getDubheDependency(network: 'mainnet' | 'testnet' | 'devnet' | 'localnet'): string {
|
|
188
|
-
switch (network) {
|
|
189
|
-
case 'localnet':
|
|
190
|
-
return 'Dubhe = { local = "../dubhe" }';
|
|
191
|
-
case 'testnet':
|
|
192
|
-
return `Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/contracts/dubhe", rev = "${packageJson.version}" }`;
|
|
193
|
-
case 'mainnet':
|
|
194
|
-
return `Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/contracts/dubhe", rev = "${packageJson.version}" }`;
|
|
195
|
-
default:
|
|
196
|
-
throw new Error(`Unsupported network: ${network}`);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
244
|
export async function updateDubheDependency(
|
|
201
245
|
filePath: string,
|
|
202
246
|
network: 'mainnet' | 'testnet' | 'devnet' | 'localnet'
|
|
203
247
|
) {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
248
|
+
// With the new --build-env mechanism, we keep Dubhe as local dependency for all networks.
|
|
249
|
+
// The Published.toml in ../dubhe resolves the correct on-chain address per environment.
|
|
250
|
+
// This function is kept for backward compatibility but is a no-op for non-localnet.
|
|
251
|
+
if (network === 'localnet') {
|
|
252
|
+
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
253
|
+
const localDependency = 'Dubhe = { local = "../dubhe" }';
|
|
254
|
+
if (!fileContent.includes(localDependency)) {
|
|
255
|
+
const updatedContent = fileContent.replace(/Dubhe = \{[^}]*\}/, localDependency);
|
|
256
|
+
fs.writeFileSync(filePath, updatedContent, 'utf-8');
|
|
257
|
+
console.log(`Ensured local Dubhe dependency in ${filePath} for localnet.`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Published.toml management for the new Sui CLI (v1.44+) publishing mechanism.
|
|
263
|
+
// Published.toml tracks on-chain package addresses per environment.
|
|
264
|
+
// It SHOULD be committed to source control.
|
|
265
|
+
|
|
266
|
+
interface PublishedEntry {
|
|
267
|
+
chainId: string;
|
|
268
|
+
publishedAt: string;
|
|
269
|
+
originalId: string;
|
|
270
|
+
version: number;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function readPublishedToml(packagePath: string): Record<string, PublishedEntry> {
|
|
274
|
+
const filePath = pathJoin(packagePath, 'Published.toml');
|
|
275
|
+
if (!fs.existsSync(filePath)) {
|
|
276
|
+
return {};
|
|
277
|
+
}
|
|
278
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
279
|
+
const result: Record<string, PublishedEntry> = {};
|
|
280
|
+
|
|
281
|
+
const sectionRegex = /\[published\.(\w+)\]([\s\S]*?)(?=\[published\.|$)/g;
|
|
282
|
+
let match;
|
|
283
|
+
while ((match = sectionRegex.exec(content)) !== null) {
|
|
284
|
+
const env = match[1];
|
|
285
|
+
const body = match[2];
|
|
286
|
+
const getValue = (key: string) => {
|
|
287
|
+
const m = body.match(new RegExp(`${key}\\s*=\\s*"([^"]*)"`));
|
|
288
|
+
return m ? m[1] : '';
|
|
289
|
+
};
|
|
290
|
+
const versionMatch = body.match(/version\s*=\s*(\d+)/);
|
|
291
|
+
result[env] = {
|
|
292
|
+
chainId: getValue('chain-id'),
|
|
293
|
+
publishedAt: getValue('published-at'),
|
|
294
|
+
originalId: getValue('original-id'),
|
|
295
|
+
version: versionMatch ? parseInt(versionMatch[1], 10) : 1
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function writePublishedToml(
|
|
302
|
+
packagePath: string,
|
|
303
|
+
entries: Record<string, PublishedEntry>
|
|
304
|
+
): void {
|
|
305
|
+
const filePath = pathJoin(packagePath, 'Published.toml');
|
|
306
|
+
let content =
|
|
307
|
+
'# Generated by Move\n' +
|
|
308
|
+
'# This file contains metadata about published versions of this package in different environments\n' +
|
|
309
|
+
'# This file SHOULD be committed to source control\n';
|
|
310
|
+
|
|
311
|
+
for (const [env, entry] of Object.entries(entries)) {
|
|
312
|
+
content += `\n[published.${env}]\n`;
|
|
313
|
+
content += `chain-id = "${entry.chainId}"\n`;
|
|
314
|
+
content += `published-at = "${entry.publishedAt}"\n`;
|
|
315
|
+
content += `original-id = "${entry.originalId}"\n`;
|
|
316
|
+
content += `version = ${entry.version}\n`;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
fs.writeFileSync(filePath, content, 'utf-8');
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export function updatePublishedToml(
|
|
323
|
+
packagePath: string,
|
|
324
|
+
network: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
|
|
325
|
+
chainId: string,
|
|
326
|
+
packageId: string,
|
|
327
|
+
originalId?: string,
|
|
328
|
+
version?: number
|
|
329
|
+
): void {
|
|
330
|
+
const entries = readPublishedToml(packagePath);
|
|
331
|
+
const existing = entries[network];
|
|
332
|
+
|
|
333
|
+
entries[network] = {
|
|
334
|
+
chainId,
|
|
335
|
+
publishedAt: packageId,
|
|
336
|
+
originalId: originalId ?? existing?.originalId ?? packageId,
|
|
337
|
+
version: version ?? (existing ? existing.version + 1 : 1)
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
writePublishedToml(packagePath, entries);
|
|
341
|
+
console.log(`Updated Published.toml in ${packagePath} for ${network}.`);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function getPublishedTomlEntry(
|
|
345
|
+
packagePath: string,
|
|
346
|
+
network: string
|
|
347
|
+
): PublishedEntry | undefined {
|
|
348
|
+
const entries = readPublishedToml(packagePath);
|
|
349
|
+
return entries[network];
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export function clearPublishedTomlEntry(
|
|
353
|
+
packagePath: string,
|
|
354
|
+
network: string
|
|
355
|
+
): PublishedEntry | undefined {
|
|
356
|
+
const entries = readPublishedToml(packagePath);
|
|
357
|
+
const existing = entries[network];
|
|
358
|
+
if (!existing) return undefined;
|
|
359
|
+
|
|
360
|
+
entries[network] = {
|
|
361
|
+
...existing,
|
|
362
|
+
publishedAt: '0x0000000000000000000000000000000000000000000000000000000000000000',
|
|
363
|
+
originalId: '0x0000000000000000000000000000000000000000000000000000000000000000'
|
|
364
|
+
};
|
|
365
|
+
writePublishedToml(packagePath, entries);
|
|
366
|
+
return existing;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function restorePublishedTomlEntry(
|
|
370
|
+
packagePath: string,
|
|
371
|
+
network: string,
|
|
372
|
+
entry: PublishedEntry
|
|
373
|
+
): void {
|
|
374
|
+
const entries = readPublishedToml(packagePath);
|
|
375
|
+
entries[network] = entry;
|
|
376
|
+
writePublishedToml(packagePath, entries);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
380
|
+
// Ephemeral publication file (Pub.<env>.toml)
|
|
381
|
+
//
|
|
382
|
+
// Per the Sui package management docs (v1.63+), localnet / devnet deployments
|
|
383
|
+
// should use ephemeral publication files rather than the shared Published.toml.
|
|
384
|
+
// The ephemeral file holds the localnet addresses so that subsequent builds
|
|
385
|
+
// (e.g. for upgrades) can resolve local dependencies correctly.
|
|
386
|
+
//
|
|
387
|
+
// Reference: https://docs.sui.io/guides/developer/packages/move-package-management
|
|
388
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
389
|
+
|
|
390
|
+
export interface EphemeralPubEntry {
|
|
391
|
+
/** Absolute path to the package source directory */
|
|
392
|
+
source: string;
|
|
393
|
+
/** Current on-chain address of the package */
|
|
394
|
+
publishedAt: string;
|
|
395
|
+
/** Address of the first published version (same as publishedAt for v1) */
|
|
396
|
+
originalId: string;
|
|
397
|
+
/** Object ID of the upgrade capability */
|
|
398
|
+
upgradeCap: string;
|
|
399
|
+
/** Package version (required by Sui CLI parser) */
|
|
400
|
+
version?: number;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Return the canonical path for the ephemeral publication file.
|
|
405
|
+
* For localnet this is <contractsDir>/Pub.localnet.toml.
|
|
406
|
+
*/
|
|
407
|
+
export function getEphemeralPubFilePath(contractsDir: string, network: string): string {
|
|
408
|
+
return pathJoin(contractsDir, `Pub.${network}.toml`);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Update (or create) an entry in the ephemeral publication file.
|
|
413
|
+
* Preserves existing entries for other packages.
|
|
414
|
+
*/
|
|
415
|
+
export function updateEphemeralPubFile(
|
|
416
|
+
pubfilePath: string,
|
|
417
|
+
chainId: string,
|
|
418
|
+
buildEnv: string,
|
|
419
|
+
entry: EphemeralPubEntry
|
|
420
|
+
): void {
|
|
421
|
+
const existing: EphemeralPubEntry[] = [];
|
|
422
|
+
// Always use the provided buildEnv and chainId parameters.
|
|
423
|
+
// The chainId passed in comes from the live network and is authoritative.
|
|
424
|
+
const currentBuildEnv = buildEnv;
|
|
425
|
+
const currentChainId = chainId;
|
|
426
|
+
|
|
427
|
+
if (fs.existsSync(pubfilePath)) {
|
|
428
|
+
const content = fs.readFileSync(pubfilePath, 'utf-8');
|
|
429
|
+
|
|
430
|
+
// Check if the file was written for a different chain (e.g. previous localnet run).
|
|
431
|
+
// If chain-id changed, discard all existing entries — they belong to a dead chain.
|
|
432
|
+
const chainIdMatch = content.match(/^chain-id\s*=\s*"([^"]*)"/m);
|
|
433
|
+
const fileChainId = chainIdMatch ? chainIdMatch[1] : '';
|
|
434
|
+
const chainChanged = fileChainId !== '' && fileChainId !== chainId;
|
|
435
|
+
|
|
436
|
+
if (!chainChanged) {
|
|
437
|
+
// Same chain: parse existing [[published]] blocks and preserve them.
|
|
438
|
+
// source field is an inline table: source = { local = "..." }
|
|
439
|
+
const blockRegex = /\[\[published\]\]([\s\S]*?)(?=\[\[published\]\]|$)/g;
|
|
440
|
+
let blockMatch;
|
|
441
|
+
while ((blockMatch = blockRegex.exec(content)) !== null) {
|
|
442
|
+
const block = blockMatch[1];
|
|
443
|
+
const get = (key: string) => {
|
|
444
|
+
const m = block.match(new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, 'm'));
|
|
445
|
+
return m ? m[1] : '';
|
|
446
|
+
};
|
|
447
|
+
// source = { local = "/path/to/package" }
|
|
448
|
+
const srcMatch = block.match(/^source\s*=\s*\{\s*local\s*=\s*"([^"]*)"\s*\}/m);
|
|
449
|
+
const src = srcMatch ? srcMatch[1] : '';
|
|
450
|
+
if (src) {
|
|
451
|
+
existing.push({
|
|
452
|
+
source: src,
|
|
453
|
+
publishedAt: get('published-at'),
|
|
454
|
+
originalId: get('original-id'),
|
|
455
|
+
upgradeCap: get('upgrade-cap')
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
} else {
|
|
460
|
+
console.log(` Pub file chain-id changed (${fileChainId} → ${chainId}), resetting entries.`);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Update override or add the entry
|
|
465
|
+
const idx = existing.findIndex((e) => e.source === entry.source);
|
|
466
|
+
if (idx >= 0) {
|
|
467
|
+
existing[idx] = entry;
|
|
468
|
+
} else {
|
|
469
|
+
existing.push(entry);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Write the file
|
|
473
|
+
let content =
|
|
474
|
+
'# generated by dubhe cli\n' +
|
|
475
|
+
'# this file contains metadata from ephemeral publications\n' +
|
|
476
|
+
'# this file should NOT be committed to source control\n\n';
|
|
477
|
+
content += `build-env = "${currentBuildEnv}"\n`;
|
|
478
|
+
content += `chain-id = "${currentChainId}"\n`;
|
|
479
|
+
|
|
480
|
+
for (const e of existing) {
|
|
481
|
+
content += '\n[[published]]\n';
|
|
482
|
+
// source must be a LocalDepInfo struct (not a plain string)
|
|
483
|
+
content += `source = { local = "${e.source}" }\n`;
|
|
484
|
+
content += `published-at = "${e.publishedAt}"\n`;
|
|
485
|
+
content += `original-id = "${e.originalId}"\n`;
|
|
486
|
+
content += `upgrade-cap = "${e.upgradeCap}"\n`;
|
|
487
|
+
// version is required by Sui CLI parser (even though docs omit it)
|
|
488
|
+
content += `version = 1\n`;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
fs.writeFileSync(pubfilePath, content, 'utf-8');
|
|
492
|
+
console.log(
|
|
493
|
+
` Updated ${pathJoin(pubfilePath.split('/').slice(-1)[0])} for ${
|
|
494
|
+
entry.source.split('/').slice(-1)[0]
|
|
495
|
+
}.`
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
async function checkRpcAvailability(rpcUrl: string): Promise<boolean> {
|
|
500
|
+
try {
|
|
501
|
+
const response = await fetch(rpcUrl, {
|
|
502
|
+
method: 'POST',
|
|
503
|
+
headers: {
|
|
504
|
+
'Content-Type': 'application/json'
|
|
505
|
+
},
|
|
506
|
+
body: JSON.stringify({
|
|
507
|
+
jsonrpc: '2.0',
|
|
508
|
+
id: 1,
|
|
509
|
+
method: 'sui_getLatestCheckpointSequenceNumber',
|
|
510
|
+
params: []
|
|
511
|
+
})
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
if (!response.ok) {
|
|
515
|
+
return false;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const data = await response.json();
|
|
519
|
+
return !data.error;
|
|
520
|
+
} catch (_error) {
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
209
523
|
}
|
|
524
|
+
|
|
525
|
+
export async function addEnv(
|
|
526
|
+
network: 'mainnet' | 'testnet' | 'devnet' | 'localnet'
|
|
527
|
+
): Promise<void> {
|
|
528
|
+
const rpcMap = {
|
|
529
|
+
localnet: 'http://127.0.0.1:9000',
|
|
530
|
+
devnet: 'https://fullnode.devnet.sui.io:443/',
|
|
531
|
+
testnet: 'https://fullnode.testnet.sui.io:443/',
|
|
532
|
+
mainnet: 'https://fullnode.mainnet.sui.io:443/'
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const rpcUrl = rpcMap[network];
|
|
536
|
+
|
|
537
|
+
// Check RPC availability first
|
|
538
|
+
const isRpcAvailable = await checkRpcAvailability(rpcUrl);
|
|
539
|
+
if (!isRpcAvailable) {
|
|
540
|
+
throw new Error(
|
|
541
|
+
`RPC endpoint ${rpcUrl} is not available. Please check your network connection or try again later.`
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return new Promise<void>((resolve, reject) => {
|
|
546
|
+
let errorOutput = '';
|
|
547
|
+
let stdoutOutput = '';
|
|
548
|
+
|
|
549
|
+
const suiProcess = spawn(
|
|
550
|
+
'sui',
|
|
551
|
+
['client', 'new-env', '--alias', network, '--rpc', rpcMap[network]],
|
|
552
|
+
{
|
|
553
|
+
env: { ...process.env },
|
|
554
|
+
stdio: 'pipe'
|
|
555
|
+
}
|
|
556
|
+
);
|
|
557
|
+
|
|
558
|
+
// Capture standard output
|
|
559
|
+
suiProcess.stdout.on('data', (data) => {
|
|
560
|
+
stdoutOutput += data.toString();
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
// Capture error output
|
|
564
|
+
suiProcess.stderr.on('data', (data) => {
|
|
565
|
+
errorOutput += data.toString();
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
// Handle process errors (e.g., command not found)
|
|
569
|
+
suiProcess.on('error', (error) => {
|
|
570
|
+
console.error(chalk.red(`\n❌ Failed to execute sui command: ${error.message}`));
|
|
571
|
+
reject(new Error(`Failed to execute sui command: ${error.message}`));
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
// Handle process exit
|
|
575
|
+
suiProcess.on('exit', (code, signal) => {
|
|
576
|
+
// Check if "already exists" message is present
|
|
577
|
+
if (errorOutput.includes('already exists') || stdoutOutput.includes('already exists')) {
|
|
578
|
+
console.log(chalk.yellow(`Environment ${network} already exists, proceeding...`));
|
|
579
|
+
resolve();
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
if (code === 0) {
|
|
584
|
+
console.log(chalk.green(`Successfully added environment ${network}`));
|
|
585
|
+
resolve();
|
|
586
|
+
} else {
|
|
587
|
+
let finalError: string;
|
|
588
|
+
if (code === null) {
|
|
589
|
+
// Process was killed by a signal
|
|
590
|
+
finalError =
|
|
591
|
+
errorOutput ||
|
|
592
|
+
stdoutOutput ||
|
|
593
|
+
`Process was terminated by signal ${signal || 'unknown'}`;
|
|
594
|
+
} else {
|
|
595
|
+
finalError = errorOutput || stdoutOutput || `Process exited with code ${code}`;
|
|
596
|
+
}
|
|
597
|
+
console.error(chalk.red(`\n❌ Failed to add environment ${network}`));
|
|
598
|
+
console.error(chalk.red(` └─ ${finalError.trim()}`));
|
|
599
|
+
reject(new Error(finalError));
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
export type NetworkAlias = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
606
|
+
|
|
607
|
+
export interface Endpoint {
|
|
608
|
+
alias: NetworkAlias;
|
|
609
|
+
rpc: string;
|
|
610
|
+
ws: string | null;
|
|
611
|
+
basic_auth: { username: string; password: string } | null;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// mainly is a tuple of [endpoint list, current active alias]
|
|
615
|
+
export type ConfigTuple = [Endpoint[], NetworkAlias];
|
|
616
|
+
|
|
617
|
+
export async function envsJSON(): Promise<ConfigTuple> {
|
|
618
|
+
try {
|
|
619
|
+
return new Promise<ConfigTuple>((resolve, reject) => {
|
|
620
|
+
let errorOutput = '';
|
|
621
|
+
let stdoutOutput = '';
|
|
622
|
+
|
|
623
|
+
const suiProcess = spawn('sui', ['client', 'envs', '--json'], {
|
|
624
|
+
env: { ...process.env },
|
|
625
|
+
stdio: 'pipe'
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
suiProcess.stdout.on('data', (data) => {
|
|
629
|
+
stdoutOutput += data.toString();
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
suiProcess.stderr.on('data', (data) => {
|
|
633
|
+
errorOutput += data.toString();
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
suiProcess.on('error', (error) => {
|
|
637
|
+
console.error(chalk.red(`\n❌ Failed to execute sui command: ${error.message}`));
|
|
638
|
+
reject(new Error(`Failed to execute sui command: ${error.message}`));
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
suiProcess.on('exit', (code, signal) => {
|
|
642
|
+
if (code === 0) {
|
|
643
|
+
resolve(JSON.parse(stdoutOutput) as ConfigTuple);
|
|
644
|
+
} else {
|
|
645
|
+
let finalError: string;
|
|
646
|
+
if (code === null) {
|
|
647
|
+
// Process was killed by a signal
|
|
648
|
+
finalError =
|
|
649
|
+
errorOutput ||
|
|
650
|
+
stdoutOutput ||
|
|
651
|
+
`Process was terminated by signal ${signal || 'unknown'}`;
|
|
652
|
+
} else {
|
|
653
|
+
finalError = errorOutput || stdoutOutput || `Process exited with code ${code}`;
|
|
654
|
+
}
|
|
655
|
+
console.error(chalk.red(`\n❌ Failed to get envs`));
|
|
656
|
+
console.error(chalk.red(` └─ ${finalError.trim()}`));
|
|
657
|
+
reject(new Error(finalError));
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
});
|
|
661
|
+
} catch (error) {
|
|
662
|
+
// Re-throw the error for the caller to handle
|
|
663
|
+
throw error;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
export async function getDefaultNetwork(): Promise<NetworkAlias> {
|
|
668
|
+
const [_, currentAlias] = await envsJSON();
|
|
669
|
+
return currentAlias as NetworkAlias;
|
|
670
|
+
}
|
|
671
|
+
|
|
210
672
|
export async function switchEnv(network: 'mainnet' | 'testnet' | 'devnet' | 'localnet') {
|
|
211
673
|
try {
|
|
674
|
+
// First, try to add the environment
|
|
675
|
+
await addEnv(network);
|
|
676
|
+
|
|
677
|
+
// Then switch to the specified environment
|
|
212
678
|
return new Promise<void>((resolve, reject) => {
|
|
679
|
+
let errorOutput = '';
|
|
680
|
+
let stdoutOutput = '';
|
|
681
|
+
|
|
213
682
|
const suiProcess = spawn('sui', ['client', 'switch', '--env', network], {
|
|
214
683
|
env: { ...process.env },
|
|
215
684
|
stdio: 'pipe'
|
|
216
685
|
});
|
|
217
686
|
|
|
687
|
+
suiProcess.stdout.on('data', (data) => {
|
|
688
|
+
stdoutOutput += data.toString();
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
suiProcess.stderr.on('data', (data) => {
|
|
692
|
+
errorOutput += data.toString();
|
|
693
|
+
});
|
|
694
|
+
|
|
218
695
|
suiProcess.on('error', (error) => {
|
|
219
|
-
console.error(chalk.red(
|
|
220
|
-
|
|
221
|
-
reject(error); // Reject promise on error
|
|
696
|
+
console.error(chalk.red(`\n❌ Failed to execute sui command: ${error.message}`));
|
|
697
|
+
reject(new Error(`Failed to execute sui command: ${error.message}`));
|
|
222
698
|
});
|
|
223
699
|
|
|
224
|
-
suiProcess.on('exit', (code) => {
|
|
225
|
-
if (code
|
|
226
|
-
console.
|
|
227
|
-
|
|
700
|
+
suiProcess.on('exit', (code, signal) => {
|
|
701
|
+
if (code === 0) {
|
|
702
|
+
console.log(chalk.green(`Successfully switched to environment ${network}`));
|
|
703
|
+
resolve();
|
|
228
704
|
} else {
|
|
229
|
-
|
|
705
|
+
let finalError: string;
|
|
706
|
+
if (code === null) {
|
|
707
|
+
// Process was killed by a signal
|
|
708
|
+
finalError =
|
|
709
|
+
errorOutput ||
|
|
710
|
+
stdoutOutput ||
|
|
711
|
+
`Process was terminated by signal ${signal || 'unknown'}`;
|
|
712
|
+
} else {
|
|
713
|
+
finalError = errorOutput || stdoutOutput || `Process exited with code ${code}`;
|
|
714
|
+
}
|
|
715
|
+
console.error(chalk.red(`\n❌ Failed to switch to environment ${network}`));
|
|
716
|
+
console.error(chalk.red(` └─ ${finalError.trim()}`));
|
|
717
|
+
reject(new Error(finalError));
|
|
230
718
|
}
|
|
231
719
|
});
|
|
232
720
|
});
|
|
233
721
|
} catch (error) {
|
|
234
|
-
|
|
235
|
-
|
|
722
|
+
// Re-throw the error for the caller to handle
|
|
723
|
+
throw error;
|
|
236
724
|
}
|
|
237
725
|
}
|
|
238
726
|
|
|
@@ -272,3 +760,172 @@ export function initializeDubhe({
|
|
|
272
760
|
metadata
|
|
273
761
|
});
|
|
274
762
|
}
|
|
763
|
+
|
|
764
|
+
export function generateConfigJson(config: DubheConfig): string {
|
|
765
|
+
const resources = Object.entries(config.resources).map(([name, resource]) => {
|
|
766
|
+
// Simple type shorthand (e.g., counter1: 'u32') – entity-keyed by account (entity_id: String).
|
|
767
|
+
if (typeof resource === 'string') {
|
|
768
|
+
return {
|
|
769
|
+
[name]: {
|
|
770
|
+
fields: [{ entity_id: 'String' }, { value: resource }],
|
|
771
|
+
keys: ['entity_id'],
|
|
772
|
+
offchain: false
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// Empty resource object – only the implicit entity key.
|
|
778
|
+
if (Object.keys(resource as object).length === 0) {
|
|
779
|
+
return {
|
|
780
|
+
[name]: {
|
|
781
|
+
fields: [{ entity_id: 'String' }],
|
|
782
|
+
keys: ['entity_id'],
|
|
783
|
+
offchain: false
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
const fields = (resource as any).fields || {};
|
|
789
|
+
const keys = (resource as any).keys || [];
|
|
790
|
+
const offchain = (resource as any).offchain ?? false;
|
|
791
|
+
|
|
792
|
+
// Full Component format with no explicit keys: auto-inject 'entity_id: String'.
|
|
793
|
+
if (keys.length === 0) {
|
|
794
|
+
const fieldEntries = Object.entries(fields);
|
|
795
|
+
const orderedFields: [string, unknown][] = [['entity_id', 'String'], ...fieldEntries];
|
|
796
|
+
return {
|
|
797
|
+
[name]: {
|
|
798
|
+
fields: orderedFields.map(([fieldName, fieldType]) => ({
|
|
799
|
+
[fieldName]: fieldType
|
|
800
|
+
})),
|
|
801
|
+
keys: ['entity_id'],
|
|
802
|
+
offchain: offchain
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// Full Component format with explicit custom keys: inject 'entity_id: String' as the first
|
|
808
|
+
// field and first key so that key_tuple[0] (the BCS-encoded account injected by the indexer)
|
|
809
|
+
// maps correctly, followed by the user-defined keys.
|
|
810
|
+
const fieldEntries = Object.entries(fields);
|
|
811
|
+
const orderedFields: [string, unknown][] = [['entity_id', 'String'], ...fieldEntries];
|
|
812
|
+
return {
|
|
813
|
+
[name]: {
|
|
814
|
+
fields: orderedFields.map(([fieldName, fieldType]) => ({
|
|
815
|
+
[fieldName]: fieldType
|
|
816
|
+
})),
|
|
817
|
+
keys: ['entity_id', ...keys],
|
|
818
|
+
offchain: offchain
|
|
819
|
+
}
|
|
820
|
+
};
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
// Auto-append Dubhe framework fee state resource (entity-keyed by account string).
|
|
824
|
+
if (!resources.some((resource) => 'dapp_fee_state' in resource)) {
|
|
825
|
+
resources.push({
|
|
826
|
+
dapp_fee_state: {
|
|
827
|
+
fields: [
|
|
828
|
+
{ entity_id: 'String' },
|
|
829
|
+
{ base_fee: 'u256' },
|
|
830
|
+
{ byte_fee: 'u256' },
|
|
831
|
+
{ free_credit: 'u256' },
|
|
832
|
+
{ total_bytes_size: 'u256' },
|
|
833
|
+
{ total_recharged: 'u256' },
|
|
834
|
+
{ total_paid: 'u256' }
|
|
835
|
+
],
|
|
836
|
+
keys: ['entity_id'],
|
|
837
|
+
offchain: false
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// handle enums
|
|
843
|
+
const enums = Object.entries(config.enums || {}).map(([name, enumFields]) => {
|
|
844
|
+
// Sort enum values by first letter
|
|
845
|
+
const sortedFields = enumFields.sort((a, b) => a.localeCompare(b)).map((value) => value);
|
|
846
|
+
|
|
847
|
+
return {
|
|
848
|
+
[name]: sortedFields
|
|
849
|
+
};
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
return JSON.stringify(
|
|
853
|
+
{
|
|
854
|
+
resources,
|
|
855
|
+
enums
|
|
856
|
+
},
|
|
857
|
+
null,
|
|
858
|
+
2
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* Updates the dubhe address and published-at in Move.toml file
|
|
864
|
+
* @param path - Directory path containing Move.toml file
|
|
865
|
+
* @param packageAddress - New dubhe package address to set
|
|
866
|
+
*
|
|
867
|
+
* Logic:
|
|
868
|
+
* - If packageAddress is "0x0": only set dubhe = "0x0", remove published-at line
|
|
869
|
+
* - Otherwise: set both dubhe and published-at to packageAddress
|
|
870
|
+
*/
|
|
871
|
+
export function updateMoveTomlAddress(path: string, packageAddress: string) {
|
|
872
|
+
const moveTomlPath = `${path}/Move.toml`;
|
|
873
|
+
const moveTomlContent = fs.readFileSync(moveTomlPath, 'utf-8');
|
|
874
|
+
|
|
875
|
+
let updatedContent = moveTomlContent;
|
|
876
|
+
|
|
877
|
+
if (packageAddress === '0x0') {
|
|
878
|
+
// Case 1: Address is "0x0" - set dubhe to "0x0" and remove published-at line
|
|
879
|
+
updatedContent = updatedContent.replace(/dubhe\s*=\s*"[^"]*"/, `dubhe = "0x0"`);
|
|
880
|
+
|
|
881
|
+
// Remove published-at line (including the line break)
|
|
882
|
+
updatedContent = updatedContent.replace(/published-at\s*=\s*"[^"]*"\r?\n?/, '');
|
|
883
|
+
} else {
|
|
884
|
+
// Case 2: Address is not "0x0" - set both dubhe and published-at
|
|
885
|
+
updatedContent = updatedContent.replace(/dubhe\s*=\s*"[^"]*"/, `dubhe = "${packageAddress}"`);
|
|
886
|
+
|
|
887
|
+
// Check if published-at already exists
|
|
888
|
+
if (/published-at\s*=\s*"[^"]*"/.test(updatedContent)) {
|
|
889
|
+
// Replace existing published-at
|
|
890
|
+
updatedContent = updatedContent.replace(
|
|
891
|
+
/published-at\s*=\s*"[^"]*"/,
|
|
892
|
+
`published-at = "${packageAddress}"`
|
|
893
|
+
);
|
|
894
|
+
} else {
|
|
895
|
+
// Add published-at after [package] line if it doesn't exist
|
|
896
|
+
updatedContent = updatedContent.replace(
|
|
897
|
+
/(\[package\][^\n]*\n)/,
|
|
898
|
+
`$1published-at = "${packageAddress}"\n`
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
fs.writeFileSync(moveTomlPath, updatedContent, 'utf-8');
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
export function updateGenesisUpgradeFunction(path: string, tables: string[]) {
|
|
907
|
+
const genesisPath = `${path}/sources/codegen/genesis.move`;
|
|
908
|
+
const genesisContent = fs.readFileSync(genesisPath, 'utf-8');
|
|
909
|
+
|
|
910
|
+
// Match the first pair of // ========================================== lines (with any content, including empty, between them)
|
|
911
|
+
const separatorRegex =
|
|
912
|
+
/(\/\/ ==========================================)[\s\S]*?(\/\/ ==========================================)/;
|
|
913
|
+
const match = genesisContent.match(separatorRegex);
|
|
914
|
+
|
|
915
|
+
if (!match) {
|
|
916
|
+
throw new Error('Could not find separator comments in genesis.move');
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// Generate new table registration code
|
|
920
|
+
const registerTablesCode = tables
|
|
921
|
+
.map((table) => ` ${table}::register_table(dapp_hub, ctx);`)
|
|
922
|
+
.join('\n');
|
|
923
|
+
|
|
924
|
+
// Build new content, preserve separators, replace middle content
|
|
925
|
+
const newContent = `${match[1]}\n${registerTablesCode}\n${match[2]}`;
|
|
926
|
+
|
|
927
|
+
// Replace matched content
|
|
928
|
+
const updatedContent = genesisContent.replace(separatorRegex, newContent);
|
|
929
|
+
|
|
930
|
+
fs.writeFileSync(genesisPath, updatedContent, 'utf-8');
|
|
931
|
+
}
|