@0xobelisk/sui-cli 1.2.0-pre.12 → 1.2.0-pre.121
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 +7 -7
- package/dist/dubhe.js +152 -51
- package/dist/dubhe.js.map +1 -1
- package/package.json +31 -19
- package/src/commands/build.ts +61 -18
- package/src/commands/call.ts +83 -83
- package/src/commands/checkBalance.ts +27 -12
- package/src/commands/convertJson.ts +85 -0
- package/src/commands/doctor.ts +1515 -0
- package/src/commands/faucet.ts +20 -10
- package/src/commands/generate.ts +61 -0
- package/src/commands/generateKey.ts +3 -2
- package/src/commands/index.ts +20 -11
- package/src/commands/info.ts +61 -0
- package/src/commands/loadMetadata.ts +68 -0
- package/src/commands/localnode.ts +22 -6
- package/src/commands/publish.ts +55 -7
- package/src/commands/query.ts +101 -101
- package/src/commands/shell.ts +208 -0
- package/src/commands/{configStore.ts → storeConfig.ts} +13 -5
- package/src/commands/switchEnv.ts +33 -0
- package/src/commands/test.ts +143 -31
- package/src/commands/upgrade.ts +46 -6
- package/src/commands/wait.ts +333 -22
- package/src/commands/watch.ts +9 -8
- package/src/dubhe.ts +12 -4
- package/src/utils/axios-downloader.ts +116 -0
- package/src/utils/callHandler.ts +118 -118
- package/src/utils/checkBalance.ts +6 -2
- package/src/utils/constants.ts +9 -0
- package/src/utils/generateAccount.ts +1 -1
- package/src/utils/index.ts +4 -3
- package/src/utils/metadataHandler.ts +17 -0
- package/src/utils/publishHandler.ts +408 -289
- package/src/utils/queryStorage.ts +141 -141
- package/src/utils/startNode.ts +115 -16
- package/src/utils/storeConfig.ts +50 -10
- package/src/utils/upgradeHandler.ts +218 -85
- package/src/utils/utils.ts +1041 -63
- package/src/commands/schemagen.ts +0 -40
package/dist/dubhe.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Es from"yargs";import{hideBin as Ts}from"yargs/helpers";import hn from"chalk";import{execSync as be,spawn as _t}from"child_process";import D from"chalk";import bn from"chalk";function ge(){console.log(bn.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,61 +10,162 @@ Welcome to Dubhe
|
|
|
10
10
|
\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
|
|
11
11
|
\\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
|
|
12
12
|
|
|
13
|
-
`))}import{Transaction as
|
|
13
|
+
`))}import{Transaction as Ue}from"@0xobelisk/sui-client";import{execSync as Nn}from"child_process";import U from"chalk";import*as qe from"fs/promises";import{mkdirSync as $n,writeFileSync as Cn}from"fs";import{dirname as _n,join as se}from"path";import*as ct from"readline";import{SUI_PRIVATE_KEY_PREFIX as Pn}from"@mysten/sui/cryptography";import Ce from"chalk";import{ZodError as wn}from"zod";import{fromZodError as vn,ValidationError as xn}from"zod-validation-error";var ze=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},V=class extends Error{name="DubheCliError"},Fe=class extends Error{name="UpgradeError"};function B(e){if(e instanceof xn)console.log(Ce.redBright(e.message));else if(e instanceof wn){let t=vn(e,{prefixSeparator:`
|
|
14
14
|
- `,issueSeparator:`
|
|
15
|
-
- `});console.log(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
- `});console.log(Ce.redBright(t.message))}else e instanceof ze?(console.log(Ce.red(e.message)),console.log(""),console.log(Ce.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof V?console.log(Ce.red(e)):console.log(e)}import*as N from"fs";import R from"chalk";import{spawn as Ge}from"child_process";import{Dubhe as Sn,loadMetadata as kn,getDefaultConfig as Je}from"@0xobelisk/sui-client";function Ye(e){if(e.startsWith(Pn))return e.length===70?e:!1;if(e.startsWith("0x")){let t=e.slice(2);return t.length===64?t:!1}else return e.length===64?e:!1}async function J(e,t){try{let n=await qe.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(n)}catch(n){throw new Error(`read .history/sui_${t}/latest.json failed. ${n}`)}}async function En(e,t){try{let n=await qe.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(n).dappHubId}catch{return""}}async function fe(e){let n=`${process.cwd()}/src/dubhe`;if(e==="localnet")return await En(n,"localnet");let o=Je(e);if(!o.dappHubId)throw new Error(`DappHub object ID is not configured for network "${e}". Update MAINNET_DUBHE_HUB_OBJECT_ID / TESTNET_DUBHE_HUB_OBJECT_ID in @0xobelisk/sui-client.`);return o.dappHubId}async function re(e){let n=`${process.cwd()}/src/dubhe`;if(e==="localnet")return await _e(n,e);let o=Je(e);if(!o.frameworkPackageId)throw new Error(`Framework package ID is not configured for network "${e}". Update MAINNET_DUBHE_FRAMEWORK_PACKAGE_ID / TESTNET_DUBHE_FRAMEWORK_PACKAGE_ID in @0xobelisk/sui-client.`);return o.frameworkPackageId}async function dt(e,t){return(await J(e,t)).resources}async function ut(e,t){return(await J(e,t)).version}async function _e(e,t){return(await J(e,t)).packageId}async function pt(e,t){return(await J(e,t)).dappStorageId??""}async function Xe(e,t){return(await J(e,t)).upgradeCap}async function gt(e,t){return(await J(e,t)).startCheckpoint}async function Pe(e,t,n,o,s,r,i,c,a,d,u,g){let f={projectName:e,network:t,startCheckpoint:n,packageId:o,originalPackageId:s,dappHubId:r,frameworkPackageId:u,dappStorageId:g,upgradeCap:i,version:c,resources:a,enums:d},y=process.cwd(),w=JSON.stringify(f,null,2);await Ke(w,`${y}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function Se(e,t,n,o){let s=process.cwd();try{let r=await kn(t,n,o);if(r){let i=JSON.stringify(r,null,2);await Ke(i,`${s}/src/${e}/.history/sui_${t}/${n}.json`,"Save package metadata"),await Ke(i,`${s}/metadata.json`,"Save latest metadata")}}catch(r){console.warn(R.yellow(`Warning: Failed to save metadata: ${r}`))}}async function Ke(e,t,n){$n(_n(t),{recursive:!0}),Cn(t,e),n!==void 0&&console.log(`${n}: ${t}`)}function ie(e){let t=se(e,"Published.toml");if(!N.existsSync(t))return{};let n=N.readFileSync(t,"utf-8"),o={},s=/\[published\.(\w+)\]([\s\S]*?)(?=\[published\.|$)/g,r;for(;(r=s.exec(n))!==null;){let i=r[1],c=r[2],a=u=>{let g=c.match(new RegExp(`${u}\\s*=\\s*"([^"]*)"`));return g?g[1]:""},d=c.match(/version\s*=\s*(\d+)/);o[i]={chainId:a("chain-id"),publishedAt:a("published-at"),originalId:a("original-id"),version:d?parseInt(d[1],10):1}}return o}function Qe(e,t){let n=se(e,"Published.toml"),o=`# Generated by Move
|
|
16
|
+
# This file contains metadata about published versions of this package in different environments
|
|
17
|
+
# This file SHOULD be committed to source control
|
|
18
|
+
`;for(let[s,r]of Object.entries(t))o+=`
|
|
19
|
+
[published.${s}]
|
|
20
|
+
`,o+=`chain-id = "${r.chainId}"
|
|
21
|
+
`,o+=`published-at = "${r.publishedAt}"
|
|
22
|
+
`,o+=`original-id = "${r.originalId}"
|
|
23
|
+
`,o+=`version = ${r.version}
|
|
24
|
+
`;N.writeFileSync(n,o,"utf-8")}function me(e,t,n,o,s,r){let i=ie(e),c=i[t];i[t]={chainId:n,publishedAt:o,originalId:s??c?.originalId??o,version:r??(c?c.version+1:1)},Qe(e,i),console.log(`Updated Published.toml in ${e} for ${t}.`)}function Ze(e,t){return ie(e)[t]}function Re(e,t,n){if(t==="localnet"||t==="devnet")return;let o=Je(t).frameworkPackageId;if(!o)return;let s=se(e,"src","dubhe");!N.existsSync(s)||Ze(s,t)?.publishedAt===o||(me(s,t,n,o,o,1),console.log(R.gray(` \u251C\u2500 Auto-synced dubhe framework address for ${t}: ${o.slice(0,10)}...`)))}function Me(e,t){let n=ie(e),o=n[t];if(o)return n[t]={...o,publishedAt:"0x0000000000000000000000000000000000000000000000000000000000000000",originalId:"0x0000000000000000000000000000000000000000000000000000000000000000"},Qe(e,n),o}function ke(e,t,n){let o=ie(e);o[t]=n,Qe(e,o)}function he(e,t){return se(e,`Pub.${t}.toml`)}function Oe(e,t,n,o){let s=[],r=n,i=t;if(N.existsSync(e)){let d=N.readFileSync(e,"utf-8"),u=d.match(/^chain-id\s*=\s*"([^"]*)"/m),g=u?u[1]:"";if(g!==""&&g!==t)console.log(` Pub file chain-id changed (${g} \u2192 ${t}), resetting entries.`);else{let y=/\[\[published\]\]([\s\S]*?)(?=\[\[published\]\]|$)/g,w;for(;(w=y.exec(d))!==null;){let T=w[1],p=C=>{let S=T.match(new RegExp(`^${C}\\s*=\\s*"([^"]*)"`,"m"));return S?S[1]:""},b=T.match(/^source\s*=\s*\{\s*local\s*=\s*"([^"]*)"\s*\}/m),m=b?b[1]:"";m&&s.push({source:m,publishedAt:p("published-at"),originalId:p("original-id"),upgradeCap:p("upgrade-cap")})}}}let c=s.findIndex(d=>d.source===o.source);c>=0?s[c]=o:s.push(o);let a=`# generated by dubhe cli
|
|
25
|
+
# this file contains metadata from ephemeral publications
|
|
26
|
+
# this file should NOT be committed to source control
|
|
27
|
+
|
|
28
|
+
`;a+=`build-env = "${r}"
|
|
29
|
+
`,a+=`chain-id = "${i}"
|
|
30
|
+
`;for(let d of s)a+=`
|
|
31
|
+
[[published]]
|
|
32
|
+
`,a+=`source = { local = "${d.source}" }
|
|
33
|
+
`,a+=`published-at = "${d.publishedAt}"
|
|
34
|
+
`,a+=`original-id = "${d.originalId}"
|
|
35
|
+
`,a+=`upgrade-cap = "${d.upgradeCap}"
|
|
36
|
+
`,a+=`version = 1
|
|
37
|
+
`;N.writeFileSync(e,a,"utf-8"),console.log(` Updated ${se(e.split("/").slice(-1)[0])} for ${o.source.split("/").slice(-1)[0]}.`)}async function Tn(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"sui_getLatestCheckpointSequenceNumber",params:[]})});return t.ok?!(await t.json()).error:!1}catch{return!1}}async function In(e,t){let o=t||{localnet:"http://127.0.0.1:9000",devnet:"https://fullnode.devnet.sui.io:443/",testnet:"https://fullnode.testnet.sui.io:443/",mainnet:"https://fullnode.mainnet.sui.io:443/"}[e];if(!await Tn(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((r,i)=>{let c="",a="",d=Ge("sui",["client","new-env","--alias",e,"--rpc",o],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",u=>{a+=u.toString()}),d.stderr.on("data",u=>{c+=u.toString()}),d.on("error",u=>{console.error(R.red(`
|
|
38
|
+
\u274C Failed to execute sui command: ${u.message}`)),i(new Error(`Failed to execute sui command: ${u.message}`))}),d.on("exit",(u,g)=>{if(c.includes("already exists")||a.includes("already exists")){console.log(R.yellow(`Environment ${e} already exists, proceeding...`)),r();return}if(u===0)console.log(R.green(`Successfully added environment ${e}`)),r();else{let f;u===null?f=c||a||`Process was terminated by signal ${g||"unknown"}`:f=c||a||`Process exited with code ${u}`,console.error(R.red(`
|
|
39
|
+
\u274C Failed to add environment ${e}`)),console.error(R.red(` \u2514\u2500 ${f.trim()}`)),i(new Error(f))}})})}async function Dn(){try{return new Promise((e,t)=>{let n="",o="",s=Ge("sui",["client","envs","--json"],{env:{...process.env},stdio:"pipe"});s.stdout.on("data",r=>{o+=r.toString()}),s.stderr.on("data",r=>{n+=r.toString()}),s.on("error",r=>{console.error(R.red(`
|
|
40
|
+
\u274C Failed to execute sui command: ${r.message}`)),t(new Error(`Failed to execute sui command: ${r.message}`))}),s.on("exit",(r,i)=>{if(r===0)e(JSON.parse(o));else{let c;r===null?c=n||o||`Process was terminated by signal ${i||"unknown"}`:c=n||o||`Process exited with code ${r}`,console.error(R.red(`
|
|
41
|
+
\u274C Failed to get envs`)),console.error(R.red(` \u2514\u2500 ${c.trim()}`)),t(new Error(c))}})})}catch(e){throw e}}async function M(){let[e,t]=await Dn();return t}async function Y(e,t){try{return await In(e,t),new Promise((n,o)=>{let s="",r="",i=Ge("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});i.stdout.on("data",c=>{r+=c.toString()}),i.stderr.on("data",c=>{s+=c.toString()}),i.on("error",c=>{console.error(R.red(`
|
|
42
|
+
\u274C Failed to execute sui command: ${c.message}`)),o(new Error(`Failed to execute sui command: ${c.message}`))}),i.on("exit",(c,a)=>{if(c===0)console.log(R.green(`Successfully switched to environment ${e}`)),n();else{let d;c===null?d=s||r||`Process was terminated by signal ${a||"unknown"}`:d=s||r||`Process exited with code ${c}`,console.error(R.red(`
|
|
43
|
+
\u274C Failed to switch to environment ${e}`)),console.error(R.red(` \u2514\u2500 ${d.trim()}`)),o(new Error(d))}})})}catch(n){throw n}}var ae=e=>new Promise(t=>setTimeout(t,e));function An(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new V(`Missing private key environment variable.
|
|
19
44
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
20
45
|
or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
21
|
-
in your contracts directory to use the default sui private key.`);let t=
|
|
22
|
-
`),
|
|
46
|
+
in your contracts directory to use the default sui private key.`);let t=Ye(e);if(t===!1)throw new V("Please check your privateKey.");return t}function z({network:e,packageId:t,metadata:n,fullnodeUrls:o}){let s=An();return new Sn({networkType:e,secretKey:s,packageId:t,metadata:n,fullnodeUrls:o})}function ft(e){let t=(c={})=>Object.entries(c).map(([a,d])=>({[a]:d})),n=Object.entries(e.resources??{}).map(([c,a])=>{if(typeof a=="string")return{[c]:{fields:[{entity_id:"String"},{value:a}],keys:["entity_id"],offchain:!1}};if(Object.keys(a).length===0)return{[c]:{fields:[{entity_id:"String"}],keys:["entity_id"],offchain:!1}};let d=a.fields||{},u=a.keys||[],g=a.offchain??!1;if(u.length===0){let w=Object.entries(d),T=[["entity_id","String"],...w];return{[c]:{fields:T.map(([p,b])=>({[p]:b})),keys:["entity_id"],offchain:g}}}let f=Object.entries(d),y=[["entity_id","String"],...f];return{[c]:{fields:y.map(([w,T])=>({[w]:T})),keys:["entity_id",...u],offchain:g}}}),o=Object.entries(e.enums||{}).map(([c,a])=>{let d=a.sort((u,g)=>u.localeCompare(g)).map(u=>u);return{[c]:d}}),s=Object.entries(e.objects??{}).map(([c,a])=>({[c]:{fields:t(a.fields),accepts:a.accepts??[],acceptsFrom:a.acceptsFrom??[],adminOnly:a.adminOnly??!1}})),r=Object.entries(e.scenes??{}).map(([c,a])=>({[c]:{fields:t(a.fields),authorization:a.authorization,accepts:a.accepts??[],acceptsFrom:a.acceptsFrom??[]}})),i=Object.entries(e.permits??{}).map(([c,a])=>({[c]:a??{}}));return JSON.stringify({resources:n,objects:s,scenes:r,permits:i,enums:o},null,2)}function ye(e,t){let n=`${e}/Move.toml`,s=N.readFileSync(n,"utf-8");t==="0x0"?(s=s.replace(/dubhe\s*=\s*"[^"]*"/,'dubhe = "0x0"'),s=s.replace(/published-at\s*=\s*"[^"]*"\r?\n?/,"")):(s=s.replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`),/published-at\s*=\s*"[^"]*"/.test(s)?s=s.replace(/published-at\s*=\s*"[^"]*"/,`published-at = "${t}"`):s=s.replace(/(\[package\][^\n]*\n)/,`$1published-at = "${t}"
|
|
47
|
+
`)),N.writeFileSync(n,s,"utf-8")}function mt(e,t,n){let o=`${e}/sources/scripts/migrate.move`;if(!N.existsSync(o))throw new Error(`migrate.move not found at ${o}`);let s=N.readFileSync(o,"utf-8");if(s.includes(`migrate_to_v${n}`))return;s=s.replace(/const ON_CHAIN_VERSION:\s*u32\s*=\s*\d+\s*;/,`const ON_CHAIN_VERSION: u32 = ${n};`);let r=`
|
|
48
|
+
public entry fun migrate_to_v${n}(
|
|
49
|
+
dapp_hub: &mut dubhe::dapp_service::DappHub,
|
|
50
|
+
dapp_storage: &mut dubhe::dapp_service::DappStorage,
|
|
51
|
+
new_package_id: address,
|
|
52
|
+
ctx: &mut TxContext
|
|
53
|
+
) {
|
|
54
|
+
let new_version = ${t}::migrate::on_chain_version();
|
|
55
|
+
dubhe::dapp_system::upgrade_dapp<${t}::dapp_key::DappKey>(
|
|
56
|
+
dapp_hub, dapp_storage, new_package_id, new_version, ctx
|
|
57
|
+
);
|
|
58
|
+
${t}::genesis::migrate(dapp_hub, dapp_storage, ctx);
|
|
59
|
+
}
|
|
60
|
+
`,i=s.lastIndexOf("}");if(i===-1)throw new Error(`Could not find closing brace in ${o}`);let c=s.slice(0,i)+r+s.slice(i);N.writeFileSync(o,c,"utf-8")}function X(e){let t=se(e,"sources","systems");if(!N.existsSync(t))return[];let n=[],o=N.readdirSync(t).filter(s=>s.endsWith(".move"));for(let s of o){let r=se(t,s),i=N.readFileSync(r,"utf-8"),c=/public\s+entry\s+fun\s+(\w+)\s*\(/g,a;for(;(a=c.exec(i))!==null;){let d=a[1],u=a.index+a[0].length-1,g=0,f=u;for(let b=u;b<i.length;b++)if(i[b]==="(")g++;else if(i[b]===")"&&(g--,g===0)){f=b;break}let y=i.slice(u+1,f);if(!/DappStorage/.test(y))continue;let w=i.indexOf("{",f);if(w===-1)continue;g=0;let T=w;for(let b=w;b<i.length;b++)if(i[b]==="{")g++;else if(i[b]==="}"&&(g--,g===0)){T=b;break}let p=i.slice(w,T+1);/ensure_latest_version/.test(p)||n.push({file:s,fn:d})}}return n}function Q(e){if(e.length===0)return"";let t=[R.yellow("\u26A0\uFE0F Missing ensure_latest_version in the following entry functions:"),R.yellow(" Old-package callers can still invoke these functions after an upgrade."),""];for(let n of e)t.push(R.yellow(` \u2022 ${n.file} \u2192 ${n.fn}()`));return t.push(""),t.push(R.yellow(" Fix: add dubhe::dapp_system::ensure_latest_version(dapp_storage); at the top of each function.")),t.push(""),t.join(`
|
|
61
|
+
`)}function je(e){return new Promise(t=>{let n=ct.createInterface({input:process.stdin,output:process.stdout});n.question(R.yellow(`${e} [y/N] `),o=>{n.close(),t(o.trim().toLowerCase()==="y")})})}function ht(e,t){if(!N.existsSync(e))return;let n=JSON.parse(N.readFileSync(e,"utf-8")),o=Array.isArray(n.package_ids)?n.package_ids:[];o.includes(t)||(n.package_ids=[...o,t],N.writeFileSync(e,JSON.stringify(n,null,2)))}import*as P from"fs";import*as Z from"path";function et(e,t){if(!P.existsSync(e))return null;let n=P.readFileSync(e,"utf-8");if(n.includes("localnet"))return null;let o;return n.includes("[environments]")?o=n.replace("[environments]",`[environments]
|
|
62
|
+
localnet = "${t}"`):o=n.trimEnd()+`
|
|
63
|
+
|
|
64
|
+
[environments]
|
|
65
|
+
localnet = "${t}"
|
|
66
|
+
`,P.writeFileSync(e,o,"utf-8"),n}async function tt(e,t){if(!P.existsSync(e))return;let n=P.readFileSync(e,"utf-8"),o=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=n.replace(o,"");P.writeFileSync(e,s,"utf-8")}function yt(e,t,n,o,s){let r=Z.resolve(e),i=P.readFileSync(r,"utf-8"),c=i.split(`
|
|
67
|
+
`),a=c.findIndex(f=>f.trim()===`[env.${t}]`),d={chainId:o,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(a===-1)if(n==="publish")d.originalPublishedId=s,d.latestPublishedId=s,d.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let f=a+1;f<c.length;f++){let y=c[f].trim();if(y.startsWith("["))break;let[w,T]=y.split("=").map(p=>p.trim().replace(/"/g,""));switch(w){case"original-published-id":d.originalPublishedId=T;break;case"latest-published-id":d.latestPublishedId=T;break;case"published-version":d.publishedVersion=parseInt(T,10);break}}n==="publish"?(d.originalPublishedId=s,d.latestPublishedId=s,d.publishedVersion=1):n==="upgrade"&&(d.latestPublishedId=s,d.publishedVersion+=1)}let u=`
|
|
23
68
|
[env.${t}]
|
|
24
|
-
chain-id = "${
|
|
25
|
-
original-published-id = "${
|
|
26
|
-
latest-published-id = "${
|
|
27
|
-
published-version = "${
|
|
28
|
-
`,
|
|
29
|
-
`)+
|
|
30
|
-
|
|
31
|
-
\u{
|
|
32
|
-
\u{
|
|
33
|
-
\
|
|
34
|
-
|
|
35
|
-
\u26A1 Executing Deploy Hook...`),await O(5e3);let y=new Q,S=[];if(t.name!=="dubhe"){let u=await R(o);S.push(y.object(u))}S.push(y.object("0x6")),y.moveCall({target:`${P}::${t.name}_genesis::run`,arguments:S});let g;try{g=await e.signAndSendTxn({tx:y})}catch(u){console.error(f.red(" \u2514\u2500 Deploy hook execution failed")),console.error(u.message),process.exit(1)}g.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${g.digest}`),console.log(`
|
|
36
|
-
\u{1F4CB} Created Objects:`),g.objectChanges?.map(u=>{u.type==="created"&&u.objectType&&u.objectType.includes("schema::Schema")&&(j=u.objectId||""),u.type==="created"&&u.objectType&&u.objectType.includes("schema")&&!u.objectType.includes("dynamic_field")&&x.push(u)}),x.map(u=>{console.log(` \u251C\u2500 Type: ${u.objectType}`),console.log(` \u2514\u2500 ID: ${u.objectId}`)}),L(t.name,o,P,j,k,w,F),console.log(`
|
|
69
|
+
chain-id = "${d.chainId}"
|
|
70
|
+
original-published-id = "${d.originalPublishedId}"
|
|
71
|
+
latest-published-id = "${d.latestPublishedId}"
|
|
72
|
+
published-version = "${d.publishedVersion}"
|
|
73
|
+
`,g=a===-1?i+u:c.slice(0,a).join(`
|
|
74
|
+
`)+u;P.writeFileSync(r,g,"utf-8")}function bt(e,t,n){let o,s;try{let r;t==="localnet"?(r=" --build-env testnet",n&&(r+=` --pubfile-path ${n}`)):r=t?` -e ${t}`:"";let i=JSON.parse(Nn(`sui move build --dump-bytecode-as-base64 --no-tree-shaking${r} --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));o=i.modules,s=i.dependencies}catch(r){throw console.error(U.red(" \u2514\u2500 Build failed")),console.error(r.stdout||r.stderr),new Error(`Build failed: ${r.stdout||r.stderr||r.message}`)}return[o,s]}async function wt(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let n=e.getAddress(),o=await e.suiInteractor.currentClient.getCoins({owner:n,coinType:"0x2::sui::SUI"});if(o.data.length>0){let s=o.data.reduce((r,i)=>r+Number(i.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(U.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function Fn(e,t,n,o,s,r,i){console.log(`
|
|
75
|
+
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${o}`),console.log(` \u251C\u2500 Network: ${n}`),console.log(" \u251C\u2500 Waiting for node...");let c=await wt(e);console.log(" \u251C\u2500 Validating Environment..."),await tt(`${o}/Move.lock`,n),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),t.name!=="dubhe"&&Re(process.cwd(),n,c),console.log(`
|
|
76
|
+
\u{1F4E6} Building Contract...`);let a=n==="localnet"?he(process.cwd(),n):void 0;if(a&&P.existsSync(a)){let F=P.readFileSync(a,"utf-8").match(/^chain-id\s*=\s*"([^"]*)"/m),oe=F?F[1]:"";oe&&oe!==c&&(console.log(U.yellow(` \u251C\u2500 Stale Pub.localnet.toml (chain ${oe} \u2192 ${c}), discarding`)),P.unlinkSync(a),a=void 0)}let d=`${o}/Move.toml`,u=Z.join(Z.dirname(o),"dubhe","Move.toml"),g=null,f=null,y=`${o}/Published.toml`,w=null,T=null;if(n==="localnet"&&P.existsSync(y))w=P.readFileSync(y,"utf-8"),P.unlinkSync(y);else if(n==="testnet"||n==="mainnet"||n==="devnet"){let $=Ze(o,n);$&&r?(T={network:n,entry:$},Me(o,n)):$||(g=P.readFileSync(d,"utf-8"),ye(o,"0x0"))}let p=Z.join(Z.dirname(o),"dubhe","Published.toml"),b=null;n==="localnet"&&P.existsSync(p)&&(b=P.readFileSync(p,"utf-8"),P.unlinkSync(p)),n==="localnet"&&(g=et(d,c),f=et(u,c));let m,C;try{[m,C]=bt(o,n,a)}finally{w!==null&&P.writeFileSync(y,w,"utf-8"),T!==null&&ke(o,T.network,T.entry),b!==null&&P.writeFileSync(p,b,"utf-8"),g!==null&&P.writeFileSync(d,g,"utf-8"),f!==null&&P.writeFileSync(u,f,"utf-8")}console.log(`
|
|
77
|
+
\u{1F504} Publishing Contract...`);let S=new Ue;s&&S.setGasBudget(s);let[_]=S.publish({modules:m,dependencies:C});S.transferObjects([_],e.getAddress());let v;try{v=await e.signAndSendTxn({tx:S})}catch($){throw console.error(U.red(" \u2514\u2500 Publication failed")),console.error($.message),!r&&(n==="testnet"||n==="mainnet"||n==="devnet")&&/PublishErrorNonZeroAddress/i.test(String($?.message))&&console.error(U.yellow(' Tip: This package may already be published on this network. Use --force to clear the stored address and publish as new, or use "dubhe upgrade" to update the existing package.')),new Error(`Contract publication failed: ${$.message}`)}if(!v||v.effects?.status.status==="failure")throw new Error("Contract publication transaction failed");console.log(" \u251C\u2500 Processing publication results...");let j=1,x="",E="",A=t.resources??{},W=t.enums,Ne="",xe="",H=[];v.objectChanges.map($=>{$.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${$.packageId}`),x=$.packageId||""),$.type==="created"&&$.objectType&&$.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${$.objectId}`),Ne=$.objectId||""),$.type==="created"&&$.objectType&&$.objectType.includes("dapp_service::DappHub")&&(E=$.objectId||""),$.type==="created"&&H.push($)}),console.log(` \u2514\u2500 Transaction: ${v.digest}`),yt(`${o}/Move.lock`,n,"publish",c,x),me(o,n,c,x,x,1),console.log(`
|
|
78
|
+
\u26A1 Executing Deploy Hook...`),await ae(5e3),xe=await e.suiInteractor.currentClient.getLatestCheckpointSequenceNumber();let ne=new Ue,$e=[],pe=t.name==="dubhe"?E:await fe(n);$e.push(ne.object(pe)),t.name!=="dubhe"&&$e.push(ne.object("0x6")),ne.moveCall({target:`${x}::genesis::run`,arguments:$e});let k;try{k=await e.signAndSendTxn({tx:ne})}catch($){throw console.error(U.red(" \u2514\u2500 Deploy hook execution failed")),console.error($.message),new Error(`genesis::run failed: ${$.message}`)}if(k.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${k.digest}`);let $="";k.objectChanges.map(G=>{G.type==="created"&&G.objectType&&G.objectType.includes("dapp_service::DappStorage")&&($=G.objectId||"",console.log(` \u251C\u2500 DappStorage: ${$}`))}),console.log(`
|
|
79
|
+
\u{1F4CB} Created Objects:`),H.map(G=>{console.log(` \u251C\u2500 ID: ${G.objectId}`),console.log(` \u2514\u2500 Type: ${G.objectType}`)}),await Pe(t.name,n,xe,x,x,pe,Ne,j,A,W,n==="localnet"?await re(n):void 0,$||void 0),await Se(t.name,n,x,i);let F=JSON.parse(P.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));F.original_package_id=x,F.package_ids=[x],F.dubhe_object_id=pe,F.original_dubhe_package_id=t.name==="dubhe"?x:await re(n),F.start_checkpoint=xe;let oe=x.replace(/^0x/i,"").padStart(64,"0");F.dapp_key=`${oe}::dapp_key::DappKey`,$&&(F.dapp_storage_id=$),P.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(F,null,2)),console.log(`
|
|
37
80
|
\u2705 Contract Publication Complete
|
|
38
|
-
`)
|
|
39
|
-
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(
|
|
40
|
-
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
\
|
|
44
|
-
\
|
|
45
|
-
\
|
|
46
|
-
\
|
|
47
|
-
\
|
|
48
|
-
\u{
|
|
81
|
+
`)}else throw new Error(`genesis::run transaction failed. Digest: ${k.digest}`)}async function Rn(e){return P.existsSync(e)?!0:(console.log(U.yellow(`
|
|
82
|
+
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(U.yellow(" \u251C\u2500 Expected Path:"),e),console.log(U.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(U.yellow(" \u2502 1. Create directory: mkdir -p src/dubhe")),console.log(U.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe src/dubhe")),console.log(U.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(U.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function Mn(e,t){let n=process.cwd(),o=`${n}/src/dubhe`;if(!await Rn(o))return;console.log(`
|
|
83
|
+
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await wt(e);await tt(`${o}/Move.lock`,t),t==="localnet"&&await tt(`${o}/Move.lock`,"testnet"),await ye(o,"0x0");let r=await e.suiInteractor.currentClient.getLatestCheckpointSequenceNumber(),i=`${o}/Published.toml`,c=null;t==="localnet"&&P.existsSync(i)&&(c=P.readFileSync(i,"utf-8"),P.unlinkSync(i));let a=`${o}/Move.toml`,d=null;t==="localnet"&&(d=et(a,s));let u,g;try{[u,g]=bt(o,t)}finally{c!==null&&P.writeFileSync(i,c,"utf-8"),d!==null&&P.writeFileSync(a,d,"utf-8")}let f=new Ue,[y]=f.publish({modules:u,dependencies:g});f.transferObjects([y],e.getAddress());let w;try{w=await e.signAndSendTxn({tx:f})}catch(_){throw console.error(U.red(" \u2514\u2500 Publication failed")),console.error(_.message),new Error(`Dubhe framework publication failed: ${_.message}`)}if(!w||w.effects?.status.status==="failure")throw new Error("Dubhe framework publication transaction failed");let T=1,p="",b="",m="";w.objectChanges.map(_=>{_.type==="published"&&(p=_.packageId||""),_.type==="created"&&_.objectType&&_.objectType==="0x2::package::UpgradeCap"&&(m=_.objectId||""),_.type==="created"&&_.objectType&&_.objectType.includes("dapp_service::DappHub")&&(b=_.objectId||"")}),await ae(3e3);let C=new Ue;C.moveCall({target:`${p}::genesis::run`,arguments:[C.object(b)]});let S;try{S=await e.signAndSendTxn({tx:C})}catch(_){throw console.error(U.red(" \u2514\u2500 Deploy hook execution failed")),console.error(_.message),new Error(`Dubhe genesis::run failed: ${_.message}`)}if(S.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");if(await ye(o,p),await Pe("dubhe",t,r,p,p,b,m,T,{},{},t==="localnet"?p:void 0),yt(`${o}/Move.lock`,t,"publish",s,p),me(o,t,s,p,p,1),t==="localnet"){let _=he(n,t);Oe(_,s,"testnet",{source:o,publishedAt:p,originalId:p,upgradeCap:m})}}async function vt(e,t,n,o,s){await Y(t,s?.[0]);let r=z({network:t,fullnodeUrls:s}),c=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await Mn(r,t),await Fn(r,e,t,c,o,n,s)}import{Transaction as xt,UpgradePolicy as On}from"@0xobelisk/sui-client";import{execSync as jn}from"child_process";import K from"chalk";import*as ee from"fs";import*as $t from"path";function Le(e,t,n,o){let s=$t.resolve(e),i=ee.readFileSync(s,"utf-8").split(`
|
|
84
|
+
`),c=i.findIndex(u=>u.trim()===`[env.${t}]`);if(c===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let a=-1,d="";for(let u=c+1;u<i.length;u++){let g=i[u].trim();if(g.startsWith("["))break;if(g.startsWith(n)){a=u,d=g.split("=")[1].trim().replace(/"/g,"");break}}if(a!==-1){i[a]=`${n} = "${o}"`;let u=i.join(`
|
|
85
|
+
`);ee.writeFileSync(s,u,"utf-8")}else console.log(`${n} not found for [env.${t}].`);return d}async function Ct(e,t,n,o=!1,s){await Y(n,s?.[0]);let r=process.cwd(),i=`${r}/src/${t}`,c=z({network:n,fullnodeUrls:s}),a=Number(await ut(i,n)),d=await _e(i,n),u=await Xe(i,n),g=await gt(i,n),f=await fe(n),y=await pt(i,n),w=n==="localnet"?await re(n):void 0,T=await dt(i,n),p=[];Object.entries(e.resources??{}).forEach(([v,j])=>{T.hasOwnProperty(v)||p.push({name:v,fields:j})});let b=p.map(v=>v.name),m=b.length>0||o;m&&(o&&b.length===0&&console.log(K.yellow("--bump-version: forcing version bump with no schema changes.")),mt(i,e.name,a+1));let C=Le(`${i}/Move.lock`,n,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),S=n!=="localnet"?Me(i,n):void 0;if(t!=="dubhe"&&(n==="testnet"||n==="mainnet")){let v=await c.suiInteractor.currentClient.getChainIdentifier();Re(r,n,v)}let _=process.cwd();if(n==="localnet"&&t!=="dubhe"){let v=`${_}/src/dubhe`,x=ie(v).localnet;if(x){let E=he(_,n),A=await Xe(v,n).catch(()=>"");Oe(E,x.chainId,"testnet",{source:v,publishedAt:x.publishedAt,originalId:x.originalId,upgradeCap:A})}}try{let v,j,x,E=null;if(n==="localnet"&&t==="dubhe"){let k=`${i}/Move.toml`;E=ee.readFileSync(k,"utf-8"),ye(i,"0x0")}try{let k;n==="localnet"?t!=="dubhe"?k=`sui move build --dump-bytecode-as-base64 --no-tree-shaking --build-env testnet --pubfile-path ${he(_,n)} --path ${r}/src/${t}`:k=`sui move build --dump-bytecode-as-base64 --no-tree-shaking --build-env testnet --path ${r}/src/${t}`:k=`sui move build --dump-bytecode-as-base64 --no-tree-shaking -e ${n} --path ${r}/src/${t}`;let{modules:$,dependencies:F,digest:oe}=JSON.parse(jn(k,{encoding:"utf-8",stdio:"pipe"}));v=$,j=F,x=oe}catch(k){throw S&&ke(i,n,S),new Fe(k.stdout||k.stderr||k.message)}finally{E!==null&&ee.writeFileSync(`${i}/Move.toml`,E,"utf-8")}console.log(`
|
|
86
|
+
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",d),console.log("\u{1F4CB} UpgradeCap Object Id:",u),console.log("\u{1F4CB} OldVersion:",a);let A=new xt,W=A.moveCall({target:"0x2::package::authorize_upgrade",arguments:[A.object(u),A.pure.u8(On.COMPATIBLE),A.pure.vector("u8",x)]}),Ne=A.upgrade({modules:v,dependencies:j,package:d,ticket:W});A.moveCall({target:"0x2::package::commit_upgrade",arguments:[A.object(u),Ne]});let xe=await c.signAndSendTxn({tx:A,onSuccess:k=>{console.log(K.green(`Upgrade Transaction Digest: ${k.digest}`))},onError:k=>{console.log(K.red("Upgrade Transaction failed!")),console.error(k)}}),H="";xe.objectChanges.map(k=>{k.type==="published"&&(console.log(K.blue(`${t} new PackageId: ${k.packageId}`)),console.log(K.blue(`${t} new Version: ${a+1}`)),H=k.packageId)}),Le(`${i}/Move.lock`,n,"original-published-id",C),Le(`${i}/Move.lock`,n,"latest-published-id",H),Le(`${i}/Move.lock`,n,"published-version",a+1+"");let ne=ie(i)[n],$e=S?.chainId??ne?.chainId??"";me(i,n,$e,H,S?.originalId??ne?.originalId??C,a+1),Pe(t,n,g,H,C,f,u,a+1,e.resources??{},e.enums,w,y||void 0);let pe=`${process.cwd()}/dubhe.config.json`;if(ht(pe,H),ee.existsSync(pe)&&console.log(K.green(`\u2705 Appended ${H} to dubhe.config.json package_ids`)),m){p.length>0?(console.log(`
|
|
87
|
+
\u{1F680} Starting Migration Process...`),p.forEach(F=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(F,null,2))})):console.log(`
|
|
88
|
+
\u{1F680} Starting Migration Process (forced version bump)...`),n==="localnet"&&await new Promise(F=>setTimeout(F,5e3)),y||console.warn(K.yellow("Warning: dappStorageId not found in latest.json. Re-publish the contract to capture it, or pass DappStorage manually."));let k=new xt,$=a+1;k.moveCall({target:`${H}::migrate::migrate_to_v${$}`,arguments:[k.object(f),k.object(y),k.pure.address(H)]}),await c.signAndSendTxn({tx:k,onSuccess:F=>{console.log(K.green(`Migration Transaction Digest: ${F.digest}`))},onError:F=>{console.log(K.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(F)}})}else console.log(`
|
|
89
|
+
\u2705 No schema changes \u2014 migration step skipped.`),n==="localnet"&&await new Promise(k=>setTimeout(k,2e3))}catch(v){throw S&&ke(i,n,S),console.log(K.red("upgrade handler execution failed!")),v}}import{TESTNET_DUBHE_HUB_OBJECT_ID as lr,TESTNET_DUBHE_FRAMEWORK_PACKAGE_ID as cr,MAINNET_DUBHE_HUB_OBJECT_ID as dr,MAINNET_DUBHE_FRAMEWORK_PACKAGE_ID as ur}from"@0xobelisk/sui-client";import{TESTNET_DUBHE_FRAMEWORK_PACKAGE_ID as gr}from"@0xobelisk/sui-client";import{Dubhe as Un}from"@0xobelisk/sui-client";import*as He from"fs";function Ln(){console.log(D.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{be("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let n of t)try{let o=be(`pgrep -f "${n}"`,{stdio:"pipe"}).toString().trim();if(o){let s=o.split(`
|
|
90
|
+
`).filter(r=>r);console.log(D.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${n}"`)),s.forEach(r=>{try{be(`kill -TERM ${r}`,{stdio:"ignore"}),console.log(D.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{be(`kill -KILL ${r}`,{stdio:"ignore"}),console.log(D.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log(D.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?D.green(" \u2514\u2500 Local Node stopped successfully"):D.gray(" \u2514\u2500 No running Local Node found"))}function Hn(e){try{He.existsSync(e)?(console.log(D.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),He.rmSync(e,{recursive:!0,force:!0}),console.log(D.green(" \u2514\u2500 Directory removed successfully"))):console.log(D.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(D.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function Vn(){try{if(process.platform==="win32")return be('tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH').toString().trim().toLowerCase().includes("sui.exe");{let e=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let t of e)try{let n=be(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(n&&n.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function Wn(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,n)=>{let s=new Un({secretKey:t}).getSigner();_t("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${s.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${n}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(D.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(D.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Bn(e){let t=()=>{console.log(D.yellow(`
|
|
91
|
+
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Pt(e,t){if(t)console.log(D.cyan(`
|
|
92
|
+
\u{1F504} Force mode enabled`)),Ln(),console.log(D.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await ae(3e3),Hn(e),console.log("");else if(Vn()){console.log(D.yellow(`
|
|
93
|
+
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(D.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(D.yellow(" \u2514\u2500 Please stop the existing process first"));return}ge(),console.log("\u{1F680} Starting Local Node...");let n=null;try{let o=["start","--with-faucet"];if(t&&o.push("--force-regenesis"),o.push("--data-ingestion-dir",e),n=_t("sui",o,{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),n.on("error",r=>{console.error(D.red(`
|
|
94
|
+
\u274C Failed to Start Local Node`)),console.error(D.red(` \u2514\u2500 Error: ${r.message}`))}),await ae(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(` \u251C\u2500 Force Regenesis: ${t?"Yes":"No"}`),console.log(" \u251C\u2500 RPC server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await Wn(),await ae(2e3),Ye("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new V("Please check your privateKey.");console.log(D.green("\u{1F389} Local environment is ready!")),Bn(n),await new Promise(r=>{n?.on("exit",()=>r())})}catch(o){console.error(D.red(`
|
|
95
|
+
\u274C Failed to Start Local Node`)),console.error(D.red(` \u2514\u2500 Error: ${o.message}`)),n&&n.kill("SIGINT"),process.exit(1)}}import zn from"readline";import Kn from"yargs";import te from"chalk";import qn from"dotenv";import{spawn as Gn}from"child_process";qn.config();var kt=!0,nt=["shell","wait"],h=(e=0)=>{kt&&process.exit(e)},St=()=>we.filter(e=>!nt.includes(e.command)).map(e=>e.command),Jn={command:"shell",describe:"Open a shell to interact with the Dubhe System",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL injected into every sub-command (overrides the default for the selected network)"}})},handler:async({network:e,"rpc-url":t})=>{e=="default"&&(e=await M(),console.log(te.yellow(`Use default network: [${e}]`))),kt=!1;let n=[];function o(r){let i=St().filter(c=>c?c.startsWith(r.toLowerCase()):!1);return[i.length?i:St(),r]}let s=zn.createInterface({input:process.stdin,output:process.stdout,prompt:`dubhe(${te.green(e)}${t?te.gray("[custom-rpc]"):""}) ${te.bold(">")} `,completer:o,historySize:200});s.on("line",async r=>{let i=r.trim();if(!i){s.prompt();return}n.push(i);let c=i.split(/\s+/),a=c[0].toLowerCase(),d=we.find(u=>u.command===a&&!nt.includes(a));if(c.includes("--help")||c.includes("-h")){if(d)try{let u=Gn("node",[process.argv[1],a,"--help"],{stdio:"inherit",env:{...process.env}});u.on("exit",()=>{s.prompt()}),u.on("error",()=>{console.log(`
|
|
96
|
+
${d.describe||`${a} command`}`),console.log(`
|
|
97
|
+
Usage: ${a} [options]`),console.log(`
|
|
98
|
+
For complete help with all options, please exit shell and run:`),console.log(te.cyan(` dubhe ${a} --help`)),s.prompt()});return}catch{console.log(`
|
|
99
|
+
${d.describe||`${a} command`}`),console.log(`
|
|
100
|
+
Usage: ${a} [options]`),console.log(`
|
|
101
|
+
For complete help with all options, please exit shell and run:`),console.log(te.cyan(` dubhe ${a} --help`))}else console.log(`\u{1F937} Unknown command: "${a}". Type 'help' to see available commands.`);s.prompt();return}if(d)try{let{builder:u,handler:g}=d,f=Kn().exitProcess(!1);if(u){typeof u=="function"?u(f):f.options(u);let y=c.slice(1),w=y.includes("--network")||y.includes("-n"),T=y.includes("--rpc-url"),p=f.parseSync([a,...w?[]:["--network",e],...T||!t?[]:["--rpc-url",t],...y]);g&&await g(p)}}catch(u){console.log(te.red(u))}else if(a=="help"){console.log("Available dubhe commands:");let u=we.filter(f=>!nt.includes(f.command)),g=Math.max(...u.map(f=>(typeof f.command=="string"?f.command:Array.isArray(f.command)?f.command[0]:"").length));u.forEach(f=>{let w=(typeof f.command=="string"?f.command:Array.isArray(f.command)?f.command[0]:"").padEnd(g);console.log(` ${te.green(w)} ${f.describe}`)}),s.prompt();return}else if(["exit","quit"].indexOf(a)!==-1){console.log("Goodbye You will have a nice day! \u{1F44B}"),s.close();return}else console.log(`\u{1F937} Unknown command: "${i}". Type 'help' to see available commands.`);s.prompt()}),s.on("close",()=>{process.exit(0)}),ge(),s.prompt()}},Et=Jn;var Yn={command:"node",describe:"Manage local Sui node",builder:{"data-dir":{type:"string",default:".chk",desc:"Path to the data directory"},force:{type:"boolean",default:!1,desc:"Force restart: stop existing node and remove data directory"}},async handler({"data-dir":e,force:t}){try{await Pt(e,t)}catch(n){console.error("Error executing command:",n),h(1)}h()}},Tt=Yn;import{requestSuiFromFaucetV2 as Xn,getFaucetHost as Qn}from"@mysten/sui/faucet";import{SuiClient as Zn,getFullnodeUrl as eo}from"@mysten/sui/client";var ot=60,to=1e3,It=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],no={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",alias:"r",desc:"Sui address to fund"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL for balance check (overrides the default for the selected network)"}})},async handler({network:e,recipient:t,"rpc-url":n}){let o="";t===void 0?o=z({network:e}).getAddress():o=t,console.log(`
|
|
102
|
+
\u{1F30A} Starting Faucet Operation...`),console.log(` \u251C\u2500 Network: ${e}`),t===void 0?(console.log(" \u251C\u2500 Using Environment PrivateKey"),console.log(` \u251C\u2500 Generated Address: ${o}`)):console.log(` \u251C\u2500 Using Provided Address: ${o}`),console.log(" \u251C\u2500 Requesting funds from faucet...");let s=0,r=!1,i=0,c=Date.now(),a=!1,d=()=>{a=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
103
|
+
\u2514\u2500 Operation cancelled by user`),h(1)};process.on("SIGINT",d);try{for(;s<ot&&!r&&!a;)try{await Xn({host:Qn(e),recipient:o}),r=!0}catch{if(a)break;s++,s===ot&&(console.log(` \u2514\u2500 Failed to request funds after ${ot} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),console.log(" \u2514\u2500 You can visit https://faucet.testnet.sui.io/ to request funds manually."),h(1));let w=Math.floor((Date.now()-c)/1e3),T=It[i%It.length];i++,process.stdout.write(`\r \u251C\u2500 ${T} Retrying... (${w}s)`),await new Promise(p=>setTimeout(p,to))}}finally{process.removeListener("SIGINT",d)}a&&h(1),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let u=new Zn({url:n||eo(e)}),g={owner:o},f=await u.getBalance(g);console.log(`
|
|
104
|
+
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(f.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
|
|
49
105
|
\u2705 Faucet Operation Complete
|
|
50
|
-
`),
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
`,
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
`+l:r=l,G.writeFileSync(`${o}/.env`,r),console.log(B.green(`File created/updated at: ${o}/.env`)),console.log(B.blue(`New account generated: ${c.toSuiAddress()}`))}}var oo={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await Re(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ae=oo;import no from"chalk";import ro from"dotenv";ro.config();async function Ue(e){try{let o=await C({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new v("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(no.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var so={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await Ue(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ve=so;import{mkdirSync as ao,writeFileSync as io}from"fs";import{dirname as co}from"path";async function lo(e,t,o,n){let r=await R(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
106
|
+
`),h()}},Dt=no;import{codegen as oo,loadConfig as so}from"@0xobelisk/sui-common";import At from"chalk";import ro from"node:path";var io={command:"generate",aliases:["schemagen"],describe:"Generate Move code from dubhe.config.ts",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},mode:{type:"string",choices:["user_pays","dapp_subsidizes"],default:"user_pays",desc:"Initial settlement mode for this DApp (only applies on first generate)"}},async handler({"config-path":e,network:t,mode:n}){try{if(!e)throw new Error("Config path is required");t=="default"&&(t=await M(),console.log(At.yellow(`Use default network: [${t}]`)));let o=await so(e),s=ro.dirname(e);await oo(s,o,t,n==="dapp_subsidizes"?0:1),h()}catch(o){console.log(At.red("Generate failed!")),console.error(o.message),h(1)}}},Nt=io;import{loadConfig as ao}from"@0xobelisk/sui-common";import{execSync as lo}from"child_process";import{join as co}from"path";import Ft from"chalk";var uo={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0},force:{type:"boolean",default:!1,desc:"Clear existing published state for this network before build (use when re-publishing or to fix PublishErrorNonZeroAddress)"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},async handler({network:e,"config-path":t,"gas-budget":n,force:o,"rpc-url":s}){try{e=="default"&&(e=await M(),console.log(Ft.yellow(`Use default network: [${e}]`)));let r=await ao(t),i=co(process.cwd(),"src",r.name),c=X(i);if(c.length>0&&(process.stdout.write(Q(c)),!await je("Some entry functions are missing ensure_latest_version. Proceed with publish anyway?"))){console.log(Ft.red("Publish cancelled.")),h(1);return}let a=s?[s]:void 0;lo(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await vt(r,e,o,n,a)}catch(r){B(r),h(1)}h()}},Rt=uo;import{execFileSync as po,execSync as go}from"child_process";import{loadConfig as fo}from"@0xobelisk/sui-common";function mo(){try{return go("sui client active-env",{encoding:"utf-8",stdio:"pipe"}).trim()}catch{return"testnet"}}function ho(e){let t=["move","test"];return e.buildEnv&&t.push("--build-env",e.buildEnv),t.push("--path",e.projectPath),e.list&&t.push("-l"),t.push("--gas-limit",e.gasLimit),e.filter&&!e.list&&t.push(e.filter),t}async function yo(e,t={}){let n=t["gas-limit"]??t.gasLimit??"100000000",s=`${process.cwd()}/src/${e.name}`,r=ho({projectPath:s,gasLimit:n,buildEnv:t.buildEnv,filter:t.filter,list:t.list});return po("sui",r,{stdio:"pipe",encoding:"utf-8"})}function bo(e){return e.filter??e.test}var wo={command:"test [filter]",describe:"Run Move unit tests in Dubhe contracts",builder(e){return e.positional("filter",{type:"string",describe:"Substring of fully qualified test name (see `sui move test --help`); optional when using --list"}).options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Path to the Dubhe config file"},test:{type:"string",describe:"Same as positional [filter] (kept for backward compatibility)"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"},list:{type:"boolean",default:!1,describe:"List all Move unit tests (`sui move test -l`)"}})},async handler(e){let{"config-path":t,"gas-limit":n,list:o}=e,s=bo(e);try{console.log(o?"\u{1F680} Listing Move unit tests":"\u{1F680} Running move test");let r=await fo(t),i=`${process.cwd()}/src/${r.name}`,c=X(i),a=Q(c);a&&process.stdout.write(a);let d=mo(),g=await yo(r,{filter:s,"gas-limit":n,buildEnv:d==="localnet"||d==="devnet"?"testnet":void 0,list:o});g&&process.stdout.write(g)}catch(r){r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),!r.stdout&&!r.stderr&&r.message&&process.stderr.write(r.message),h(1)}h()}},Mt=wo;import{execSync as vo,exec as xo}from"child_process";import st from"path";import Ot from"chalk";import{loadConfig as $o}from"@0xobelisk/sui-common";async function Co(e,t,n=!1){let o=process.cwd(),s=st.join(o,"src",e.name),r;return t==="localnet"?r=`sui move build --build-env testnet --pubfile-path ${st.join(o,"Pub.localnet.toml")} --path ${s}`:r=`sui move build -e ${t} --path ${s}`,n&&(r+=" --dump-bytecode-as-base64"),vo(r,{encoding:"utf-8"})}var _o={command:"build",describe:"Build Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Path to the Dubhe config file"},network:{type:"string",default:"default",choices:["mainnet","testnet","devnet","localnet","default"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":n,"rpc-url":o}){try{t=="default"&&(t=await M(),console.log(Ot.yellow(`Use default network: [${t}]`))),console.log("\u{1F680} Running move build");let s=await $o(e);await Y(t,o);let r=st.join(process.cwd(),"src",s.name),i=X(r),c=Q(i);c&&process.stdout.write(c);let a=await Co(s,t,n);console.log(a),xo(`pnpm dubhe convert-json --config-path ${e}`)}catch(s){console.error(Ot.red("Error executing sui move build:")),s.stdout&&process.stdout.write(s.stdout),s.stderr&&process.stderr.write(s.stderr),!s.stdout&&!s.stderr&&s.message&&process.stderr.write(s.message),h(1)}}},jt=_o;var Po={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){ge()}},Ut=Po;import{Dubhe as Lt}from"@0xobelisk/sui-client";import*as Te from"fs";import Ee from"chalk";async function Ht(e=!1,t=!1){t&&(console.log(Ee.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(Ee.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
|
|
107
|
+
`)));let n=process.cwd(),o,s="";try{s=Te.readFileSync(`${n}/.env`,"utf8");let r=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(r=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),r){let i=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",c=s.split(`
|
|
108
|
+
`),a=!1;for(let g=c.length-1;g>=0;g--){let f=c[g];if(f.endsWith(r)){let[y]=f.split("=");t?a=y==="PRIVATE_KEY":a=y==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(a){for(let g=c.length-1;g>=0;g--)if(c[g].endsWith(r)){let y=`${i}=${r}`;c[g]=y,s=c.join(`
|
|
109
|
+
`),Te.writeFileSync(`${n}/.env`,s);break}}let u=new Lt({secretKey:r}).getSigner();console.log(Ee.blue(`Using existing account: ${u.toSuiAddress()}`));return}}catch{}if(e||!o){let i=new Lt().getSigner();o=i.getSecretKey();let a=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${o}`;s?s=s.trim()+`
|
|
110
|
+
`+a:s=a,Te.writeFileSync(`${n}/.env`,s),console.log(Ee.green(`File created/updated at: ${n}/.env`)),console.log(Ee.blue(`New account generated: ${i.toSuiAddress()}`))}}var So={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await Ht(e,t)}catch(n){console.error("Error generating account:",n),h(1)}h()}},Vt=So;import ko from"chalk";import Eo from"dotenv";Eo.config();async function Wt(e,t){try{let o=await z({network:e,fullnodeUrls:t}).getBalance(),s=Number(o.totalBalance)/1e9;if(s===0)throw new V("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(ko.green(`Current account balance: ${s.toFixed(4)} SUI`))}catch(n){throw new V("Failed to check balance: "+n)}}import To from"chalk";var Io={command:"check-balance",describe:"Check the balance of the account",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],desc:"Network to check balance on",default:"default"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},async handler({network:e,"rpc-url":t}){try{e=="default"&&(e=await M(),console.log(To.yellow(`Use default network: [${e}]`))),await Wt(e,t?[t]:void 0)}catch(n){console.error("Error checking balance:",n),h(1)}h()}},Bt=Io;import{mkdirSync as Do,writeFileSync as Ao}from"fs";import{dirname as No}from"path";function Fo(e){return`${e.replace(/^0x/i,"").padStart(64,"0")}::dapp_key::DappKey`}async function Ro(e,t,n,o,s){let r=await fe(e),i;e==="localnet"&&(i=await re(e));let c=i!==void 0?`
|
|
111
|
+
// Published package ID of the dubhe framework \u2014 required for proxy operations.
|
|
112
|
+
export const FrameworkPackageId: string | undefined = '${i}';
|
|
113
|
+
`:`
|
|
114
|
+
// Published package ID of the dubhe framework \u2014 required for proxy operations.
|
|
115
|
+
// For testnet/mainnet the SDK resolves this automatically via getDefaultConfig().
|
|
116
|
+
export const FrameworkPackageId: string | undefined = undefined;
|
|
117
|
+
`,a=Fo(n),d=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
63
118
|
|
|
64
|
-
export const
|
|
65
|
-
export const
|
|
66
|
-
|
|
67
|
-
export const
|
|
68
|
-
|
|
69
|
-
|
|
119
|
+
export const Network: NetworkType = '${e}';
|
|
120
|
+
export const PackageId = '${t}';
|
|
121
|
+
/** The first-published (original) package ID \u2014 stable across upgrades. Used for dapp_key and indexer filtering. */
|
|
122
|
+
export const OriginalPackageId = '${n}';
|
|
123
|
+
/** Canonical dapp_key type string derived from OriginalPackageId. Pass to the Dubhe SDK and GraphQL queries. */
|
|
124
|
+
export const DappKey = '${a}';
|
|
125
|
+
export const DappHubId = '${r}';
|
|
126
|
+
export const DappStorageId = '${o}';
|
|
127
|
+
${c}`;Mo(d,s,"storeConfig")}async function Mo(e,t,n){Do(No(t),{recursive:!0}),Ao(t,e),n!==void 0&&console.log(`${n}: ${t}`)}async function zt(e,t,n){let s=`${process.cwd()}/src/${e.name}`,r=await J(s,t),i=r.originalPackageId??r.packageId;await Ro(r.network,r.packageId,i,r.dappStorageId??"",n)}import{loadConfig as Oo}from"@0xobelisk/sui-common";import jo from"chalk";var Uo={command:"store-config",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":n}){try{t=="default"&&(t=await M(),console.log(jo.yellow(`Use default network: [${t}]`)));let o=await Oo(e);await zt(o,t,n)}catch(o){console.error("Error storing config:",o),h(1)}h()}},Kt=Uo;import Lo from"chokidar";import{exec as Ho}from"child_process";var Vo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{Ho("pnpm dubhe generate",(o,s,r)=>{if(o){console.error(`Error executing generate: ${o.message}`);return}if(r){console.error(`generate stderr: ${r}`);return}console.log(`generate stdout: ${s}`)})},n=Lo.watch(e,{persistent:!0});n.on("change",o=>{console.log(`${o} has been changed. Running generate...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{n.close(),console.log(`
|
|
128
|
+
Watch stopped.`),h()})}},qt=Vo;import Gt from"wait-on";import ve from"ora";import le from"chalk";import Wo from"net";async function Jt(e){let t={HTTP_PROXY:process.env.HTTP_PROXY,HTTPS_PROXY:process.env.HTTPS_PROXY,http_proxy:process.env.http_proxy,https_proxy:process.env.https_proxy,NO_PROXY:process.env.NO_PROXY,no_proxy:process.env.no_proxy};delete process.env.HTTP_PROXY,delete process.env.HTTPS_PROXY,delete process.env.http_proxy,delete process.env.https_proxy,process.env.NO_PROXY="127.0.0.1,localhost,*.local",process.env.no_proxy="127.0.0.1,localhost,*.local";try{return await e()}finally{Object.keys(t).forEach(n=>{let o=t[n];o!==void 0?process.env[n]=o:delete process.env[n]})}}async function Yt(){return Xt(5432)}async function Xt(e,t="127.0.0.1"){return new Promise(n=>{let o=new Wo.Socket,s=!1,r=setTimeout(()=>{o.destroy(),s||n(!1)},2e3);o.connect(e,t,()=>{s=!0,clearTimeout(r),o.destroy(),n(!0)}),o.on("error",()=>{clearTimeout(r),s||n(!1)})})}async function Bo(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),2e3),n=await fetch("http://127.0.0.1:8080/health",{signal:e.signal,headers:{Accept:"application/json"}});return clearTimeout(t),n.status===200}catch{return!1}}async function zo(e){let t=ve({text:"Waiting for dubhe localnet services...",color:"cyan"});t.start();let n=Date.now();for(;Date.now()-n<e.timeout;){try{if(await Jt(()=>Gt({resources:["http://127.0.0.1:9123","http://127.0.0.1:4000"],timeout:e.interval,interval:500,validateStatus:s=>s===200})),await Yt()){t.succeed(le.green("All dubhe localnet services are ready!"));return}}catch{}await new Promise(o=>setTimeout(o,e.interval))}throw new Error("Timeout waiting for services")}async function Ko(e){let t=ve({text:"Waiting for local database...",color:"cyan"});t.start();let n=Date.now();for(;Date.now()-n<e.timeout;){if(await Yt()){t.succeed(le.green("Local database is ready!"));return}await new Promise(s=>setTimeout(s,e.interval))}throw new Error("Timeout waiting for local database")}async function qo(e){let t=ve({text:"Waiting for local Sui node...",color:"cyan"});t.start();let n=Date.now();for(;Date.now()-n<e.timeout;){if(await Xt(9123)){t.succeed(le.green("Local Sui node is ready!"));return}await new Promise(s=>setTimeout(s,e.interval))}throw new Error("Timeout waiting for local Sui node")}async function Go(e){let t=ve({text:"Waiting for local indexer...",color:"cyan"});t.start();let n=Date.now();for(;Date.now()-n<e.timeout;){if(await Bo()){t.succeed(le.green("Local indexer is ready!"));return}await new Promise(s=>setTimeout(s,e.interval))}throw new Error("Timeout waiting for local indexer")}var Jo={command:"wait",describe:"Wait for service(s) to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for (single service)"}).option("localnet",{type:"boolean",description:"Wait for all dubhe localnet services (sui localnode:9000&9123, postgres:5432, graphql:4000)",default:!1}).option("local-database",{type:"boolean",description:"Wait for local database (PostgreSQL on port 5432)",default:!1}).option("local-node",{type:"boolean",description:"Wait for local Sui node (port 9123)",default:!1}).option("local-indexer",{type:"boolean",description:"Wait for local indexer (health check at http://127.0.0.1:8080/health)",default:!1}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:24*60*60*1e3}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3}).check(t=>{let n=!!t.url,o=!!t.localnet,s=!!t["local-database"],r=!!t["local-node"],i=!!t["local-indexer"],c=[n,o,s,r,i].filter(Boolean).length;if(c===0)throw new Error("Please provide at least one option: --url, --localnet, --local-database, --local-node, or --local-indexer");if(n&&c>1)throw new Error("Cannot use --url together with other options");if(o&&(s||r||i))throw new Error("Cannot use --localnet together with individual service options");return!0})},async handler(e){let t=e;try{if(t.localnet)await zo(t);else if(t["local-database"])await Ko(t);else if(t["local-node"])await qo(t);else if(t["local-indexer"])await Go(t);else{let n=ve({text:`Waiting for ${t.url}...`,color:"cyan"});n.start(),await Jt(()=>Gt({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:o=>o===200})),n.succeed(le.green("Service is ready!"))}h()}catch{let o=ve(),s="Timeout waiting for service",r="Please make sure the service is running...";t.localnet?(s="Timeout waiting for dubhe localnet services",r=`Please make sure all required services are running:
|
|
129
|
+
- Sui localnode on port 9000
|
|
130
|
+
- Sui faucet on port 9123
|
|
131
|
+
- PostgreSQL database on port 5432
|
|
132
|
+
- Dubhe GraphQL server on port 4000`):t["local-database"]?(s="Timeout waiting for local database",r="Please make sure PostgreSQL is running on port 5432"):t["local-node"]?(s="Timeout waiting for local Sui node",r="Please make sure Sui localnode is running on port 9123"):t["local-indexer"]&&(s="Timeout waiting for local indexer",r="Please make sure indexer is running and health endpoint is available at http://127.0.0.1:8080/health"),o.fail(le.red(s)),console.error(le.yellow(r)),h(1)}}},Qt=Jo;var Yo={command:"switch-env",describe:"Switch environment",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},async handler(e){await Y(e.network,e["rpc-url"]),h()}},Zt=Yo;import Xo from"dotenv";import ce from"chalk";Xo.config();var Qo={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},handler:async({network:e,"rpc-url":t})=>{try{e=="default"&&(e=await M(),console.log(ce.yellow(`Use default network: [${e}]`)));let o=z({network:e,fullnodeUrls:t?[t]:void 0}),s=o.getSigner();console.log(ce.blue("Account Information:")),console.log(` Network: ${ce.green(e)}`),console.log(` Address: ${ce.green(s.toSuiAddress())}`);try{let r=await o.getBalance("0x2::sui::SUI"),i=(Number(r.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${ce.green(i)} SUI`)}catch{console.log(` Balance: ${ce.red("Failed to fetch balance")} ${ce.gray("(Network error)")}`)}h()}catch(n){B(n),h(1)}}},en=Qo;import{loadConfig as Zo}from"@0xobelisk/sui-common";async function tn(e,t,n,o){if(n)await Se(e.name,t,n,o);else{let s=`${process.cwd()}/src/${e.name}`,r=await _e(s,t);await Se(e.name,t,r,o)}}import es from"chalk";var ts={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},async handler({network:e,"config-path":t,"package-id":n,"rpc-url":o}){try{e=="default"&&(e=await M(),console.log(es.yellow(`Use default network: [${e}]`)));let s=await Zo(t);await tn(s,e,n,o?[o]:void 0)}catch(s){B(s),h(1)}h()}},nn=ts;import l from"chalk";import{spawn as rs}from"child_process";import an from"cli-table3";import We from"inquirer";import*as I from"fs";import*as O from"path";import*as ue from"os";import*as cn from"net";import is from"axios";var de={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.121",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",author:"team@obelisk.build",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",format:"prettier --write .","format:check":"prettier --check .",lint:"eslint . --ext .ts",test:"vitest run","test:all":"pnpm test && pnpm test:integration","test:coverage":"vitest run --coverage","test:integration":"vitest run --config vitest.integration.config.ts","test:localnet":"vitest run --config vitest.integration.config.ts tests/integration/localnet.test.ts","test:testnet":"vitest run --config vitest.integration.config.ts tests/integration/testnet.test.ts","test:watch":"vitest","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"1.35.0","@types/wait-on":"^5.3.4",axios:"^1.12.0",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",typescript:"^5.8.3","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^22.16.0","@types/yargs":"^17.0.10",eslint:"^9.0.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"},engines:{node:">=22.0.0"},publishConfig:{access:"public"}};import Ve from"chalk";import*as on from"cli-progress";import*as sn from"fs";import os from"axios";async function rn(e,t){try{let n=await os.get(e,{responseType:"stream",timeout:3e4,headers:{"User-Agent":"dubhe-cli"},maxRedirects:5,validateStatus:o=>o<400});await ss(n,t),console.log(Ve.green(" \u2713 Successfully downloaded"))}catch(n){if(n.code==="ENOTFOUND")throw new Error(`DNS resolution failed: ${n.message}. Please check your internet connection.`);if(n.code==="ECONNRESET")throw new Error(`Connection reset: ${n.message}. Please check your network connection.`);if(n.code==="ETIMEDOUT")throw new Error(`Connection timeout: ${n.message}. Please check your network connection.`);if(n.message.includes("protocol mismatch"))throw new Error(`Protocol mismatch: ${n.message}. Please check your network configuration.`);if(n.response)throw new Error(`HTTP ${n.response.status}: ${n.response.statusText}`);{let o=n instanceof Error?n.message:String(n);throw new Error(`Download failed: ${o}`)}}}async function ss(e,t){let n=parseInt(e.headers["content-length"]||"0"),o=new on.SingleBar({format:Ve.cyan("Download Progress")+" |{bar}| {percentage}% | {value}/{total} MB | Speed: {speed} MB/s | ETA: {eta}s",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,barsize:30,forceRedraw:!0});n>0?o.start(Math.round(n/1024/1024*100)/100,0,{speed:"0.00"}):console.log(Ve.blue("\u{1F4E5} Downloading... (unable to get file size)"));let s=sn.createWriteStream(t),r=0,i=Date.now();return new Promise((c,a)=>{e.data.on("data",d=>{if(r+=d.length,n>0){let u=Math.round(r/1024/1024*100)/100,g=(Date.now()-i)/1e3,f=g>0?Math.round(u/g*100)/100:0;o.update(u,{speed:f.toFixed(2)})}}),e.data.pipe(s),s.on("finish",()=>{n>0&&o.stop();let d=Math.round(r/1024/1024*100)/100,u=(Date.now()-i)/1e3,g=u>0?Math.round(d/u*100)/100:0;console.log(Ve.green(`\u2713 Download completed! ${d} MB, average speed: ${g} MB/s`)),c()}),s.on("error",d=>{n>0&&o.stop(),a(d)})})}function it(){let e=process.platform,t=process.arch,n,o;switch(e){case"darwin":n="macos";break;case"win32":n="windows";break;case"linux":n="ubuntu";break;default:n=e}switch(t){case"x64":o="x86_64";break;case"arm64":o="aarch64";break;default:o=t}return{platform:e,arch:t,platformForAsset:n,archForAsset:o}}var L={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:O.join(ue.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe",binaryName:"dubhe-indexer",installDir:O.join(ue.homedir(),".dubhe","bin")}};async function q(e,t=[]){return new Promise(n=>{let o=rs(e,t,{shell:!0}),s="",r="";o.stdout?.on("data",i=>{s+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}),o.on("close",i=>{n({code:i||0,stdout:s,stderr:r})}),o.on("error",()=>{n({code:-1,stdout:s,stderr:r})})})}async function dn(e,t={}){try{let n={timeout:3e4,maxRedirects:5,validateStatus:s=>s<500,...t},o=await is(e,n);return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,json:async()=>o.data,headers:o.headers}}catch(n){let o=n.response?.status||0,s=n.response?.statusText||n.message;return n.code==="ENOTFOUND"?s="DNS resolution failed - please check your internet connection":n.code==="ECONNRESET"?s="Connection reset - please check your network connection":n.code==="ETIMEDOUT"?s="Connection timeout - please check your network connection":n.message.includes("protocol mismatch")&&(s="Protocol mismatch - please check your network configuration"),{ok:!1,status:o,statusText:s,json:async()=>n.response?.data||{},headers:n.response?.headers||{}}}}async function at(e,t=10,n=3){let o=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=n;s++)try{s>1&&console.log(l.gray(` Retry ${s}/${n}...`));let r=await dn(o,{headers:{"User-Agent":"dubhe-cli",Accept:"application/vnd.github.v3+json"}});if(!r.ok)throw r.status===403?new Error(`GitHub API rate limit: ${r.status}. Please retry later or set GITHUB_TOKEN environment variable`):new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);return await r.json()}catch(r){if(s>1&&console.log(l.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${r instanceof Error?r.message:String(r)}`)),s===n)return console.error(l.red(` \u274C Failed to fetch releases after ${n} attempts`)),[];await new Promise(i=>setTimeout(i,1e3*s))}return[]}function De(e,t){return e.assets.filter(o=>{let s=o.name.toLowerCase(),r=[t.platformForAsset.toLowerCase(),...t.platformForAsset==="macos"?["darwin","apple"]:[],...t.platformForAsset==="windows"?["win","win32","windows"]:[],...t.platformForAsset==="ubuntu"?["linux","gnu"]:[]],i=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],c=r.some(u=>s.includes(u)),a=i.some(u=>s.includes(u)),d=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return c&&a&&d}).map(o=>o.name)}async function as(e,t){let n=L[e];return n?(await at(n.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:De(s,t).length>0})):[]}async function ls(e){try{let t=Ae();if(!t){console.log(l.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:n,configFile:o}=t,s=n==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(I.existsSync(o)&&I.readFileSync(o,"utf8").includes(e)){console.log(l.green(` \u2713 PATH already configured in ${o}`));return}let i=`# Added by dubhe doctor
|
|
133
|
+
${s}`;I.appendFileSync(o,`
|
|
134
|
+
${i}
|
|
135
|
+
`),console.log(l.green(` \u2713 Automatically added to PATH in ${o}`)),console.log(l.blue(` \u{1F4DD} To apply changes: source ${o} or restart terminal`))}catch(t){console.log(l.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(l.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function Ae(){let e=ue.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:O.join(e,".zshrc")};if(t.includes("bash")){let o=O.join(e,".bash_profile"),s=O.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&I.existsSync(o)?o:s}}else if(t.includes("fish")){let o=O.join(e,".config","fish");return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),{shellName:"fish",configFile:O.join(o,"config.fish")}}}let n=[{name:"zsh",file:O.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?O.join(e,".bash_profile"):O.join(e,".bashrc")},{name:"bash",file:O.join(e,".bashrc")}];for(let o of n)if(I.existsSync(o.file))return{shellName:o.name,configFile:o.file};return process.env.ZSH||I.existsSync("/bin/zsh")?{shellName:"zsh",configFile:O.join(e,".zshrc")}:null}async function rt(e,t){let n=L[e];if(!n)return console.error(`Unknown tool: ${e}`),!1;let o=it();console.log(l.gray(` System: ${o.platform}/${o.arch}`));try{console.log(l.gray(" Fetching release information..."));let s=await at(n.repo,10);if(s.length===0)return console.error(l.red(` \u274C Unable to fetch releases for ${n.name}`)),!1;let r=null;if(t){if(t.startsWith("v")||(t=`v${t}`),r=s.find(p=>p.tag_name===t)||null,!r)return console.error(`Version ${t} not found`),!1}else for(let p of s)if(De(p,o).length>0){r=p;break}if(!r)return console.error("No compatible version found"),!1;let i=De(r,o);if(i.length===0)return console.error(`Version ${r.tag_name} has no compatible binaries`),!1;let c=i[0],a=r.assets.find(p=>p.name===c);if(!a)return console.error(`Asset file not found: ${c}`),!1;console.log(l.green(` \u2713 Found compatible version: ${r.tag_name}`)),console.log(l.gray(` Download file: ${a.name}`));try{let p=await dn(a.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!p.ok)console.log(l.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${p.status})`));else{let b=p.headers["content-length"];b&&console.log(l.gray(` File size: ${Math.round(parseInt(b)/1024/1024*100)/100} MB`))}}catch{console.log(l.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}I.existsSync(n.installDir)||(I.mkdirSync(n.installDir,{recursive:!0}),console.log(l.gray(` Created install directory: ${n.installDir}`))),console.log(l.blue(" \u{1F4E5} Downloading..."));let d=O.join(ue.tmpdir(),a.name),u=3;for(let p=1;p<=u;p++)try{p>1&&console.log(l.gray(` Attempt ${p} to download...`)),await rn(a.browser_download_url,d);break}catch(b){let m=b instanceof Error?b.message:String(b);if(console.log(l.yellow(` \u26A0\uFE0F Download failed (attempt ${p}): ${m}`)),p===u)throw new Error(`Download failed after ${u} attempts: ${m}`);console.log(l.gray(` Waiting ${p*2} seconds before retry...`)),await new Promise(C=>setTimeout(C,p*2e3))}console.log(l.blue(" \u{1F4E6} Extracting and installing..."));let g=O.join(ue.tmpdir(),`extract_${Date.now()}`);if(I.mkdirSync(g,{recursive:!0}),a.name.endsWith(".tar.gz")||a.name.endsWith(".tgz")){let p=await q("tar",["-xzf",d,"-C",g]);if(p.code!==0)throw new Error(`Extraction failed: ${p.stderr}`)}else if(a.name.endsWith(".tar.bz2")){let p=await q("tar",["-xjf",d,"-C",g]);if(p.code!==0)throw new Error(`Extraction failed: ${p.stderr}`)}else if(a.name.endsWith(".tar.xz")){let p=await q("tar",["-xJf",d,"-C",g]);if(p.code!==0)throw new Error(`Extraction failed: ${p.stderr}`)}else if(a.name.endsWith(".zip")){let p=await q("unzip",["-q",d,"-d",g]);if(p.code!==0)throw new Error(`Extraction failed: ${p.stderr}`)}else throw new Error(`Unsupported compression format: ${a.name}`);let f=p=>{let b=I.readdirSync(p,{withFileTypes:!0});for(let m of b){let C=O.join(p,m.name);if(m.isDirectory()){let S=f(C);if(S)return S}else if(m.name===n.binaryName||m.name===`${n.binaryName}.exe`)return C}return null},y=f(g);if(!y)throw new Error(`Cannot find ${n.binaryName} binary in extracted files`);let w=O.join(n.installDir,n.binaryName+(process.platform==="win32"?".exe":""));return I.copyFileSync(y,w),process.platform!=="win32"&&I.chmodSync(w,493),I.rmSync(d,{force:!0}),I.rmSync(g,{recursive:!0,force:!0}),console.log(l.green(" \u2705 Installation completed!")),console.log(l.gray(` Location: ${w}`)),console.log(l.gray(` Version: ${r.tag_name}`)),(process.env.PATH||"").includes(n.installDir)||(console.log(l.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(l.gray(` Please add to PATH: set PATH=%PATH%;${n.installDir}`)):await ls(n.installDir)),!0}catch(s){return console.error(l.red(`\u274C Installation failed: ${s}`)),!1}}async function cs(e){let t=it(),n=await as(e,t);if(n.length===0)return console.log(l.red(`Unable to get version information for ${e}`)),null;let o=n.filter(r=>r.hasCompatibleAsset).slice(0,5);if(o.length===0)return console.log(l.red("No compatible versions found for current system")),null;console.log(l.blue(`
|
|
136
|
+
\u{1F4CB} Select version for ${e}`)),console.log(l.gray(`System: ${t.platform}/${t.arch}`)),console.log(l.gray(`Compatible versions (latest 5):
|
|
137
|
+
`));let s=o.map((r,i)=>({name:`${r.version} ${i===0?l.green("(latest)"):l.gray("(available)")}`,value:r.version,short:r.version}));try{let r=await We.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new We.Separator,{name:l.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return r.version==="cancel"?(console.log(l.gray("Installation cancelled")),null):r.version}catch{return console.log(l.gray(`
|
|
138
|
+
Installation cancelled`)),null}}function Be(e){let t=L[e];if(!t)return!1;let n=O.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return I.existsSync(n)}async function ds(){try{let e=de.version,t=await q("dubhe-indexer",["--version"]);if(t.code!==0)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot get dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let n=t.stdout.trim().match(/dubhe-indexer\s+(\S+)/);if(!n)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot parse dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let o=n[1];return e===o?{name:"Dubhe-indexer Version Consistency",status:"success",message:`Versions match (${e})`}:{name:"Dubhe-indexer Version Consistency",status:"warning",message:`Version mismatch: sui-cli ${e}, dubhe-indexer ${o}`,fixSuggestion:`Consider reinstalling dubhe-indexer to match sui-cli version ${e}`}}catch{return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Version check failed",fixSuggestion:"Unable to verify version consistency"}}}async function Ie(e,t="--version"){try{let n=await q(e,[t]);if(n.code===0){let o=n.stdout.trim().split(`
|
|
139
|
+
`)[0];return{name:e,status:"success",message:`Installed ${o}`}}else{if(Be(e)){let o=Ae(),s=o?o.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:ln(e)}}}catch{if(Be(e)){let o=Ae(),s=o?o.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:ln(e)}}}function ln(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function us(){try{let e=await q("node",["--version"]);if(e.code===0){let t=e.stdout.trim();return parseFloat(t.replace("v",""))>=18?{name:"Node.js Version",status:"success",message:`${t} (meets requirement >=18.0)`}:{name:"Node.js Version",status:"warning",message:`${t} (recommend upgrade to >=18.0)`,fixSuggestion:"Please upgrade Node.js to 18.0 or higher"}}else return{name:"Node.js Version",status:"error",message:"Not installed",fixSuggestion:"Please install Node.js 18.0 or higher"}}catch{return{name:"Node.js Version",status:"error",message:"Check failed",fixSuggestion:"Please install Node.js"}}}async function ps(){try{return(await q("docker",["info"])).code===0?{name:"Docker Service",status:"success",message:"Running"}:{name:"Docker Service",status:"warning",message:"Not running",fixSuggestion:"Please start Docker service"}}catch{return{name:"Docker Service",status:"error",message:"Check failed",fixSuggestion:"Please install and start Docker"}}}async function gs(){try{let e=await q("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}async function un(e){let t=["127.0.0.1","0.0.0.0"];for(let n of t)if(!await fs(e,n))return!1;return!0}async function fs(e,t){return new Promise(n=>{let o=cn.createServer(),s=setTimeout(()=>{o.close(),n(!1)},2e3);o.listen(e,t,()=>{clearTimeout(s),o.close(()=>{n(!0)})}),o.on("error",r=>{clearTimeout(s),o.close(),r.code,n(!1)})})}async function ms(){try{return await un(5432)?{name:"PostgreSQL Port (5432)",status:"success",message:"Available"}:{name:"PostgreSQL Port (5432)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"PostgreSQL Port (5432)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}async function hs(){try{return await un(4e3)?{name:"GraphQL Server Port (4000)",status:"success",message:"Available"}:{name:"GraphQL Server Port (4000)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"GraphQL Server Port (4000)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}function ys(e){let t={success:l.green("\u2713"),warning:l.yellow("!"),error:l.red("\u2717")},n={success:l.green("Pass"),warning:l.yellow("Warning"),error:l.red("Fail")},o="";return e.status==="success"?o=e.message:o=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${n[e.status]}`,o]}async function bs(e){if(console.log(l.bold.blue(`
|
|
140
|
+
\u{1F50D} Dubhe Doctor - Development Environment Checker
|
|
141
|
+
`)),e.listVersions){let m=e.listVersions;L[m]||(console.error(l.red(`\u274C Unsupported tool: ${m}`)),h(1)),console.log(l.blue(`\u{1F4CB} Available versions for ${m}:`));let C=it();console.log(l.gray(`System: ${C.platform}/${C.arch}
|
|
142
|
+
`));let S=L[m],_=await at(S.repo,10);_.length===0&&(console.log(l.red("Unable to get version information")),h(1));let v=_.map(x=>({version:x.tag_name,hasCompatibleAsset:De(x,C).length>0,publishDate:new Date(x.published_at).toLocaleDateString("en-US")})),j=new an({head:[l.bold.cyan("Version"),l.bold.cyan("Compatibility"),l.bold.cyan("Release Date")],colWidths:[30,15,25]});if(v.forEach(x=>{j.push([x.version,x.hasCompatibleAsset?l.green("\u2713 Compatible"):l.red("\u2717 Incompatible"),x.publishDate])}),console.log(j.toString()),e.debug&&v.length>0){console.log(l.blue(`
|
|
143
|
+
\u{1F50D} Debug Information:`));let x=v.find(E=>E.hasCompatibleAsset);if(x){let E=_.find(A=>A.tag_name===x.version);if(E){console.log(l.gray(`Latest compatible version: ${x.version}`)),console.log(l.gray("Available asset files:")),E.assets.forEach(W=>{console.log(l.gray(` - ${W.name}`))});let A=De(E,C);console.log(l.gray("Compatible asset files:")),A.forEach(W=>{console.log(l.green(` \u2713 ${W}`))})}}}h()}if(console.log(l.gray(`Checking your development environment...
|
|
144
|
+
`)),e.install){let m=e.install;L[m]||(console.error(l.red(`\u274C Unsupported tool: ${m}`)),console.log(l.gray(`Supported tools: ${Object.keys(L).join(", ")}`)),h(1));let C=null;e.selectVersion?(C=await cs(m),C||h(1)):m==="dubhe-indexer"&&(C=de.version,console.log(l.blue(`\u{1F4E6} Installing dubhe-indexer version ${C} (matching sui-cli version)`)));let S=await rt(m,C||void 0);h(S?0:1)}let t=[];console.log(`Running checks...
|
|
145
|
+
`);let n=await us();t.push(n);let o=await Ie("pnpm");t.push(o);let s=await gs();s.status==="error"&&(s.status="warning"),t.push(s);let r=await Ie("docker");t.push(r);let i=null;r.status==="success"&&(i=await ps(),t.push(i));let c=await Ie("docker-compose");t.push(c);let a=await Ie("sui");t.push(a);let d=await Ie("dubhe-indexer");if(t.push(d),d.status==="success"){let m=await ds();t.push(m)}let u=await ms();t.push(u);let g=await hs();t.push(g);let f=new an({head:[l.bold.cyan("Check Item"),l.bold.cyan("Result"),l.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(m=>{f.push(ys(m))}),console.log(f.toString());let y={success:t.filter(m=>m.status==="success").length,warning:t.filter(m=>m.status==="warning").length,error:t.filter(m=>m.status==="error").length};console.log(`
|
|
146
|
+
`+l.bold("\u{1F4CA} Check Summary:")),console.log(` ${l.green("\u2713 Passed:")} ${y.success} items`),console.log(` ${l.yellow("! Warning:")} ${y.warning} items`),console.log(` ${l.red("\u2717 Failed:")} ${y.error} items`);let w=t.find(m=>m.name==="Dubhe-indexer Version Consistency"&&m.status==="warning"&&m.message.includes("Version mismatch"));if(w){console.log(l.yellow(`
|
|
147
|
+
\u26A0\uFE0F Dubhe-indexer version inconsistency detected!`)),console.log(l.gray(` ${w.message}`));try{(await We.prompt([{type:"confirm",name:"reinstallDubheIndexer",message:"Would you like to reinstall dubhe-indexer to match the sui-cli version?",default:!0}])).reinstallDubheIndexer?(console.log(l.blue(`
|
|
148
|
+
\u{1F4E6} Reinstalling dubhe-indexer...
|
|
149
|
+
`)),console.log(l.blue(`${"=".repeat(60)}`)),console.log(l.blue("\u{1F4E6} Installing dubhe-indexer...")),console.log(l.blue(`${"=".repeat(60)}`)),await rt("dubhe-indexer",de.version)?(console.log(l.green(`
|
|
150
|
+
\u2705 Dubhe-indexer reinstallation completed successfully!`)),console.log(l.blue(" Please restart your terminal or run: source ~/.zshrc (or ~/.bashrc)")),console.log(l.blue(" Then run: dubhe doctor to verify the installation"))):(console.log(l.red(`
|
|
151
|
+
\u274C Dubhe-indexer reinstallation failed`)),console.log(l.gray(" You can try manual installation: dubhe doctor --install dubhe-indexer")))):(console.log(l.gray(`
|
|
152
|
+
Version inconsistency ignored. You can reinstall later with:`)),console.log(l.gray(" dubhe doctor --install dubhe-indexer")))}catch{console.log(l.gray(`
|
|
153
|
+
Version inconsistency check cancelled.`))}}let T=t.filter(m=>m.status==="error"),p=T.filter(m=>L[m.name]),b=T.filter(m=>!L[m.name]);if(b.length>0&&(console.log(l.blue(`
|
|
154
|
+
\u{1F527} Missing tools that require manual installation:`)),b.forEach(m=>{console.log(` ${l.red("\u2717")} ${m.name}: ${m.fixSuggestion||m.message}`)})),p.length>0){let m=p.filter(S=>Be(S.name)),C=p.filter(S=>!Be(S.name));if(m.length>0){let S=m.map(x=>x.name).join(", "),_=L[m[0].name]?.installDir||"~/.dubhe/bin",v=Ae(),j=v?v.configFile:"~/.zshrc (or ~/.bashrc)";console.log(l.yellow(`
|
|
155
|
+
\u26A0\uFE0F Tools already installed but not in PATH: ${S}`)),console.log(l.gray(` Location: ${_}`)),console.log(l.blue(" To fix this, apply PATH changes:")),console.log(l.green(` source ${j}`)),console.log(l.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(l.gray(` If you want to reinstall, remove the files from ${_} and run dubhe doctor again`))}if(C.length>0){let S=C.map(_=>_.name).join(", ");console.log(l.blue(`
|
|
156
|
+
\u{1F680} Auto-installable tools detected: ${S}`));try{if((await We.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${S})`,default:!0}])).installAll){console.log(l.blue(`
|
|
157
|
+
\u{1F4E6} Starting installation of auto-installable tools...
|
|
158
|
+
`));let v=[];for(let E of C){console.log(l.blue(`${"=".repeat(60)}`)),console.log(l.blue(`\u{1F4E6} Installing ${E.name}...`)),console.log(l.blue(`${"=".repeat(60)}`));let A=E.name==="dubhe-indexer"?de.version:void 0;E.name==="dubhe-indexer"&&console.log(l.blue(` Using version ${A} (matching sui-cli version)`));let W=await rt(E.name,A);v.push({name:E.name,success:W}),W?console.log(l.green(`
|
|
159
|
+
\u2705 ${E.name} installation completed successfully!`)):(console.log(l.red(`
|
|
160
|
+
\u274C ${E.name} installation failed`)),console.log(l.gray(` Manual installation: dubhe doctor --install ${E.name}`))),console.log("")}console.log(l.blue(`${"=".repeat(60)}`)),console.log(l.bold("\u{1F4CB} Installation Summary:")),console.log(l.blue(`${"=".repeat(60)}`)),v.forEach(E=>{let A=E.success?l.green("\u2705 Success"):l.red("\u274C Failed");console.log(` ${E.name}: ${A}`)});let j=v.filter(E=>E.success).length,x=v.length-j;if(console.log(`
|
|
161
|
+
${l.green("Successful:")} ${j}/${v.length}`),x>0&&console.log(` ${l.red("Failed:")} ${x}/${v.length}`),j>0){let E=Ae(),A=E?E.configFile:"~/.zshrc (or ~/.bashrc)";console.log(l.blue(`
|
|
162
|
+
\u{1F504} Next Steps:`)),console.log(l.yellow(" 1. Apply PATH changes by running:")),console.log(l.green(` source ${A}`)),console.log(l.yellow(" 2. Or restart your terminal")),console.log(l.yellow(" 3. Then run the doctor check again:")),console.log(l.green(" dubhe doctor")),console.log(l.gray(`
|
|
163
|
+
This will verify that all tools are properly configured.`))}else console.log(l.red(`
|
|
164
|
+
\u274C All installations failed. Please check the error messages above.`))}else console.log(l.gray(`
|
|
165
|
+
Auto-installation skipped. You can install them manually later:`)),C.forEach(v=>{console.log(l.gray(` dubhe doctor --install ${v.name}`))})}catch{console.log(l.gray(`
|
|
166
|
+
Installation cancelled. You can install them manually later:`)),C.forEach(v=>{console.log(l.gray(` dubhe doctor --install ${v.name}`))})}}}p.length===0&&(y.error>0?(console.log(l.red(`
|
|
167
|
+
\u274C Your environment has some issues. Please fix them according to the suggestions above.`)),h(1)):y.warning>0?console.log(l.yellow(`
|
|
168
|
+
\u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(l.green(`
|
|
169
|
+
\u2705 Congratulations! Your development environment is fully ready!`))),console.log(l.gray(`
|
|
170
|
+
\u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var ws={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("install",{type:"string",describe:"Auto-install specified tool (sui, dubhe-indexer)",choices:Object.keys(L)}).option("select-version",{type:"boolean",default:!1,describe:"Select specific version for installation"}).option("list-versions",{type:"string",describe:"List available versions for specified tool",choices:Object.keys(L)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await bs({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(l.red("Error occurred during check:"),t),h(1)}}},pn=ws;import vs from"chalk";import{loadConfig as xs}from"@0xobelisk/sui-common";import lt from"fs";var $s=["original_package_id","dubhe_object_id","original_dubhe_package_id","dapp_key","start_checkpoint","package_ids"];function Cs(e,t){let n={...e};for(let o of $s)t[o]!==void 0&&(n[o]=t[o]);if(!n.dapp_key&&n.original_package_id){let o=n.original_package_id.replace(/^0x/i,"").padStart(64,"0");n.dapp_key=`${o}::dapp_key::DappKey`}return n}var _s={command:"convert-json",describe:"Convert JSON from Dubhe config to config.json",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},"output-path":{type:"string",default:"dubhe.config.json",description:"Output path for the config.json file"}})},async handler({"config-path":e,"output-path":t}){try{console.log("\u{1F680} Running convert json");let n=await xs(e),o=JSON.parse(ft(n)),s={};if(lt.existsSync(t))try{s=JSON.parse(lt.readFileSync(t,"utf-8"))}catch{}let r=Cs(o,s);lt.writeFileSync(t,JSON.stringify(r,null,2))}catch(n){console.error(vs.red("Error executing convert json:")),console.log(n.stdout),h(1)}h()}},gn=_s;import{loadConfig as Ps}from"@0xobelisk/sui-common";import{join as Ss}from"path";import fn from"chalk";var ks={command:"upgrade",describe:"Upgrade your move contracts",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Network of the node (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",decs:"Path to the config file"},"bump-version":{type:"boolean",default:!1,desc:"Force a version bump even when no new resources were added (use for breaking logic changes or security fixes that must invalidate old clients)"},"rpc-url":{type:"string",desc:"Custom RPC endpoint URL (overrides the default for the selected network)"}})},async handler({network:e,"config-path":t,"bump-version":n,"rpc-url":o}){try{e=="default"&&(e=await M(),console.log(fn.yellow(`Use default network: [${e}]`)));let s=await Ps(t),r=Ss(process.cwd(),"src",s.name),i=X(r);if(i.length>0&&(process.stdout.write(Q(i)),!await je("Some entry functions are missing ensure_latest_version. Proceed with upgrade anyway?"))){console.log(fn.red("Upgrade cancelled.")),h(1);return}let c=o?[o]:void 0;await Ct(s,s.name,e,n,c)}catch(s){B(s),h(1)}h()}},mn=ks;var we=[Tt,Rt,Dt,Nt,mn,Mt,jt,Ut,Vt,Bt,Kt,qt,Qt,Zt,en,nn,pn,gn,Et];import*as yn from"dotenv";yn.config();Es(Ts(process.argv)).scriptName("dubhe").command(we).version(de.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(hn.red(e)),e.includes("Missing required argument")&&console.log(hn.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(B(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
|
|
70
171
|
//# sourceMappingURL=dubhe.js.map
|