@0xobelisk/sui-cli 1.2.0-pre.42 → 1.2.0-pre.44

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 CHANGED
@@ -12,7 +12,7 @@ It comes with
12
12
 
13
13
  ## Installation
14
14
 
15
- We don't recommend installing the CLI globally.
15
+ We dont recommend installing the CLI globally.
16
16
 
17
17
  Instead, you should add the CLI as a dev dependency to your project (done automatically if you start from a starter kit using `pnpm create dubhe`), and use it with `pnpm build` inside your project directory.
18
18
 
package/dist/dubhe.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import jo from"yargs";import{hideBin as Oo}from"yargs/helpers";import tt from"chalk";import{execSync as U,spawn as _e}from"child_process";import $ from"chalk";import nt from"chalk";function J(){console.log(nt.yellow(`
2
+ import xo from"yargs";import{hideBin as Co}from"yargs/helpers";import Ue from"chalk";import{execSync as P,spawn as pe}from"child_process";import p from"chalk";import qe from"chalk";function U(){console.log(qe.yellow(`
3
3
  Welcome to Dubhe
4
4
  --from team@obelisk
5
5
  ________ ___ ___ ________ ___ ___ _______
@@ -10,83 +10,62 @@ Welcome to Dubhe
10
10
  \\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
11
11
  \\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
12
12
 
13
- `))}import{Transaction as ee}from"@0xobelisk/sui-client";import{execSync as bt}from"child_process";import C from"chalk";import*as ie from"fs/promises";import{mkdirSync as lt,writeFileSync as ct}from"fs";import{dirname as dt}from"path";import{SUI_PRIVATE_KEY_PREFIX as ut}from"@mysten/sui/cryptography";import V from"chalk";import{ZodError as st}from"zod";import{fromZodError as rt,ValidationError as at}from"zod-validation-error";var re=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},E=class extends Error{name="DubheCliError"};function N(e){if(e instanceof at)console.log(V.redBright(e.message));else if(e instanceof st){let t=rt(e,{prefixSeparator:`
13
+ `))}import{Transaction as L}from"@0xobelisk/sui-client";import{execSync as nt}from"child_process";import y from"chalk";import*as G from"fs/promises";import{mkdirSync as Ye,writeFileSync as We}from"fs";import{dirname as Je}from"path";import{SUI_PRIVATE_KEY_PREFIX as Ge}from"@mysten/sui/cryptography";import N from"chalk";import{ZodError as Le}from"zod";import{fromZodError as He,ValidationError as Be}from"zod-validation-error";var W=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},v=class extends Error{name="DubheCliError"};function _(e){if(e instanceof Be)console.log(N.redBright(e.message));else if(e instanceof Le){let t=He(e,{prefixSeparator:`
14
14
  - `,issueSeparator:`
15
- - `});console.log(V.redBright(t.message))}else e instanceof re?(console.log(V.red(e.message)),console.log(""),console.log(V.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof E?console.log(V.red(e)):console.log(e)}import*as R from"fs";import A from"chalk";import{spawn as he}from"child_process";import{Dubhe as pt,loadMetadata as gt}from"@0xobelisk/sui-client";var L={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.42",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",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",publishConfig:{access:"public"},engines:{node:">=18"},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",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",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",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","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":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.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"}};function le(e){if(e.startsWith(ut))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 ce(e,t){try{let o=await ie.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch(o){throw new Error(`read .history/sui_${t}/latest.json failed. ${o}`)}}async function X(e,t){try{let o=await ie.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function Z(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await X(o,"mainnet");case"testnet":return await X(o,"testnet");case"devnet":return await X(o,"devnet");case"localnet":return await X(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function ye(e,t){return(await ce(e,t)).packageId}async function de(e,t,o,n,s,r,i){let c={projectName:e,network:t,packageId:o,dappHub:n,components:i,upgradeCap:s,version:r},d=process.cwd(),u=JSON.stringify(c,null,2);await ae(u,`${d}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function B(e,t,o){let n=process.cwd();try{let s=await gt(t,o);if(s){let r=JSON.stringify(s,null,2);await ae(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await ae(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(A.yellow(`Warning: Failed to save metadata: ${s}`))}}async function ae(e,t,o){lt(dt(t),{recursive:!0}),ct(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function mt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${L.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${L.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function Q(e,t){let o=R.readFileSync(e,"utf-8"),n=mt(t),s=o.replace(/Dubhe = \{.*\}/,n);R.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function ft(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 ht(e){let 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/"},o=t[e];if(!await ft(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,r)=>{let i="",c="",d=he("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",u=>{c+=u.toString()}),d.stderr.on("data",u=>{i+=u.toString()}),d.on("error",u=>{console.error(A.red(`
16
- \u274C Failed to execute sui command: ${u.message}`)),r(new Error(`Failed to execute sui command: ${u.message}`))}),d.on("exit",u=>{if(i.includes("already exists")||c.includes("already exists")){console.log(A.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(u===0)console.log(A.green(`Successfully added environment ${e}`)),s();else{let h=i||c||`Process exited with code ${u}`;console.error(A.red(`
17
- \u274C Failed to add environment ${e}`)),console.error(A.red(` \u2514\u2500 ${h.trim()}`)),r(new Error(h))}})})}async function H(e){try{return await ht(e),new Promise((t,o)=>{let n="",s="",r=he("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{n+=i.toString()}),r.on("error",i=>{console.error(A.red(`
18
- \u274C Failed to execute sui command: ${i.message}`)),o(new Error(`Failed to execute sui command: ${i.message}`))}),r.on("exit",i=>{if(i===0)console.log(A.green(`Successfully switched to environment ${e}`)),t();else{let c=n||s||`Process exited with code ${i}`;console.error(A.red(`
19
- \u274C Failed to switch to environment ${e}`)),console.error(A.red(` \u2514\u2500 ${c.trim()}`)),o(new Error(c))}})})}catch(t){throw t}}var j=e=>new Promise(t=>setTimeout(t,e));function yt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new E(`Missing private key environment variable.
15
+ - `});console.log(N.redBright(t.message))}else e instanceof W?(console.log(N.red(e.message)),console.log(""),console.log(N.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof v?console.log(N.red(e)):console.log(e)}import*as D from"fs";import x from"chalk";import{spawn as ne}from"child_process";import{Dubhe as Xe,loadMetadata as Ze}from"@0xobelisk/sui-client";var M={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.44",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",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",publishConfig:{access:"public"},engines:{node:">=18"},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",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.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"}};function X(e){if(e.startsWith(Ge))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 Z(e,t){try{let o=await G.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch(o){throw new Error(`read .history/sui_${t}/latest.json failed. ${o}`)}}async function V(e,t){try{let o=await G.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function K(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await V(o,"mainnet");case"testnet":return await V(o,"testnet");case"devnet":return await V(o,"devnet");case"localnet":return await V(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function se(e,t){return(await Z(e,t)).packageId}async function Q(e,t,o,n,s,r,i){let a={projectName:e,network:t,packageId:o,dappHub:n,components:i,upgradeCap:s,version:r},l=process.cwd(),c=JSON.stringify(a,null,2);await J(c,`${l}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function O(e,t,o){let n=process.cwd();try{let s=await Ze(t,o);if(s){let r=JSON.stringify(s,null,2);await J(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await J(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(x.yellow(`Warning: Failed to save metadata: ${s}`))}}async function J(e,t,o){Ye(Je(t),{recursive:!0}),We(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Qe(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${M.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${M.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function q(e,t){let o=D.readFileSync(e,"utf-8"),n=Qe(t),s=o.replace(/Dubhe = \{.*\}/,n);D.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function et(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 tt(e){let 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/"},o=t[e];if(!await et(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,r)=>{let i="",a="",l=ne("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});l.stdout.on("data",c=>{a+=c.toString()}),l.stderr.on("data",c=>{i+=c.toString()}),l.on("error",c=>{console.error(x.red(`
16
+ \u274C Failed to execute sui command: ${c.message}`)),r(new Error(`Failed to execute sui command: ${c.message}`))}),l.on("exit",c=>{if(i.includes("already exists")||a.includes("already exists")){console.log(x.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(c===0)console.log(x.green(`Successfully added environment ${e}`)),s();else{let g=i||a||`Process exited with code ${c}`;console.error(x.red(`
17
+ \u274C Failed to add environment ${e}`)),console.error(x.red(` \u2514\u2500 ${g.trim()}`)),r(new Error(g))}})})}async function I(e){try{return await tt(e),new Promise((t,o)=>{let n="",s="",r=ne("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{n+=i.toString()}),r.on("error",i=>{console.error(x.red(`
18
+ \u274C Failed to execute sui command: ${i.message}`)),o(new Error(`Failed to execute sui command: ${i.message}`))}),r.on("exit",i=>{if(i===0)console.log(x.green(`Successfully switched to environment ${e}`)),t();else{let a=n||s||`Process exited with code ${i}`;console.error(x.red(`
19
+ \u274C Failed to switch to environment ${e}`)),console.error(x.red(` \u2514\u2500 ${a.trim()}`)),o(new Error(a))}})})}catch(t){throw t}}var E=e=>new Promise(t=>setTimeout(t,e));function ot(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new v(`Missing private key environment variable.
20
20
  Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
21
21
  or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
22
- in your contracts directory to use the default sui private key.`);let t=le(e);if(t===!1)throw new E("Please check your privateKey.");return t}function F({network:e,packageId:t,metadata:o}){let n=yt();return new pt({networkType:e,secretKey:n,packageId:t,metadata:o})}function be(e){let t=Object.entries(e.components).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{entity_id:"address"},{value:r}],keys:["entity_id"]}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"]}};let i=r.fields||{},c=r.keys||["entity_id"];return!i.entity_id&&c.includes("entity_id")&&(i.entity_id="address"),{[s]:{fields:Object.entries(i).map(([d,u])=>({[d]:u})),keys:c}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[]}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[]}};let i=r.fields||{},c=r.keys||[];return{[s]:{fields:Object.entries(i).map(([d,u])=>({[d]:u})),keys:c}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((c,d)=>c.localeCompare(d)).map((c,d)=>({[d]:c}));return{[s]:{fields:i}}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function ue(e,t){let o=`${e}/Move.toml`,s=R.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);R.writeFileSync(o,s,"utf-8")}import*as T from"fs";import*as we from"path";async function ve(e,t){if(!T.existsSync(e))return;let o=T.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");T.writeFileSync(e,s,"utf-8")}function xe(e,t,o,n,s){let r=we.resolve(e),i=T.readFileSync(r,"utf-8"),c=i.split(`
23
- `),d=c.findIndex(y=>y.trim()===`[env.${t}]`),u={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(d===-1)if(o==="publish")u.originalPublishedId=s,u.latestPublishedId=s,u.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let y=d+1;y<c.length;y++){let v=c[y].trim();if(v.startsWith("["))break;let[_,p]=v.split("=").map(l=>l.trim().replace(/"/g,""));switch(_){case"original-published-id":u.originalPublishedId=p;break;case"latest-published-id":u.latestPublishedId=p;break;case"published-version":u.publishedVersion=parseInt(p,10);break}}o==="publish"?(u.originalPublishedId=s,u.latestPublishedId=s,u.publishedVersion=1):o==="upgrade"&&(u.latestPublishedId=s,u.publishedVersion+=1)}let h=`
22
+ in your contracts directory to use the default sui private key.`);let t=X(e);if(t===!1)throw new v("Please check your privateKey.");return t}function $({network:e,packageId:t,metadata:o}){let n=ot();return new Xe({networkType:e,secretKey:n,packageId:t,metadata:o})}function re(e){let t=Object.entries(e.components).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{entity_id:"address"},{value:r}],keys:["entity_id"]}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"]}};let i=r.fields||{},a=r.keys||["entity_id"];return!i.entity_id&&a.includes("entity_id")&&(i.entity_id="address"),{[s]:{fields:Object.entries(i).map(([l,c])=>({[l]:c})),keys:a}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[]}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[]}};let i=r.fields||{},a=r.keys||[];return{[s]:{fields:Object.entries(i).map(([l,c])=>({[l]:c})),keys:a}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((a,l)=>a.localeCompare(l)).map((a,l)=>({[l]:a}));return{[s]:{fields:i}}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function ee(e,t){let o=`${e}/Move.toml`,s=D.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);D.writeFileSync(o,s,"utf-8")}import*as k from"fs";import*as ie from"path";async function ae(e,t){if(!k.existsSync(e))return;let o=k.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");k.writeFileSync(e,s,"utf-8")}function ce(e,t,o,n,s){let r=ie.resolve(e),i=k.readFileSync(r,"utf-8"),a=i.split(`
23
+ `),l=a.findIndex(d=>d.trim()===`[env.${t}]`),c={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(l===-1)if(o==="publish")c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let d=l+1;d<a.length;d++){let b=a[d].trim();if(b.startsWith("["))break;let[C,w]=b.split("=").map(S=>S.trim().replace(/"/g,""));switch(C){case"original-published-id":c.originalPublishedId=w;break;case"latest-published-id":c.latestPublishedId=w;break;case"published-version":c.publishedVersion=parseInt(w,10);break}}o==="publish"?(c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1):o==="upgrade"&&(c.latestPublishedId=s,c.publishedVersion+=1)}let g=`
24
24
  [env.${t}]
25
- chain-id = "${u.chainId}"
26
- original-published-id = "${u.originalPublishedId}"
27
- latest-published-id = "${u.latestPublishedId}"
28
- published-version = "${u.publishedVersion}"
29
- `,f=d===-1?i+h:c.slice(0,d).join(`
30
- `)+h;T.writeFileSync(r,f,"utf-8")}function $e(e){let t,o;try{let n=JSON.parse(bt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(C.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function ke(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.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(C.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function wt(e,t,o,n,s){console.log(`
31
- \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let r=await ke(e);console.log(" \u251C\u2500 Validating Environment..."),await ve(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
- \u{1F4E6} Building Contract...`);let[i,c]=$e(n);console.log(`
33
- \u{1F504} Publishing Contract...`);let d=new ee;s&&d.setGasBudget(s);let[u]=d.publish({modules:i,dependencies:c});d.transferObjects([u],e.getAddress());let h;try{h=await e.signAndSendTxn({tx:d})}catch(m){console.error(C.red(" \u2514\u2500 Publication failed")),console.error(m.message),process.exit(1)}(!h||h.effects?.status.status==="failure")&&(console.log(C.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let f=1,y="",v="",_=t.components,p="",l=[];h.objectChanges.map(m=>{m.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${m.packageId}`),y=m.packageId||""),m.type==="created"&&m.objectType&&m.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${m.objectId}`),p=m.objectId||""),m.type==="created"&&m.objectType&&m.objectType.includes("dapp_hub::DappHub")&&(v=m.objectId||""),m.type==="created"&&l.push(m)}),console.log(` \u2514\u2500 Transaction: ${h.digest}`),xe(`${n}/Move.lock`,o,"publish",r,y),console.log(`
34
- \u26A1 Executing Deploy Hook...`),await j(5e3);let g=new ee,x=[],b=t.name==="dubhe"?v:await Z(o);x.push(g.object(b)),x.push(g.object("0x6")),g.moveCall({target:`${y}::genesis::run`,arguments:x});let S;try{S=await e.signAndSendTxn({tx:g})}catch(m){console.error(C.red(" \u2514\u2500 Deploy hook execution failed")),console.error(m.message),process.exit(1)}if(S.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${S.digest}`),console.log(`
35
- \u{1F4CB} Created Objects:`),l.map(k=>{console.log(` \u251C\u2500 Type: ${k.objectType}`),console.log(` \u2514\u2500 ID: ${k.objectId}`)}),await de(t.name,o,y,v,p,f,_),await B(t.name,o,y);let m=JSON.parse(T.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));m.package_id=y,T.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(m,null,2)),console.log(`
25
+ chain-id = "${c.chainId}"
26
+ original-published-id = "${c.originalPublishedId}"
27
+ latest-published-id = "${c.latestPublishedId}"
28
+ published-version = "${c.publishedVersion}"
29
+ `,u=l===-1?i+g:a.slice(0,l).join(`
30
+ `)+g;k.writeFileSync(r,u,"utf-8")}function le(e){let t,o;try{let n=JSON.parse(nt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(y.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function de(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.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(y.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function st(e,t,o,n,s){console.log(`
31
+ \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let r=await de(e);console.log(" \u251C\u2500 Validating Environment..."),await ae(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
+ \u{1F4E6} Building Contract...`);let[i,a]=le(n);console.log(`
33
+ \u{1F504} Publishing Contract...`);let l=new L;s&&l.setGasBudget(s);let[c]=l.publish({modules:i,dependencies:a});l.transferObjects([c],e.getAddress());let g;try{g=await e.signAndSendTxn({tx:l})}catch(m){console.error(y.red(" \u2514\u2500 Publication failed")),console.error(m.message),process.exit(1)}(!g||g.effects?.status.status==="failure")&&(console.log(y.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let u=1,d="",b="",C=t.components,w="",S=[];g.objectChanges.map(m=>{m.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${m.packageId}`),d=m.packageId||""),m.type==="created"&&m.objectType&&m.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${m.objectId}`),w=m.objectId||""),m.type==="created"&&m.objectType&&m.objectType.includes("dapp_hub::DappHub")&&(b=m.objectId||""),m.type==="created"&&S.push(m)}),console.log(` \u2514\u2500 Transaction: ${g.digest}`),ce(`${n}/Move.lock`,o,"publish",r,d),console.log(`
34
+ \u26A1 Executing Deploy Hook...`),await E(5e3);let h=new L,Y=[],Ke=t.name==="dubhe"?b:await K(o);Y.push(h.object(Ke)),Y.push(h.object("0x6")),h.moveCall({target:`${d}::genesis::run`,arguments:Y});let A;try{A=await e.signAndSendTxn({tx:h})}catch(m){console.error(y.red(" \u2514\u2500 Deploy hook execution failed")),console.error(m.message),process.exit(1)}if(A.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${A.digest}`),console.log(`
35
+ \u{1F4CB} Created Objects:`),S.map(oe=>{console.log(` \u251C\u2500 Type: ${oe.objectType}`),console.log(` \u2514\u2500 ID: ${oe.objectId}`)}),await Q(t.name,o,d,b,w,u,C),await O(t.name,o,d);let m=JSON.parse(k.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));m.package_id=d,k.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(m,null,2)),console.log(`
36
36
  \u2705 Contract Publication Complete
37
- `)}else console.log(C.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(C.yellow(" Please republish or manually call deploy_hook::run")),console.log(C.yellow(" Please check the transaction digest:")),console.log(C.yellow(` ${S.digest}`)),process.exit(1)}async function vt(e){return T.existsSync(e)?!0:(console.log(C.yellow(`
38
- \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(C.yellow(" \u251C\u2500 Expected Path:"),e),console.log(C.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(C.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(C.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(C.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(C.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function xt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await vt(n))return;console.log(`
39
- \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await ke(e);await ve(`${n}/Move.lock`,t),await ue(n,"0x0");let[r,i]=$e(n),c=new ee,[d]=c.publish({modules:r,dependencies:i});c.transferObjects([d],e.getAddress());let u;try{u=await e.signAndSendTxn({tx:c})}catch(g){console.error(C.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}(!u||u.effects?.status.status==="failure")&&(console.log(C.red(" \u2514\u2500 Publication failed")),process.exit(1));let h=1,f="",y="",v={},_="";u.objectChanges.map(g=>{g.type==="published"&&(f=g.packageId||""),g.type==="created"&&g.objectType&&g.objectType==="0x2::package::UpgradeCap"&&(_=g.objectId||""),g.type==="created"&&g.objectType&&g.objectType.includes("dapp_hub::DappHub")&&(y=g.objectId||"")}),await j(3e3);let p=new ee;p.moveCall({target:`${f}::dubhe_genesis::run`,arguments:[p.object(y),p.object("0x6")]});let l;try{l=await e.signAndSendTxn({tx:p})}catch(g){console.error(C.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}if(l.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await ue(n,f),await de("dubhe",t,f,y,_,h,v),xe(`${n}/Move.lock`,t,"publish",s,f)}async function Ce(e,t,o){await H(t);let n=F({network:t}),r=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await xt(n,t),e.name!=="dubhe"&&await Q(`${r}/Move.toml`,t),await wt(n,e,t,r,o)}import{Dubhe as $t}from"@0xobelisk/sui-client";import*as te from"fs";function kt(){console.log($.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{U("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let o of t)try{let n=U(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
- `).filter(r=>r);console.log($.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{U(`kill -TERM ${r}`,{stdio:"ignore"}),console.log($.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{U(`kill -KILL ${r}`,{stdio:"ignore"}),console.log($.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log($.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?$.green(" \u2514\u2500 Local Node stopped successfully"):$.gray(" \u2514\u2500 No running Local Node found"))}function Ct(e){try{te.existsSync(e)?(console.log($.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),te.rmSync(e,{recursive:!0,force:!0}),console.log($.green(" \u2514\u2500 Directory removed successfully"))):console.log($.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error($.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function _t(){try{if(process.platform==="win32")return U('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 o=U(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function St(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new $t({secretKey:t}).getSigner();_e("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 #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log($.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log($.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Pt(e){let t=()=>{console.log($.yellow(`
41
- \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Se(e,t){if(t)console.log($.cyan(`
42
- \u{1F504} Force mode enabled`)),kt(),console.log($.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await j(3e3),Ct(e),console.log("");else if(_t()){console.log($.yellow(`
43
- \u26A0\uFE0F Warning: Local Node Already Running`)),console.log($.yellow(" \u251C\u2500 Cannot start a new instance")),console.log($.yellow(" \u2514\u2500 Please stop the existing process first"));return}J(),console.log("\u{1F680} Starting Local Node...");let o=null;try{if(o=_e("sui",["start","--with-faucet","--force-regenesis","--data-ingestion-dir",e],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",s=>{console.error($.red(`
44
- \u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${s.message}`))}),await j(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await St(),await j(2e3),le("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new E("Please check your privateKey.");console.log($.green("\u{1F389} Local environment is ready!")),Pt(o),await new Promise(s=>{o?.on("exit",()=>s())})}catch(n){console.error($.red(`
45
- \u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var Dt={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 Se(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},Pe=Dt;import{requestSuiFromFaucetV0 as Et,getFaucetHost as Tt}from"@mysten/sui/faucet";import{SuiClient as It,getFullnodeUrl as At}from"@mysten/sui/client";var pe=60,Nt=1e3,De=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ft={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",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=F(e).getAddress():o=t,console.log(`
46
- \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 n=0,s=!1,r=0,i=Date.now(),c=!1,d=()=>{c=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
47
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",d);try{for(;n<pe&&!s&&!c;)try{await Et({host:Tt(e),recipient:o}),s=!0}catch{if(c)break;n++,n===pe&&(console.log(` \u2514\u2500 Failed to request funds after ${pe} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let v=Math.floor((Date.now()-i)/1e3),_=De[r%De.length];r++,process.stdout.write(`\r \u251C\u2500 ${_} Retrying... (${v}s)`),await new Promise(p=>setTimeout(p,Nt))}}finally{process.removeListener("SIGINT",d)}c&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let u=new It({url:At(e)}),h={owner:o},f=await u.getBalance(h);console.log(`
48
- \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(f.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
37
+ `)}else console.log(y.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(y.yellow(" Please republish or manually call deploy_hook::run")),console.log(y.yellow(" Please check the transaction digest:")),console.log(y.yellow(` ${A.digest}`)),process.exit(1)}async function rt(e){return k.existsSync(e)?!0:(console.log(y.yellow(`
38
+ \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(y.yellow(" \u251C\u2500 Expected Path:"),e),console.log(y.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(y.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(y.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(y.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(y.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function it(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await rt(n))return;console.log(`
39
+ \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await de(e);await ae(`${n}/Move.lock`,t),await ee(n,"0x0");let[r,i]=le(n),a=new L,[l]=a.publish({modules:r,dependencies:i});a.transferObjects([l],e.getAddress());let c;try{c=await e.signAndSendTxn({tx:a})}catch(h){console.error(y.red(" \u2514\u2500 Publication failed")),console.error(h.message),process.exit(1)}(!c||c.effects?.status.status==="failure")&&(console.log(y.red(" \u2514\u2500 Publication failed")),process.exit(1));let g=1,u="",d="",b={},C="";c.objectChanges.map(h=>{h.type==="published"&&(u=h.packageId||""),h.type==="created"&&h.objectType&&h.objectType==="0x2::package::UpgradeCap"&&(C=h.objectId||""),h.type==="created"&&h.objectType&&h.objectType.includes("dapp_hub::DappHub")&&(d=h.objectId||"")}),await E(3e3);let w=new L;w.moveCall({target:`${u}::dubhe_genesis::run`,arguments:[w.object(d),w.object("0x6")]});let S;try{S=await e.signAndSendTxn({tx:w})}catch(h){console.error(y.red(" \u2514\u2500 Deploy hook execution failed")),console.error(h.message),process.exit(1)}if(S.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await ee(n,u),await Q("dubhe",t,u,d,C,g,b),ce(`${n}/Move.lock`,t,"publish",s,u)}async function ue(e,t,o){await I(t);let n=$({network:t}),r=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await it(n,t),e.name!=="dubhe"&&await q(`${r}/Move.toml`,t),await st(n,e,t,r,o)}import{Dubhe as at}from"@0xobelisk/sui-client";import*as H from"fs";function ct(){console.log(p.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{P("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let o of t)try{let n=P(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
+ `).filter(r=>r);console.log(p.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{P(`kill -TERM ${r}`,{stdio:"ignore"}),console.log(p.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{P(`kill -KILL ${r}`,{stdio:"ignore"}),console.log(p.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log(p.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?p.green(" \u2514\u2500 Local Node stopped successfully"):p.gray(" \u2514\u2500 No running Local Node found"))}function lt(e){try{H.existsSync(e)?(console.log(p.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),H.rmSync(e,{recursive:!0,force:!0}),console.log(p.green(" \u2514\u2500 Directory removed successfully"))):console.log(p.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(p.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function dt(){try{if(process.platform==="win32")return P('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 o=P(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function ut(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new at({secretKey:t}).getSigner();pe("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 #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(p.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(p.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function pt(e){let t=()=>{console.log(p.yellow(`
41
+ \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function me(e,t){if(t)console.log(p.cyan(`
42
+ \u{1F504} Force mode enabled`)),ct(),console.log(p.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await E(3e3),lt(e),console.log("");else if(dt()){console.log(p.yellow(`
43
+ \u26A0\uFE0F Warning: Local Node Already Running`)),console.log(p.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(p.yellow(" \u2514\u2500 Please stop the existing process first"));return}U(),console.log("\u{1F680} Starting Local Node...");let o=null;try{if(o=pe("sui",["start","--with-faucet","--force-regenesis","--data-ingestion-dir",e],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",s=>{console.error(p.red(`
44
+ \u274C Failed to Start Local Node`)),console.error(p.red(` \u2514\u2500 Error: ${s.message}`))}),await E(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await ut(),await E(2e3),X("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new v("Please check your privateKey.");console.log(p.green("\u{1F389} Local environment is ready!")),pt(o),await new Promise(s=>{o?.on("exit",()=>s())})}catch(n){console.error(p.red(`
45
+ \u274C Failed to Start Local Node`)),console.error(p.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var mt={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 me(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},ge=mt;import{requestSuiFromFaucetV0 as gt,getFaucetHost as ft}from"@mysten/sui/faucet";import{SuiClient as ht,getFullnodeUrl as yt}from"@mysten/sui/client";var te=60,bt=1e3,fe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],wt={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",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=$(e).getAddress():o=t,console.log(`
46
+ \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 n=0,s=!1,r=0,i=Date.now(),a=!1,l=()=>{a=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
47
+ \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",l);try{for(;n<te&&!s&&!a;)try{await gt({host:ft(e),recipient:o}),s=!0}catch{if(a)break;n++,n===te&&(console.log(` \u2514\u2500 Failed to request funds after ${te} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let b=Math.floor((Date.now()-i)/1e3),C=fe[r%fe.length];r++,process.stdout.write(`\r \u251C\u2500 ${C} Retrying... (${b}s)`),await new Promise(w=>setTimeout(w,bt))}}finally{process.removeListener("SIGINT",l)}a&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let c=new ht({url:yt(e)}),g={owner:o},u=await c.getBalance(g);console.log(`
48
+ \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(u.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
49
49
  \u2705 Faucet Operation Complete
50
- `),process.exit(0)}},Ee=Ft;import{schemaGen as Mt,loadConfig as jt}from"@0xobelisk/sui-common";import Ot from"chalk";import Rt from"node:path";var Ht={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await jt(e),n=Rt.dirname(e);await Mt(n,o,t),process.exit(0)}catch(o){console.log(Ot.red("Schemagen failed!")),console.error(o.message)}}},Te=Ht;import{loadConfig as Ut}from"@0xobelisk/sui-common";import{execSync as zt}from"child_process";var Vt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",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}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await Ut(t);zt(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Ce(n,e,o)}catch(n){N(n),process.exit(1)}process.exit(0)}},Ie=Vt;import{execSync as Lt}from"child_process";import{loadConfig as Bt}from"@0xobelisk/sui-common";var qt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Bt(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Lt(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Ae=qt;import{execSync as Wt,exec as Kt}from"child_process";import Gt from"chalk";import{loadConfig as Yt}from"@0xobelisk/sui-common";var Jt={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await Yt(e),r=`${process.cwd()}/src/${n.name}`;await H(t),await Q(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,c=Wt(i,{encoding:"utf-8"});console.log(c),Kt(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(Gt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Ne=Jt;var Xt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){J()}},Fe=Xt;import{Dubhe as Me}from"@0xobelisk/sui-client";import*as W from"fs";import q from"chalk";async function je(e=!1,t=!1){t&&(console.log(q.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(q.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
- `)));let o=process.cwd(),n,s="";try{s=W.readFileSync(`${o}/.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(`
52
- `),d=!1;for(let f=c.length-1;f>=0;f--){let y=c[f];if(y.endsWith(r)){let[v]=y.split("=");t?d=v==="PRIVATE_KEY":d=v==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(d){for(let f=c.length-1;f>=0;f--)if(c[f].endsWith(r)){let v=`${i}=${r}`;c[f]=v,s=c.join(`
53
- `),W.writeFileSync(`${o}/.env`,s);break}}let h=new Me({secretKey:r}).getSigner();console.log(q.blue(`Using existing account: ${h.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new Me().getSigner();n=i.getSecretKey();let d=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
- `+d:s=d,W.writeFileSync(`${o}/.env`,s),console.log(q.green(`File created/updated at: ${o}/.env`)),console.log(q.blue(`New account generated: ${i.toSuiAddress()}`))}}var Zt={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 je(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Oe=Zt;import Qt from"chalk";import eo from"dotenv";eo.config();async function Re(e){try{let o=await F({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new E("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(Qt.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new E("Failed to check balance: "+t)}}var to={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 Re(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},He=to;import{mkdirSync as oo,writeFileSync as no}from"fs";import{dirname as so}from"path";async function ro(e,t,o){let n=await Z(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
50
+ `),process.exit(0)}},he=wt;import{schemaGen as vt,loadConfig as kt}from"@0xobelisk/sui-common";import xt from"chalk";import Ct from"node:path";var _t={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await kt(e),n=Ct.dirname(e);await vt(n,o,t),process.exit(0)}catch(o){console.log(xt.red("Schemagen failed!")),console.error(o.message)}}},ye=_t;import{loadConfig as $t}from"@0xobelisk/sui-common";import{execSync as St}from"child_process";var Et={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",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}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await $t(t);St(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await ue(n,e,o)}catch(n){_(n),process.exit(1)}process.exit(0)}},be=Et;import{execSync as Dt}from"child_process";import{loadConfig as It}from"@0xobelisk/sui-common";var Pt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await It(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Dt(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},we=Pt;import{execSync as Tt,exec as Nt}from"child_process";import Mt from"chalk";import{loadConfig as Ot}from"@0xobelisk/sui-common";var jt={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await Ot(e),r=`${process.cwd()}/src/${n.name}`;await I(t),await q(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,a=Tt(i,{encoding:"utf-8"});console.log(a),Nt(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(Mt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},ve=jt;var Rt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){U()}},ke=Rt;import{Dubhe as xe}from"@0xobelisk/sui-client";import*as R from"fs";import j from"chalk";async function Ce(e=!1,t=!1){t&&(console.log(j.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(j.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
+ `)));let o=process.cwd(),n,s="";try{s=R.readFileSync(`${o}/.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",a=s.split(`
52
+ `),l=!1;for(let u=a.length-1;u>=0;u--){let d=a[u];if(d.endsWith(r)){let[b]=d.split("=");t?l=b==="PRIVATE_KEY":l=b==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(l){for(let u=a.length-1;u>=0;u--)if(a[u].endsWith(r)){let b=`${i}=${r}`;a[u]=b,s=a.join(`
53
+ `),R.writeFileSync(`${o}/.env`,s);break}}let g=new xe({secretKey:r}).getSigner();console.log(j.blue(`Using existing account: ${g.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new xe().getSigner();n=i.getSecretKey();let l=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
+ `+l:s=l,R.writeFileSync(`${o}/.env`,s),console.log(j.green(`File created/updated at: ${o}/.env`)),console.log(j.blue(`New account generated: ${i.toSuiAddress()}`))}}var Ft={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 Ce(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},_e=Ft;import At from"chalk";import Ut from"dotenv";Ut.config();async function $e(e){try{let o=await $({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(At.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var Vt={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 $e(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Se=Vt;import{mkdirSync as Kt,writeFileSync as qt}from"fs";import{dirname as Lt}from"path";async function Ht(e,t,o){let n=await K(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
55
55
 
56
56
  export const NETWORK: NetworkType = '${e}';
57
57
  export const PACKAGE_ID = '${t}';
58
58
  export const DUBHE_SCHEMA_ID = '${n}';
59
- `;ao(s,o,"storeConfig")}async function ao(e,t,o){oo(so(t),{recursive:!0}),no(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Ue(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await ce(s,t);await ro(r.network,r.packageId,o)}import{loadConfig as io}from"@0xobelisk/sui-common";var lo={command:"config-store",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"],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":o}){try{let n=await io(e);await Ue(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},ze=lo;import co from"chokidar";import{exec as uo}from"child_process";var po={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{uo("pnpm dubhe schemagen",(n,s,r)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(r){console.error(`schemagen stderr: ${r}`);return}console.log(`schemagen stdout: ${s}`)})},o=co.watch(e,{persistent:!0});o.on("change",n=>{console.log(`${n} has been changed. Running schemagen...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{o.close(),console.log(`
60
- Watch stopped.`),process.exit()})}},Ve=po;import go from"wait-on";import mo from"ora";import oe from"chalk";var fo={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=mo({text:`Waiting for service to start ${oe.cyan(t.url)}...`,color:"cyan"});o.start();try{await go({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(oe.green("Service is ready!")),process.exit(0)}catch{o.fail(oe.red("Timeout waiting for service")),console.error(oe.yellow("Please make sure the service is running...")),process.exit(1)}}},Le=fo;var ho={command:"switch-env",describe:"Switch environment",builder(e){return e.option("network",{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"})},async handler(e){await H(e.network)}},Be=ho;import yo from"dotenv";import z from"chalk";yo.config();var bo={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=F({network:e}),o=t.getSigner();console.log(z.blue("Account Information:")),console.log(` Network: ${z.green(e)}`),console.log(` Address: ${z.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${z.green(s)} SUI`)}catch{console.log(` Balance: ${z.red("Failed to fetch balance")} ${z.gray("(Network error)")}`)}}catch(t){N(t),process.exit(1)}}},qe=bo;import{loadConfig as wo}from"@0xobelisk/sui-common";async function We(e,t,o){if(o)await B(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await ye(n,t);await B(e.name,t,s)}}var vo={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",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}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await wo(t);await We(n,e,o)}catch(n){N(n),process.exit(1)}process.exit(0)}},Ke=vo;import a from"chalk";import{spawn as xo}from"child_process";import Ge from"cli-table3";import ge from"inquirer";import*as Xe from"cli-progress";import*as w from"fs";import*as P from"path";import*as O from"os";function me(){let e=process.platform,t=process.arch,o,n;switch(e){case"darwin":o="macos";break;case"win32":o="windows";break;case"linux":o="ubuntu";break;default:o=e}switch(t){case"x64":n="x86_64";break;case"arm64":n="aarch64";break;default:n=t}return{platform:e,arch:t,platformForAsset:o,archForAsset:n}}var D={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:P.join(O.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe-wip",binaryName:"dubhe-indexer",installDir:P.join(O.homedir(),".dubhe","bin")}};async function M(e,t=[]){return new Promise(o=>{let n=xo(e,t,{shell:!0}),s="",r="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{r+=i.toString()}),n.on("close",i=>{o({code:i||0,stdout:s,stderr:r})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:r})})})}async function $o(e,t){let o=await fetch(e,{headers:{"User-Agent":"dubhe-cli"}});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let n=o.headers.get("content-length"),s=n?parseInt(n):0,r=new Xe.SingleBar({format:a.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});s>0?r.start(Math.round(s/1024/1024*100)/100,0,{speed:"0.00"}):console.log(a.blue("\u{1F4E5} Downloading... (unable to get file size)"));let i=o.body?.getReader();if(!i)throw new Error("Unable to get response stream");let c=[],d=0,u=Date.now();try{for(;;){let{done:l,value:g}=await i.read();if(l)break;if(c.push(g),d+=g.length,s>0){let x=Math.round(d/1024/1024*100)/100,b=(Date.now()-u)/1e3,S=b>0?Math.round(x/b*100)/100:0;r.update(x,{speed:S.toFixed(2)})}}let h=c.reduce((l,g)=>l+g.length,0),f=new Uint8Array(h),y=0;for(let l of c)f.set(l,y),y+=l.length;w.writeFileSync(t,f),s>0&&r.stop();let v=Math.round(d/1024/1024*100)/100,_=(Date.now()-u)/1e3,p=_>0?Math.round(v/_*100)/100:0;console.log(a.green(`\u2713 Download completed! ${v} MB, average speed: ${p} MB/s`))}catch(h){throw s>0&&r.stop(),h}}async function fe(e,t=10,o=3){let n=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=o;s++)try{s>1&&console.log(a.gray(` Retry ${s}/${o}...`));let r=await fetch(n,{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(a.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${r instanceof Error?r.message:String(r)}`)),s===o)return console.error(a.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(i=>setTimeout(i,1e3*s))}return[]}function G(e,t){return e.assets.filter(n=>{let s=n.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(h=>s.includes(h)),d=i.some(h=>s.includes(h)),u=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return c&&d&&u}).map(n=>n.name)}async function ko(e,t){let o=D[e];return o?(await fe(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:G(s,t).length>0})):[]}async function Co(e){try{let t=Y();if(!t){console.log(a.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:o,configFile:n}=t,s=o==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(w.existsSync(n)&&w.readFileSync(n,"utf8").includes(e)){console.log(a.green(` \u2713 PATH already configured in ${n}`));return}let i=`# Added by dubhe doctor
61
- ${s}`;w.appendFileSync(n,`
62
- ${i}
63
- `),console.log(a.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(a.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(a.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(a.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function Y(){let e=O.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:P.join(e,".zshrc")};if(t.includes("bash")){let n=P.join(e,".bash_profile"),s=P.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&w.existsSync(n)?n:s}}else if(t.includes("fish")){let n=P.join(e,".config","fish");return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:P.join(n,"config.fish")}}}let o=[{name:"zsh",file:P.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?P.join(e,".bash_profile"):P.join(e,".bashrc")},{name:"bash",file:P.join(e,".bashrc")}];for(let n of o)if(w.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||w.existsSync("/bin/zsh")?{shellName:"zsh",configFile:P.join(e,".zshrc")}:null}async function Ye(e,t){let o=D[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=me();console.log(a.gray(` System: ${n.platform}/${n.arch}`));try{console.log(a.gray(" Fetching release information..."));let s=await fe(o.repo,10);if(s.length===0)return console.error(a.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let r=null;if(t){if(r=s.find(l=>l.tag_name===t)||null,!r)return console.error(`Version ${t} not found`),!1}else for(let l of s)if(G(l,n).length>0){r=l;break}if(!r)return console.error("No compatible version found"),!1;let i=G(r,n);if(i.length===0)return console.error(`Version ${r.tag_name} has no compatible binaries`),!1;let c=i[0],d=r.assets.find(l=>l.name===c);if(!d)return console.error(`Asset file not found: ${c}`),!1;console.log(a.green(` \u2713 Found compatible version: ${r.tag_name}`)),console.log(a.gray(` Download file: ${d.name}`));try{let l=await fetch(d.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(a.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let g=l.headers.get("content-length");g&&console.log(a.gray(` File size: ${Math.round(parseInt(g)/1024/1024*100)/100} MB`))}}catch{console.log(a.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}w.existsSync(o.installDir)||(w.mkdirSync(o.installDir,{recursive:!0}),console.log(a.gray(` Created install directory: ${o.installDir}`))),console.log(a.blue(" \u{1F4E5} Downloading..."));let u=P.join(O.tmpdir(),d.name),h=3;for(let l=1;l<=h;l++)try{l>1&&console.log(a.gray(` Attempt ${l} to download...`)),await $o(d.browser_download_url,u);break}catch(g){let x=g instanceof Error?g.message:String(g);if(console.log(a.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${x}`)),l===h)throw new Error(`Download failed after ${h} attempts: ${x}`);console.log(a.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(b=>setTimeout(b,l*2e3))}console.log(a.blue(" \u{1F4E6} Extracting and installing..."));let f=P.join(O.tmpdir(),`extract_${Date.now()}`);if(w.mkdirSync(f,{recursive:!0}),d.name.endsWith(".tar.gz")||d.name.endsWith(".tgz")){let l=await M("tar",["-xzf",u,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.bz2")){let l=await M("tar",["-xjf",u,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.xz")){let l=await M("tar",["-xJf",u,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".zip")){let l=await M("unzip",["-q",u,"-d",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${d.name}`);let y=l=>{let g=w.readdirSync(l,{withFileTypes:!0});for(let x of g){let b=P.join(l,x.name);if(x.isDirectory()){let S=y(b);if(S)return S}else if(x.name===o.binaryName||x.name===`${o.binaryName}.exe`)return b}return null},v=y(f);if(!v)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let _=P.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return w.copyFileSync(v,_),process.platform!=="win32"&&w.chmodSync(_,493),w.rmSync(u,{force:!0}),w.rmSync(f,{recursive:!0,force:!0}),console.log(a.green(" \u2705 Installation completed!")),console.log(a.gray(` Location: ${_}`)),console.log(a.gray(` Version: ${r.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(a.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(a.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await Co(o.installDir)),!0}catch(s){return console.error(a.red(`\u274C Installation failed: ${s}`)),!1}}async function _o(e){let t=me(),o=await ko(e,t);if(o.length===0)return console.log(a.red(`Unable to get version information for ${e}`)),null;let n=o.filter(r=>r.hasCompatibleAsset).slice(0,5);if(n.length===0)return console.log(a.red("No compatible versions found for current system")),null;console.log(a.blue(`
64
- \u{1F4CB} Select version for ${e}`)),console.log(a.gray(`System: ${t.platform}/${t.arch}`)),console.log(a.gray(`Compatible versions (latest 5):
65
- `));let s=n.map((r,i)=>({name:`${r.version} ${i===0?a.green("(latest)"):a.gray("(available)")}`,value:r.version,short:r.version}));try{let r=await ge.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new ge.Separator,{name:a.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return r.version==="cancel"?(console.log(a.gray("Installation cancelled")),null):r.version}catch{return console.log(a.gray(`
66
- Installation cancelled`)),null}}function ne(e){let t=D[e];if(!t)return!1;let o=P.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return w.existsSync(o)}async function K(e,t="--version"){try{let o=await M(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
67
- `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(ne(e)){let n=Y(),s=n?n.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:Je(e)}}}catch{if(ne(e)){let n=Y(),s=n?n.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:Je(e)}}}function Je(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-wip/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function So(){try{let e=await M("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 Po(){try{return(await M("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 Do(){try{let e=await M("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"}}}function Eo(e){let t={success:a.green("\u2713"),warning:a.yellow("!"),error:a.red("\u2717")},o={success:a.green("Pass"),warning:a.yellow("Warning"),error:a.red("Fail")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function To(e){if(console.log(a.bold.blue(`
68
- \u{1F50D} Dubhe Doctor - Development Environment Checker
69
- `)),e.listVersions){let p=e.listVersions;D[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(a.blue(`\u{1F4CB} Available versions for ${p}:`));let l=me();console.log(a.gray(`System: ${l.platform}/${l.arch}
70
- `));let g=D[p],x=await fe(g.repo,10);x.length===0&&(console.log(a.red("Unable to get version information")),process.exit(1));let b=x.map(m=>({version:m.tag_name,hasCompatibleAsset:G(m,l).length>0,publishDate:new Date(m.published_at).toLocaleDateString("en-US")})),S=new Ge({head:[a.bold.cyan("Version"),a.bold.cyan("Compatibility"),a.bold.cyan("Release Date")],colWidths:[30,15,25]});if(b.forEach(m=>{S.push([m.version,m.hasCompatibleAsset?a.green("\u2713 Compatible"):a.red("\u2717 Incompatible"),m.publishDate])}),console.log(S.toString()),e.debug&&b.length>0){console.log(a.blue(`
71
- \u{1F50D} Debug Information:`));let m=b.find(k=>k.hasCompatibleAsset);if(m){let k=x.find(I=>I.tag_name===m.version);if(k){console.log(a.gray(`Latest compatible version: ${m.version}`)),console.log(a.gray("Available asset files:")),k.assets.forEach(se=>{console.log(a.gray(` - ${se.name}`))});let I=G(k,l);console.log(a.gray("Compatible asset files:")),I.forEach(se=>{console.log(a.green(` \u2713 ${se}`))})}}}process.exit(0)}if(console.log(a.gray(`Checking your development environment...
72
- `)),e.install){let p=e.install;D[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),console.log(a.gray(`Supported tools: ${Object.keys(D).join(", ")}`)),process.exit(1));let l=null;e.selectVersion&&(l=await _o(p),l||process.exit(1));let g=await Ye(p,l||void 0);process.exit(g?0:1)}let t=[];console.log(`Running checks...
73
- `);let o=await So();t.push(o);let n=await K("pnpm");t.push(n);let s=await Do();s.status==="error"&&(s.status="warning"),t.push(s);let r=await K("docker");t.push(r);let i=null;r.status==="success"&&(i=await Po(),t.push(i));let c=await K("docker-compose");t.push(c);let d=await K("sui");t.push(d);let u=await K("dubhe-indexer");t.push(u);let h=new Ge({head:[a.bold.cyan("Check Item"),a.bold.cyan("Result"),a.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(Eo(p))}),console.log(h.toString());let f={success:t.filter(p=>p.status==="success").length,warning:t.filter(p=>p.status==="warning").length,error:t.filter(p=>p.status==="error").length};console.log(`
74
- `+a.bold("\u{1F4CA} Check Summary:")),console.log(` ${a.green("\u2713 Passed:")} ${f.success} items`),console.log(` ${a.yellow("! Warning:")} ${f.warning} items`),console.log(` ${a.red("\u2717 Failed:")} ${f.error} items`);let y=t.filter(p=>p.status==="error"),v=y.filter(p=>D[p.name]),_=y.filter(p=>!D[p.name]);if(_.length>0&&(console.log(a.blue(`
75
- \u{1F527} Missing tools that require manual installation:`)),_.forEach(p=>{console.log(` ${a.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),v.length>0){let p=v.filter(g=>ne(g.name)),l=v.filter(g=>!ne(g.name));if(p.length>0){let g=p.map(m=>m.name).join(", "),x=D[p[0].name]?.installDir||"~/.dubhe/bin",b=Y(),S=b?b.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.yellow(`
76
- \u26A0\uFE0F Tools already installed but not in PATH: ${g}`)),console.log(a.gray(` Location: ${x}`)),console.log(a.blue(" To fix this, apply PATH changes:")),console.log(a.green(` source ${S}`)),console.log(a.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(a.gray(` If you want to reinstall, remove the files from ${x} and run dubhe doctor again`))}if(l.length>0){let g=l.map(x=>x.name).join(", ");console.log(a.blue(`
77
- \u{1F680} Auto-installable tools detected: ${g}`));try{if((await ge.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${g})`,default:!0}])).installAll){console.log(a.blue(`
78
- \u{1F4E6} Starting installation of auto-installable tools...
79
- `));let b=[];for(let k of l){console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.blue(`\u{1F4E6} Installing ${k.name}...`)),console.log(a.blue(`${"=".repeat(60)}`));let I=await Ye(k.name);b.push({name:k.name,success:I}),I?console.log(a.green(`
80
- \u2705 ${k.name} installation completed successfully!`)):(console.log(a.red(`
81
- \u274C ${k.name} installation failed`)),console.log(a.gray(` Manual installation: dubhe doctor --install ${k.name}`))),console.log("")}console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.bold("\u{1F4CB} Installation Summary:")),console.log(a.blue(`${"=".repeat(60)}`)),b.forEach(k=>{let I=k.success?a.green("\u2705 Success"):a.red("\u274C Failed");console.log(` ${k.name}: ${I}`)});let S=b.filter(k=>k.success).length,m=b.length-S;if(console.log(`
82
- ${a.green("Successful:")} ${S}/${b.length}`),m>0&&console.log(` ${a.red("Failed:")} ${m}/${b.length}`),S>0){let k=Y(),I=k?k.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.blue(`
83
- \u{1F504} Next Steps:`)),console.log(a.yellow(" 1. Apply PATH changes by running:")),console.log(a.green(` source ${I}`)),console.log(a.yellow(" 2. Or restart your terminal")),console.log(a.yellow(" 3. Then run the doctor check again:")),console.log(a.green(" dubhe doctor")),console.log(a.gray(`
84
- This will verify that all tools are properly configured.`))}else console.log(a.red(`
85
- \u274C All installations failed. Please check the error messages above.`))}else console.log(a.gray(`
86
- Auto-installation skipped. You can install them manually later:`)),l.forEach(b=>{console.log(a.gray(` dubhe doctor --install ${b.name}`))})}catch{console.log(a.gray(`
87
- Installation cancelled. You can install them manually later:`)),l.forEach(b=>{console.log(a.gray(` dubhe doctor --install ${b.name}`))})}}}v.length===0&&(f.error>0?(console.log(a.red(`
88
- \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),process.exit(1)):f.warning>0?console.log(a.yellow(`
89
- \u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(a.green(`
90
- \u2705 Congratulations! Your development environment is fully ready!`))),console.log(a.gray(`
91
- \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var Io={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(D)}).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(D)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await To({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(a.red("Error occurred during check:"),t),process.exit(1)}}},Ze=Io;import Ao from"chalk";import{loadConfig as No}from"@0xobelisk/sui-common";import Fo from"fs";var Mo={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 o=await No(e),n=be(o);Fo.writeFileSync(t,n)}catch(o){console.error(Ao.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},Qe=Mo;var et=[Pe,Ie,Ee,Te,Ae,Ne,Fe,Oe,He,ze,Ve,Le,Be,qe,Ke,Ze,Qe];import*as ot from"dotenv";ot.config();jo(Oo(process.argv)).scriptName("dubhe").command(et).version(L.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(tt.red(e)),e.includes("Missing required argument")&&console.log(tt.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(N(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
59
+ `;Bt(s,o,"storeConfig")}async function Bt(e,t,o){Kt(Lt(t),{recursive:!0}),qt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Ee(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await Z(s,t);await Ht(r.network,r.packageId,o)}import{loadConfig as zt}from"@0xobelisk/sui-common";var Yt={command:"config-store",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"],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":o}){try{let n=await zt(e);await Ee(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},De=Yt;import Wt from"chokidar";import{exec as Jt}from"child_process";var Gt={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{Jt("pnpm dubhe schemagen",(n,s,r)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(r){console.error(`schemagen stderr: ${r}`);return}console.log(`schemagen stdout: ${s}`)})},o=Wt.watch(e,{persistent:!0});o.on("change",n=>{console.log(`${n} has been changed. Running schemagen...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{o.close(),console.log(`
60
+ Watch stopped.`),process.exit()})}},Ie=Gt;import Xt from"wait-on";import Zt from"ora";import B from"chalk";var Qt={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=Zt({text:`Waiting for service to start ${B.cyan(t.url)}...`,color:"cyan"});o.start();try{await Xt({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(B.green("Service is ready!")),process.exit(0)}catch{o.fail(B.red("Timeout waiting for service")),console.error(B.yellow("Please make sure the service is running...")),process.exit(1)}}},Pe=Qt;var eo={command:"switch-env",describe:"Switch environment",builder(e){return e.option("network",{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"})},async handler(e){await I(e.network)}},Te=eo;import to from"dotenv";import T from"chalk";to.config();var oo={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=$({network:e}),o=t.getSigner();console.log(T.blue("Account Information:")),console.log(` Network: ${T.green(e)}`),console.log(` Address: ${T.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${T.green(s)} SUI`)}catch{console.log(` Balance: ${T.red("Failed to fetch balance")} ${T.gray("(Network error)")}`)}}catch(t){_(t),process.exit(1)}}},Ne=oo;import{loadConfig as no}from"@0xobelisk/sui-common";async function Me(e,t,o){if(o)await O(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await se(n,t);await O(e.name,t,s)}}var so={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",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}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await no(t);await Me(n,e,o)}catch(n){_(n),process.exit(1)}process.exit(0)}},Oe=so;import f from"chalk";import{spawn as ro}from"child_process";import{existsSync as io}from"fs";import{homedir as ao}from"os";import{join as co}from"path";import lo from"cli-table3";async function z(e,t=[]){return new Promise(o=>{let n=ro(e,t,{shell:!0}),s="",r="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{r+=i.toString()}),n.on("close",i=>{o({code:i||0,stdout:s,stderr:r})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:r})})})}async function F(e,t="--version"){try{let o=await z(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
61
+ `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else return{name:e,status:"error",message:"Not installed",fixSuggestion:je(e)}}catch{return{name:e,status:"error",message:"Not installed",fixSuggestion:je(e)}}}function je(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:"Visit https://docs.sui.io/guides/developer/getting-started/sui-install to install Sui CLI",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js",git:"Visit https://git-scm.com/downloads to install Git"}[e]||`Please install ${e}`}function uo(e,t){let o=io(e);return{name:t,status:o?"success":"warning",message:o?"Available":"Not found",fixSuggestion:o?void 0:`Please create file: ${e}`}}async function po(){try{let e=await z("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 mo(){try{return(await z("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 go(){try{let e=await z("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 config: npm config list"}}catch{return{name:"NPM configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}function fo(e){let t={success:f.green("\u2713"),warning:f.yellow("!"),error:f.red("\u2717")},o={success:f.green("YES"),warning:f.yellow("WARN"),error:f.red("NO")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function ho(){console.log(f.bold.blue(`
62
+ \u{1F50D} Dubhe Doctor - Environment Check Tool
63
+ `)),console.log(f.gray(`Checking your development environment...
64
+ `));let e=[];console.log(`Running checks...
65
+ `);let t=await po();e.push(t);let o=await F("pnpm");e.push(o);let n=await F("git");e.push(n);let s=await go();s.status==="error"&&(s.status="warning"),e.push(s);let r=await F("docker");e.push(r);let i=null;r.status==="success"&&(i=await mo(),e.push(i));let a=await F("docker-compose");e.push(a);let l=await F("sui");e.push(l);let c=uo(co(ao(),".gitconfig"),"Git configuration");e.push(c);let g=new lo({head:[f.bold.cyan("Criteria"),f.bold.cyan("Result"),f.bold.cyan("Fix")],colWidths:[25,15,50],style:{head:["cyan"],border:["grey"]},wordWrap:!0});e.forEach(d=>{g.push(fo(d))}),console.log(g.toString());let u={success:e.filter(d=>d.status==="success").length,warning:e.filter(d=>d.status==="warning").length,error:e.filter(d=>d.status==="error").length};console.log(`
66
+ `+f.bold("\u{1F4CA} Check Summary:")),console.log(` ${f.green("\u2713 Passed:")} ${u.success} items`),console.log(` ${f.yellow("! Warning:")} ${u.warning} items`),console.log(` ${f.red("\u2717 Error:")} ${u.error} items`),u.error>0?(console.log(f.red(`
67
+ \u274C Your environment has some issues, please fix them according to the suggestions above.`)),process.exit(1)):u.warning>0?console.log(f.yellow(`
68
+ \u26A0\uFE0F Your environment is basically ready, but it is recommended to fix warning items for a better development experience.`)):console.log(f.green(`
69
+ \u2705 Congratulations! Your development environment is fully ready!`)),console.log(f.gray(`
70
+ \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var yo={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("verbose",{alias:"v",type:"boolean",description:"Show verbose output",default:!1})},async handler(){try{await ho()}catch(e){console.error(f.red("Error occurred during check:"),e),process.exit(1)}}},Re=yo;import bo from"chalk";import{loadConfig as wo}from"@0xobelisk/sui-common";import vo from"fs";var ko={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 o=await wo(e),n=re(o);vo.writeFileSync(t,n)}catch(o){console.error(bo.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},Fe=ko;var Ae=[ge,be,he,ye,we,ve,ke,_e,Se,De,Ie,Pe,Te,Ne,Oe,Re,Fe];import*as Ve from"dotenv";Ve.config();xo(Co(process.argv)).scriptName("dubhe").command(Ae).version(M.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(Ue.red(e)),e.includes("Missing required argument")&&console.log(Ue.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(_(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
92
71
  //# sourceMappingURL=dubhe.js.map