@0xobelisk/sui-cli 1.2.0-pre.63 → 1.2.0-pre.68

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/dist/dubhe.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import xn from"yargs";import{hideBin as Cn}from"yargs/helpers";import _t from"chalk";import{execSync as G,spawn as We}from"child_process";import C from"chalk";import Et from"chalk";function re(){console.log(Et.yellow(`
2
+ import Wn from"yargs";import{hideBin as qn}from"yargs/helpers";import jt from"chalk";import{execSync as ee,spawn as Xe}from"child_process";import $ from"chalk";import Lt from"chalk";function Q(){console.log(Lt.yellow(`
3
3
  Welcome to Dubhe
4
4
  --from team@obelisk
5
5
  ________ ___ ___ ________ ___ ___ _______
@@ -10,97 +10,109 @@ Welcome to Dubhe
10
10
  \\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
11
11
  \\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
12
12
 
13
- `))}import{Transaction as de}from"@0xobelisk/sui-client";import{execSync as qt}from"child_process";import T from"chalk";import*as we from"fs/promises";import{mkdirSync as Mt,writeFileSync as Rt}from"fs";import{dirname as Ft}from"path";import{SUI_PRIVATE_KEY_PREFIX as jt}from"@mysten/sui/cryptography";import X from"chalk";import{ZodError as It}from"zod";import{fromZodError as At,ValidationError as Nt}from"zod-validation-error";var ye=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},N=class extends Error{name="DubheCliError"},ie=class extends Error{name="UpgradeError"};function M(e){if(e instanceof Nt)console.log(X.redBright(e.message));else if(e instanceof It){let t=At(e,{prefixSeparator:`
13
+ `))}import{Transaction as fe}from"@0xobelisk/sui-client";import{execSync as no}from"child_process";import T from"chalk";import*as ke from"fs/promises";import{mkdirSync as Bt,writeFileSync as Yt}from"fs";import{dirname as Kt}from"path";import{SUI_PRIVATE_KEY_PREFIX as Gt}from"@mysten/sui/cryptography";import ne from"chalk";import{ZodError as Vt}from"zod";import{fromZodError as zt,ValidationError as Wt}from"zod-validation-error";var Ce=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},R=class extends Error{name="DubheCliError"},ue=class extends Error{name="UpgradeError"};function j(e){if(e instanceof Wt)console.log(ne.redBright(e.message));else if(e instanceof Vt){let t=zt(e,{prefixSeparator:`
14
14
  - `,issueSeparator:`
15
- - `});console.log(X.redBright(t.message))}else e instanceof ye?(console.log(X.red(e.message)),console.log(""),console.log(X.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof N?console.log(X.red(e)):console.log(e)}import*as L from"fs";import F from"chalk";import{spawn as _e}from"child_process";import{Dubhe as Ht,loadMetadata as Vt}from"@0xobelisk/sui-client";var R={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.63",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:">=22.0.0"},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.35.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",axios:"^1.10.0",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"^5.8.3","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^22.16.0","@types/yargs":"^17.0.10",eslint:"^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 ve(e){if(e.startsWith(jt))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 we.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 ae(e,t){try{let o=await we.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function Y(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await ae(o,"mainnet");case"testnet":return await ae(o,"testnet");case"devnet":return await ae(o,"devnet");case"localnet":return await ae(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function Te(e,t){return(await z(e,t)).components}async function De(e,t){return(await z(e,t)).resources}async function Ee(e,t){return(await z(e,t)).version}async function le(e,t){return(await z(e,t)).packageId}async function Ie(e,t){return(await z(e,t)).upgradeCap}async function Ae(e,t){return(await z(e,t)).startCheckpoint}async function Q(e,t,o,n,s,r,a,u,d,c){let g={projectName:e,network:t,startCheckpoint:o,packageId:n,dappHub:s,upgradeCap:r,version:a,components:u,resources:d,enums:c},f=process.cwd(),h=JSON.stringify(g,null,2);await be(h,`${f}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function Z(e,t,o){let n=process.cwd();try{let s=await Vt(t,o);if(s){let r=JSON.stringify(s,null,2);await be(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await be(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(F.yellow(`Warning: Failed to save metadata: ${s}`))}}async function be(e,t,o){Mt(Ft(t),{recursive:!0}),Rt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Ut(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe.git", subdir = "framework/src/dubhe", rev = "v${R.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe.git", subdir = "framework/src/dubhe", rev = "v${R.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function ce(e,t){let o=L.readFileSync(e,"utf-8"),n=Ut(t),s=o.replace(/Dubhe = \{.*\}/,n);L.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function Lt(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 zt(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 Lt(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 a="",u="",d=_e("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",c=>{u+=c.toString()}),d.stderr.on("data",c=>{a+=c.toString()}),d.on("error",c=>{console.error(F.red(`
16
- \u274C Failed to execute sui command: ${c.message}`)),r(new Error(`Failed to execute sui command: ${c.message}`))}),d.on("exit",c=>{if(a.includes("already exists")||u.includes("already exists")){console.log(F.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(c===0)console.log(F.green(`Successfully added environment ${e}`)),s();else{let g=a||u||`Process exited with code ${c}`;console.error(F.red(`
17
- \u274C Failed to add environment ${e}`)),console.error(F.red(` \u2514\u2500 ${g.trim()}`)),r(new Error(g))}})})}async function W(e){try{return await zt(e),new Promise((t,o)=>{let n="",s="",r=_e("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});r.stdout.on("data",a=>{s+=a.toString()}),r.stderr.on("data",a=>{n+=a.toString()}),r.on("error",a=>{console.error(F.red(`
18
- \u274C Failed to execute sui command: ${a.message}`)),o(new Error(`Failed to execute sui command: ${a.message}`))}),r.on("exit",a=>{if(a===0)console.log(F.green(`Successfully switched to environment ${e}`)),t();else{let u=n||s||`Process exited with code ${a}`;console.error(F.red(`
19
- \u274C Failed to switch to environment ${e}`)),console.error(F.red(` \u2514\u2500 ${u.trim()}`)),o(new Error(u))}})})}catch(t){throw t}}var q=e=>new Promise(t=>setTimeout(t,e));function Wt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new N(`Missing private key environment variable.
15
+ - `});console.log(ne.redBright(t.message))}else e instanceof Ce?(console.log(ne.red(e.message)),console.log(""),console.log(ne.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof R?console.log(ne.red(e)):console.log(e)}import*as z from"fs";import O from"chalk";import{spawn as Se}from"child_process";import{Dubhe as Jt,loadMetadata as Xt}from"@0xobelisk/sui-client";var U={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.68",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:">=22.0.0"},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.35.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",axios:"^1.10.0",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",typescript:"^5.8.3","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^22.16.0","@types/yargs":"^17.0.10",eslint:"^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 Pe(e){if(e.startsWith(Gt))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 W(e,t){try{let o=await ke.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 pe(e,t){try{let o=await ke.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 pe(o,"mainnet");case"testnet":return await pe(o,"testnet");case"devnet":return await pe(o,"devnet");case"localnet":return await pe(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function Me(e,t){return(await W(e,t)).components}async function Re(e,t){return(await W(e,t)).resources}async function Fe(e,t){return(await W(e,t)).version}async function me(e,t){return(await W(e,t)).packageId}async function je(e,t){return(await W(e,t)).upgradeCap}async function Ue(e,t){return(await W(e,t)).startCheckpoint}async function se(e,t,o,n,s,r,i,c,d,l){let m={projectName:e,network:t,startCheckpoint:o,packageId:n,dappHub:s,upgradeCap:r,version:i,components:c,resources:d,enums:l},p=process.cwd(),y=JSON.stringify(m,null,2);await $e(y,`${p}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function re(e,t,o){let n=process.cwd();try{let s=await Xt(t,o);if(s){let r=JSON.stringify(s,null,2);await $e(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await $e(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(O.yellow(`Warning: Failed to save metadata: ${s}`))}}async function $e(e,t,o){Bt(Kt(t),{recursive:!0}),Yt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Qt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe.git", subdir = "framework/src/dubhe", rev = "v${U.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe.git", subdir = "framework/src/dubhe", rev = "v${U.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function ge(e,t){let o=z.readFileSync(e,"utf-8"),n=Qt(t),s=o.replace(/Dubhe = \{.*\}/,n);z.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function Zt(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 eo(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 Zt(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=Se("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",l=>{c+=l.toString()}),d.stderr.on("data",l=>{i+=l.toString()}),d.on("error",l=>{console.error(O.red(`
16
+ \u274C Failed to execute sui command: ${l.message}`)),r(new Error(`Failed to execute sui command: ${l.message}`))}),d.on("exit",(l,m)=>{if(i.includes("already exists")||c.includes("already exists")){console.log(O.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(l===0)console.log(O.green(`Successfully added environment ${e}`)),s();else{let p;l===null?p=i||c||`Process was terminated by signal ${m||"unknown"}`:p=i||c||`Process exited with code ${l}`,console.error(O.red(`
17
+ \u274C Failed to add environment ${e}`)),console.error(O.red(` \u2514\u2500 ${p.trim()}`)),r(new Error(p))}})})}async function to(){try{return new Promise((e,t)=>{let o="",n="",s=Se("sui",["client","envs","--json"],{env:{...process.env},stdio:"pipe"});s.stdout.on("data",r=>{n+=r.toString()}),s.stderr.on("data",r=>{o+=r.toString()}),s.on("error",r=>{console.error(O.red(`
18
+ \u274C Failed to execute sui command: ${r.message}`)),t(new Error(`Failed to execute sui command: ${r.message}`))}),s.on("exit",(r,i)=>{if(r===0)e(JSON.parse(n));else{let c;r===null?c=o||n||`Process was terminated by signal ${i||"unknown"}`:c=o||n||`Process exited with code ${r}`,console.error(O.red(`
19
+ \u274C Failed to get envs`)),console.error(O.red(` \u2514\u2500 ${c.trim()}`)),t(new Error(c))}})})}catch(e){throw e}}async function D(){let[e,t]=await to();return t}async function q(e){try{return await eo(e),new Promise((t,o)=>{let n="",s="",r=Se("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(O.red(`
20
+ \u274C Failed to execute sui command: ${i.message}`)),o(new Error(`Failed to execute sui command: ${i.message}`))}),r.on("exit",(i,c)=>{if(i===0)console.log(O.green(`Successfully switched to environment ${e}`)),t();else{let d;i===null?d=n||s||`Process was terminated by signal ${c||"unknown"}`:d=n||s||`Process exited with code ${i}`,console.error(O.red(`
21
+ \u274C Failed to switch to environment ${e}`)),console.error(O.red(` \u2514\u2500 ${d.trim()}`)),o(new Error(d))}})})}catch(t){throw t}}var B=e=>new Promise(t=>setTimeout(t,e));function oo(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new R(`Missing private key environment variable.
20
22
  Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
21
23
  or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
22
- in your contracts directory to use the default sui private key.`);let t=ve(e);if(t===!1)throw new N("Please check your privateKey.");return t}function j({network:e,packageId:t,metadata:o}){let n=Wt();return new Ht({networkType:e,secretKey:n,packageId:t,metadata:o})}function Ne(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"],offchain:!1}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"],offchain:!1}};let a=r.fields||{},u=r.keys||["entity_id"],d=r.offchain??!1;return!a.entity_id&&u.includes("entity_id")&&(a.entity_id="address"),{[s]:{fields:Object.entries(a).map(([c,g])=>({[c]:g})),keys:u,offchain:d}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[],offchain:!1}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[],offchain:!1}};let a=r.fields||{},u=r.keys||[],d=r.offchain??!1;return{[s]:{fields:Object.entries(a).map(([c,g])=>({[c]:g})),keys:u,offchain:d}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let a=r.sort((u,d)=>u.localeCompare(d)).map(u=>u);return{[s]:a}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function xe(e,t){let o=`${e}/Move.toml`,s=L.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);L.writeFileSync(o,s,"utf-8")}function Oe(e,t){let o=`${e}/sources/codegen/genesis.move`,n=L.readFileSync(o,"utf-8"),s=/(\/\/ ==========================================)[\s\S]*?(\/\/ ==========================================)/,r=n.match(s);if(!r)throw new Error("Could not find separator comments in genesis.move");let a=t.map(c=>` ${c}::register_table(dapp_hub, _ctx);`).join(`
23
- `),u=`${r[1]}
24
- ${a}
25
- ${r[2]}`,d=n.replace(s,u);L.writeFileSync(o,d,"utf-8")}import*as O from"fs";import*as Me from"path";async function Re(e,t){if(!O.existsSync(e))return;let o=O.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");O.writeFileSync(e,s,"utf-8")}function Fe(e,t,o,n,s){let r=Me.resolve(e),a=O.readFileSync(r,"utf-8"),u=a.split(`
26
- `),d=u.findIndex(h=>h.trim()===`[env.${t}]`),c={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(d===-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 h=d+1;h<u.length;h++){let b=u[h].trim();if(b.startsWith("["))break;let[P,E]=b.split("=").map(l=>l.trim().replace(/"/g,""));switch(P){case"original-published-id":c.originalPublishedId=E;break;case"latest-published-id":c.latestPublishedId=E;break;case"published-version":c.publishedVersion=parseInt(E,10);break}}o==="publish"?(c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1):o==="upgrade"&&(c.latestPublishedId=s,c.publishedVersion+=1)}let g=`
24
+ in your contracts directory to use the default sui private key.`);let t=Pe(e);if(t===!1)throw new R("Please check your privateKey.");return t}function H({network:e,packageId:t,metadata:o}){let n=oo();return new Jt({networkType:e,secretKey:n,packageId:t,metadata:o})}function He(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"],offchain:!1}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"],offchain:!1}};let i=r.fields||{},c=r.keys||["entity_id"],d=r.offchain??!1;!i.entity_id&&c.includes("entity_id")&&(i.entity_id="address");let l=Object.entries(i),m=l.find(([b])=>b==="entity_id"),p=l.filter(([b])=>b!=="entity_id"),y=m?[m,...p]:p;return{[s]:{fields:y.map(([b,P])=>({[b]:P})),keys:c,offchain:d}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[],offchain:!1}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[],offchain:!1}};let i=r.fields||{},c=r.keys||[],d=r.offchain??!1;return{[s]:{fields:Object.entries(i).map(([l,m])=>({[l]:m})),keys:c,offchain:d}}});o.some(s=>"dapp_fee_state"in s)||o.push({dapp_fee_state:{fields:[{dapp_key:"String"},{base_fee:"u256"},{byte_fee:"u256"},{free_credit:"u256"},{total_bytes_size:"u256"},{total_recharged:"u256"},{total_paid:"u256"}],keys:["dapp_key"],offchain:!1}});let n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((c,d)=>c.localeCompare(d)).map(c=>c);return{[s]:i}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function _e(e,t){let o=`${e}/Move.toml`,s=z.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);z.writeFileSync(o,s,"utf-8")}function Le(e,t){let o=`${e}/sources/codegen/genesis.move`,n=z.readFileSync(o,"utf-8"),s=/(\/\/ ==========================================)[\s\S]*?(\/\/ ==========================================)/,r=n.match(s);if(!r)throw new Error("Could not find separator comments in genesis.move");let i=t.map(l=>` ${l}::register_table(dapp_hub, _ctx);`).join(`
25
+ `),c=`${r[1]}
26
+ ${i}
27
+ ${r[2]}`,d=n.replace(s,c);z.writeFileSync(o,d,"utf-8")}import*as F from"fs";import*as Ve from"path";async function ze(e,t){if(!F.existsSync(e))return;let o=F.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");F.writeFileSync(e,s,"utf-8")}function We(e,t,o,n,s){let r=Ve.resolve(e),i=F.readFileSync(r,"utf-8"),c=i.split(`
28
+ `),d=c.findIndex(y=>y.trim()===`[env.${t}]`),l={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(d===-1)if(o==="publish")l.originalPublishedId=s,l.latestPublishedId=s,l.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 b=c[y].trim();if(b.startsWith("["))break;let[P,A]=b.split("=").map(u=>u.trim().replace(/"/g,""));switch(P){case"original-published-id":l.originalPublishedId=A;break;case"latest-published-id":l.latestPublishedId=A;break;case"published-version":l.publishedVersion=parseInt(A,10);break}}o==="publish"?(l.originalPublishedId=s,l.latestPublishedId=s,l.publishedVersion=1):o==="upgrade"&&(l.latestPublishedId=s,l.publishedVersion+=1)}let m=`
27
29
  [env.${t}]
28
- chain-id = "${c.chainId}"
29
- original-published-id = "${c.originalPublishedId}"
30
- latest-published-id = "${c.latestPublishedId}"
31
- published-version = "${c.publishedVersion}"
32
- `,f=d===-1?a+g:u.slice(0,d).join(`
33
- `)+g;O.writeFileSync(r,f,"utf-8")}function je(e){let t,o;try{let n=JSON.parse(qt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(T.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function He(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,a)=>r+Number(a.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(T.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function Bt(e,t,o,n,s){console.log(`
34
- \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 He(e);console.log(" \u251C\u2500 Validating Environment..."),await Re(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
35
- \u{1F4E6} Building Contract...`);let[a,u]=je(n);console.log(`
36
- \u{1F504} Publishing Contract...`);let d=new de;s&&d.setGasBudget(s);let[c]=d.publish({modules:a,dependencies:u});d.transferObjects([c],e.getAddress());let g;try{g=await e.signAndSendTxn({tx:d})}catch(m){console.error(T.red(" \u2514\u2500 Publication failed")),console.error(m.message),process.exit(1)}(!g||g.effects?.status.status==="failure")&&(console.log(T.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let f=1,h="",b="",P=t.components,E=t.resources,l=t.enums,k="",p="",y=[];g.objectChanges.map(m=>{m.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${m.packageId}`),h=m.packageId||""),m.type==="created"&&m.objectType&&m.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${m.objectId}`),k=m.objectId||""),m.type==="created"&&m.objectType&&m.objectType.includes("dapp_service::DappHub")&&(b=m.objectId||""),m.type==="created"&&y.push(m)}),console.log(` \u2514\u2500 Transaction: ${g.digest}`),Fe(`${n}/Move.lock`,o,"publish",r,h),console.log(`
37
- \u26A1 Executing Deploy Hook...`),await q(5e3),p=await e.suiInteractor.currentClient.getLatestCheckpointSequenceNumber();let $=new de,I=[],S=t.name==="dubhe"?b:await Y(o);I.push($.object(S)),I.push($.object("0x6")),$.moveCall({target:`${h}::genesis::run`,arguments:I});let _;try{_=await e.signAndSendTxn({tx:$})}catch(m){console.error(T.red(" \u2514\u2500 Deploy hook execution failed")),console.error(m.message),process.exit(1)}if(_.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${_.digest}`),console.log(`
38
- \u{1F4CB} Created Objects:`),y.map(v=>{console.log(` \u251C\u2500 ID: ${v.objectId}`),console.log(` \u2514\u2500 Type: ${v.objectType}`)}),await Q(t.name,o,p,h,b,k,f,P,E,l),await Z(t.name,o,h);let m=JSON.parse(O.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));m.package_id=h,m.start_checkpoint=p,O.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(m,null,2)),console.log(`
30
+ chain-id = "${l.chainId}"
31
+ original-published-id = "${l.originalPublishedId}"
32
+ latest-published-id = "${l.latestPublishedId}"
33
+ published-version = "${l.publishedVersion}"
34
+ `,p=d===-1?i+m:c.slice(0,d).join(`
35
+ `)+m;F.writeFileSync(r,p,"utf-8")}function qe(e){let t,o;try{let n=JSON.parse(no(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(T.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function Be(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(T.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function so(e,t,o,n,s){console.log(`
36
+ \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 Be(e);console.log(" \u251C\u2500 Validating Environment..."),await ze(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
37
+ \u{1F4E6} Building Contract...`);let[i,c]=qe(n);console.log(`
38
+ \u{1F504} Publishing Contract...`);let d=new fe;s&&d.setGasBudget(s);let[l]=d.publish({modules:i,dependencies:c});d.transferObjects([l],e.getAddress());let m;try{m=await e.signAndSendTxn({tx:d})}catch(h){console.error(T.red(" \u2514\u2500 Publication failed")),console.error(h.message),process.exit(1)}(!m||m.effects?.status.status==="failure")&&(console.log(T.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let p=1,y="",b="",P=t.components,A=t.resources,u=t.enums,k="",f="",w=[];m.objectChanges.map(h=>{h.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${h.packageId}`),y=h.packageId||""),h.type==="created"&&h.objectType&&h.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${h.objectId}`),k=h.objectId||""),h.type==="created"&&h.objectType&&h.objectType.includes("dapp_service::DappHub")&&(b=h.objectId||""),h.type==="created"&&w.push(h)}),console.log(` \u2514\u2500 Transaction: ${m.digest}`),We(`${n}/Move.lock`,o,"publish",r,y),console.log(`
39
+ \u26A1 Executing Deploy Hook...`),await B(5e3),f=await e.suiInteractor.currentClient.getLatestCheckpointSequenceNumber();let S=new fe,N=[],_=t.name==="dubhe"?b:await Z(o);N.push(S.object(_)),N.push(S.object("0x6")),S.moveCall({target:`${y}::genesis::run`,arguments:N});let E;try{E=await e.signAndSendTxn({tx:S})}catch(h){console.error(T.red(" \u2514\u2500 Deploy hook execution failed")),console.error(h.message),process.exit(1)}if(E.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${E.digest}`),console.log(`
40
+ \u{1F4CB} Created Objects:`),w.map(x=>{console.log(` \u251C\u2500 ID: ${x.objectId}`),console.log(` \u2514\u2500 Type: ${x.objectType}`)}),await se(t.name,o,f,y,b,k,p,P,A,u),await re(t.name,o,y);let h=JSON.parse(F.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));h.package_id=y,h.start_checkpoint=f,F.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(h,null,2)),console.log(`
39
41
  \u2705 Contract Publication Complete
40
- `)}else console.log(T.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(T.yellow(" Please republish or manually call deploy_hook::run")),console.log(T.yellow(" Please check the transaction digest:")),console.log(T.yellow(` ${_.digest}`)),process.exit(1)}async function Kt(e){return O.existsSync(e)?!0:(console.log(T.yellow(`
41
- \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(T.yellow(" \u251C\u2500 Expected Path:"),e),console.log(T.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(T.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(T.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(T.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(T.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function Yt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await Kt(n))return;console.log(`
42
- \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await He(e);await Re(`${n}/Move.lock`,t),await xe(n,"0x0");let[r,a]=je(n),u=new de,[d]=u.publish({modules:r,dependencies:a});u.transferObjects([d],e.getAddress());let c;try{c=await e.signAndSendTxn({tx:u})}catch(l){console.error(T.red(" \u2514\u2500 Publication failed")),console.error(l.message),process.exit(1)}(!c||c.effects?.status.status==="failure")&&(console.log(T.red(" \u2514\u2500 Publication failed")),process.exit(1));let g=1,f="",h="",b="";c.objectChanges.map(l=>{l.type==="published"&&(f=l.packageId||""),l.type==="created"&&l.objectType&&l.objectType==="0x2::package::UpgradeCap"&&(b=l.objectId||""),l.type==="created"&&l.objectType&&l.objectType.includes("dapp_service::DappHub")&&(h=l.objectId||"")}),await q(3e3);let P=new de;P.moveCall({target:`${f}::genesis::run`,arguments:[P.object(h),P.object("0x6")]});let E;try{E=await e.signAndSendTxn({tx:P})}catch(l){console.error(T.red(" \u2514\u2500 Deploy hook execution failed")),console.error(l.message),process.exit(1)}if(E.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await xe(n,f),await Q("dubhe",t,f,"0",h,b,g,{},{},{}),Fe(`${n}/Move.lock`,t,"publish",s,f)}async function Ve(e,t,o,n){await W(t);let s=j({network:t}),a=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await Yt(s,t),console.log(o),e.name!=="dubhe"&&o&&await ce(`${a}/Move.toml`,t),await Bt(s,e,t,a,n)}import{Transaction as Ue,UpgradePolicy as Gt}from"@0xobelisk/sui-client";import{execSync as Jt}from"child_process";import B from"chalk";import*as pe from"fs";import*as Le from"path";function ue(e,t,o,n){let s=Le.resolve(e),a=pe.readFileSync(s,"utf-8").split(`
43
- `),u=a.findIndex(g=>g.trim()===`[env.${t}]`);if(u===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let d=-1,c="";for(let g=u+1;g<a.length;g++){let f=a[g].trim();if(f.startsWith("["))break;if(f.startsWith(o)){d=g,c=f.split("=")[1].trim().replace(/"/g,"");break}}if(d!==-1){a[d]=`${o} = "${n}"`;let g=a.join(`
44
- `);pe.writeFileSync(s,g,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return c}async function ze(e,t,o){await W(o);let n=process.cwd(),s=`${n}/src/${t}`,r=j({network:o}),a=Number(await Ee(s,o)),u=await le(s,o),d=await Ie(s,o),c=await Ae(s,o),g=await Y(o),f=await De(s,o),h=await Te(s,o),b=[];Object.entries(e.resources).forEach(([l,k])=>{f.hasOwnProperty(l)||b.push({name:l,fields:k})}),Object.entries(e.components).forEach(([l,k])=>{h.hasOwnProperty(l)||b.push({name:l,fields:k})});let P=b.map(l=>l.name);Oe(s,P);let E=ue(`${s}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000");try{let l,k,p;try{let{modules:w,dependencies:U,digest:Dt}=JSON.parse(Jt(`sui move build --dump-bytecode-as-base64 --path ${n}/src/${t}`,{encoding:"utf-8"}));l=w,k=U,p=Dt}catch(w){throw new ie(w.stdout)}console.log(`
45
- \u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",u),console.log("\u{1F4CB} UpgradeCap Object Id:",d),console.log("\u{1F4CB} OldVersion:",a);let y=new Ue,$=y.moveCall({target:"0x2::package::authorize_upgrade",arguments:[y.object(d),y.pure.u8(Gt.COMPATIBLE),y.pure.vector("u8",p)]}),I=y.upgrade({modules:l,dependencies:k,package:u,ticket:$});y.moveCall({target:"0x2::package::commit_upgrade",arguments:[y.object(d),I]});let S=await r.signAndSendTxn({tx:y,onSuccess:w=>{console.log(B.green(`Upgrade Transaction Digest: ${w.digest}`))},onError:w=>{console.log(B.red("Upgrade Transaction failed!")),console.error(w)}}),_="";S.objectChanges.map(w=>{w.type==="published"&&(console.log(B.blue(`${t} new PackageId: ${w.packageId}`)),console.log(B.blue(`${t} new Version: ${a+1}`)),_=w.packageId)}),ue(`${s}/Move.lock`,o,"original-published-id",E),ue(`${s}/Move.lock`,o,"latest-published-id",_),ue(`${s}/Move.lock`,o,"published-version",a+1+""),Q(t,o,c,_,g,d,a+1,e.components,e.resources,e.enums),console.log(`
46
- \u{1F680} Starting Migration Process...`),b.forEach(w=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(w,null,2))}),await new Promise(w=>setTimeout(w,5e3));let m=new Ue,v=a+1;m.moveCall({target:`${_}::migrate::migrate_to_v${v}`,arguments:[m.object(g),m.pure.address(_),m.pure.u32(v)]}),await r.signAndSendTxn({tx:m,onSuccess:w=>{console.log(B.green(`Migration Transaction Digest: ${w.digest}`))},onError:w=>{console.log(B.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(w)}})}catch(l){console.log(B.red("upgrade handler execution failed!")),console.error(l.message)}}import{Dubhe as Xt}from"@0xobelisk/sui-client";import*as ge from"fs";function Qt(){console.log(C.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{G("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=G(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
47
- `).filter(r=>r);console.log(C.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{G(`kill -TERM ${r}`,{stdio:"ignore"}),console.log(C.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{G(`kill -KILL ${r}`,{stdio:"ignore"}),console.log(C.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log(C.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?C.green(" \u2514\u2500 Local Node stopped successfully"):C.gray(" \u2514\u2500 No running Local Node found"))}function Zt(e){try{ge.existsSync(e)?(console.log(C.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),ge.rmSync(e,{recursive:!0,force:!0}),console.log(C.green(" \u2514\u2500 Directory removed successfully"))):console.log(C.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(C.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function eo(){try{if(process.platform==="win32")return G('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=G(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function to(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new Xt({secretKey:t}).getSigner();We("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(C.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(C.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function oo(e){let t=()=>{console.log(C.yellow(`
48
- \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function qe(e,t){if(t)console.log(C.cyan(`
49
- \u{1F504} Force mode enabled`)),Qt(),console.log(C.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await q(3e3),Zt(e),console.log("");else if(eo()){console.log(C.yellow(`
50
- \u26A0\uFE0F Warning: Local Node Already Running`)),console.log(C.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(C.yellow(" \u2514\u2500 Please stop the existing process first"));return}re(),console.log("\u{1F680} Starting Local Node...");let o=null;try{let n=["start","--with-faucet"];if(t&&n.push("--force-regenesis"),n.push("--data-ingestion-dir",e),o=We("sui",n,{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",r=>{console.error(C.red(`
51
- \u274C Failed to Start Local Node`)),console.error(C.red(` \u2514\u2500 Error: ${r.message}`))}),await q(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(` \u251C\u2500 Force Regenesis: ${t?"Yes":"No"}`),console.log(" \u251C\u2500 RPC server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await to(),await q(2e3),ve("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new N("Please check your privateKey.");console.log(C.green("\u{1F389} Local environment is ready!")),oo(o),await new Promise(r=>{o?.on("exit",()=>r())})}catch(n){console.error(C.red(`
52
- \u274C Failed to Start Local Node`)),console.error(C.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var no={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 qe(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},Be=no;import{requestSuiFromFaucetV0 as so,getFaucetHost as ro}from"@mysten/sui/faucet";import{SuiClient as io,getFullnodeUrl as ao}from"@mysten/sui/client";var Ce=60,lo=1e3,Ke=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],co={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=j(e).getAddress():o=t,console.log(`
53
- \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,a=Date.now(),u=!1,d=()=>{u=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
54
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",d);try{for(;n<Ce&&!s&&!u;)try{await so({host:ro(e),recipient:o}),s=!0}catch{if(u)break;n++,n===Ce&&(console.log(` \u2514\u2500 Failed to request funds after ${Ce} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let b=Math.floor((Date.now()-a)/1e3),P=Ke[r%Ke.length];r++,process.stdout.write(`\r \u251C\u2500 ${P} Retrying... (${b}s)`),await new Promise(E=>setTimeout(E,lo))}}finally{process.removeListener("SIGINT",d)}u&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let c=new io({url:ao(e)}),g={owner:o},f=await c.getBalance(g);console.log(`
55
- \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(f.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
42
+ `)}else console.log(T.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(T.yellow(" Please republish or manually call deploy_hook::run")),console.log(T.yellow(" Please check the transaction digest:")),console.log(T.yellow(` ${E.digest}`)),process.exit(1)}async function ro(e){return F.existsSync(e)?!0:(console.log(T.yellow(`
43
+ \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(T.yellow(" \u251C\u2500 Expected Path:"),e),console.log(T.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(T.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(T.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(T.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(T.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function ao(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await ro(n))return;console.log(`
44
+ \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await Be(e);await ze(`${n}/Move.lock`,t),await _e(n,"0x0");let[r,i]=qe(n),c=new fe,[d]=c.publish({modules:r,dependencies:i});c.transferObjects([d],e.getAddress());let l;try{l=await e.signAndSendTxn({tx:c})}catch(u){console.error(T.red(" \u2514\u2500 Publication failed")),console.error(u.message),process.exit(1)}(!l||l.effects?.status.status==="failure")&&(console.log(T.red(" \u2514\u2500 Publication failed")),process.exit(1));let m=1,p="",y="",b="";l.objectChanges.map(u=>{u.type==="published"&&(p=u.packageId||""),u.type==="created"&&u.objectType&&u.objectType==="0x2::package::UpgradeCap"&&(b=u.objectId||""),u.type==="created"&&u.objectType&&u.objectType.includes("dapp_service::DappHub")&&(y=u.objectId||"")}),await B(3e3);let P=new fe;P.moveCall({target:`${p}::genesis::run`,arguments:[P.object(y),P.object("0x6")]});let A;try{A=await e.signAndSendTxn({tx:P})}catch(u){console.error(T.red(" \u2514\u2500 Deploy hook execution failed")),console.error(u.message),process.exit(1)}if(A.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await _e(n,p),await se("dubhe",t,p,"0",y,b,m,{},{},{}),We(`${n}/Move.lock`,t,"publish",s,p)}async function Ye(e,t,o,n){await q(t);let s=H({network:t}),i=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await ao(s,t),console.log(o),e.name!=="dubhe"&&o&&await ge(`${i}/Move.toml`,t),await so(s,e,t,i,n)}import{Transaction as Ke,UpgradePolicy as io}from"@0xobelisk/sui-client";import{execSync as lo}from"child_process";import Y from"chalk";import*as ye from"fs";import*as Ge from"path";function he(e,t,o,n){let s=Ge.resolve(e),i=ye.readFileSync(s,"utf-8").split(`
45
+ `),c=i.findIndex(m=>m.trim()===`[env.${t}]`);if(c===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let d=-1,l="";for(let m=c+1;m<i.length;m++){let p=i[m].trim();if(p.startsWith("["))break;if(p.startsWith(o)){d=m,l=p.split("=")[1].trim().replace(/"/g,"");break}}if(d!==-1){i[d]=`${o} = "${n}"`;let m=i.join(`
46
+ `);ye.writeFileSync(s,m,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return l}async function Je(e,t,o){await q(o);let n=process.cwd(),s=`${n}/src/${t}`,r=H({network:o}),i=Number(await Fe(s,o)),c=await me(s,o),d=await je(s,o),l=await Ue(s,o),m=await Z(o),p=await Re(s,o),y=await Me(s,o),b=[];Object.entries(e.resources).forEach(([u,k])=>{p.hasOwnProperty(u)||b.push({name:u,fields:k})}),Object.entries(e.components).forEach(([u,k])=>{y.hasOwnProperty(u)||b.push({name:u,fields:k})});let P=b.map(u=>u.name);Le(s,P);let A=he(`${s}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000");try{let u,k,f;try{let{modules:v,dependencies:V,digest:Ht}=JSON.parse(lo(`sui move build --dump-bytecode-as-base64 --path ${n}/src/${t}`,{encoding:"utf-8"}));u=v,k=V,f=Ht}catch(v){throw new ue(v.stdout)}console.log(`
47
+ \u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",c),console.log("\u{1F4CB} UpgradeCap Object Id:",d),console.log("\u{1F4CB} OldVersion:",i);let w=new Ke,S=w.moveCall({target:"0x2::package::authorize_upgrade",arguments:[w.object(d),w.pure.u8(io.COMPATIBLE),w.pure.vector("u8",f)]}),N=w.upgrade({modules:u,dependencies:k,package:c,ticket:S});w.moveCall({target:"0x2::package::commit_upgrade",arguments:[w.object(d),N]});let _=await r.signAndSendTxn({tx:w,onSuccess:v=>{console.log(Y.green(`Upgrade Transaction Digest: ${v.digest}`))},onError:v=>{console.log(Y.red("Upgrade Transaction failed!")),console.error(v)}}),E="";_.objectChanges.map(v=>{v.type==="published"&&(console.log(Y.blue(`${t} new PackageId: ${v.packageId}`)),console.log(Y.blue(`${t} new Version: ${i+1}`)),E=v.packageId)}),he(`${s}/Move.lock`,o,"original-published-id",A),he(`${s}/Move.lock`,o,"latest-published-id",E),he(`${s}/Move.lock`,o,"published-version",i+1+""),se(t,o,l,E,m,d,i+1,e.components,e.resources,e.enums),console.log(`
48
+ \u{1F680} Starting Migration Process...`),b.forEach(v=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(v,null,2))}),await new Promise(v=>setTimeout(v,5e3));let h=new Ke,x=i+1;h.moveCall({target:`${E}::migrate::migrate_to_v${x}`,arguments:[h.object(m),h.pure.address(E),h.pure.u32(x)]}),await r.signAndSendTxn({tx:h,onSuccess:v=>{console.log(Y.green(`Migration Transaction Digest: ${v.digest}`))},onError:v=>{console.log(Y.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(v)}})}catch(u){console.log(Y.red("upgrade handler execution failed!")),console.error(u.message)}}import{Dubhe as co}from"@0xobelisk/sui-client";import*as be from"fs";function uo(){console.log($.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{ee("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=ee(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
49
+ `).filter(r=>r);console.log($.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{ee(`kill -TERM ${r}`,{stdio:"ignore"}),console.log($.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{ee(`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 po(e){try{be.existsSync(e)?(console.log($.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),be.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 mo(){try{if(process.platform==="win32")return ee('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=ee(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function go(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new co({secretKey:t}).getSigner();Xe("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 fo(e){let t=()=>{console.log($.yellow(`
50
+ \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Qe(e,t){if(t)console.log($.cyan(`
51
+ \u{1F504} Force mode enabled`)),uo(),console.log($.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await B(3e3),po(e),console.log("");else if(mo()){console.log($.yellow(`
52
+ \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}Q(),console.log("\u{1F680} Starting Local Node...");let o=null;try{let n=["start","--with-faucet"];if(t&&n.push("--force-regenesis"),n.push("--data-ingestion-dir",e),o=Xe("sui",n,{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",r=>{console.error($.red(`
53
+ \u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${r.message}`))}),await B(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(` \u251C\u2500 Force Regenesis: ${t?"Yes":"No"}`),console.log(" \u251C\u2500 RPC server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await go(),await B(2e3),Pe("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new R("Please check your privateKey.");console.log($.green("\u{1F389} Local environment is ready!")),fo(o),await new Promise(r=>{o?.on("exit",()=>r())})}catch(n){console.error($.red(`
54
+ \u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}import ho from"readline";import yo from"yargs";import K from"chalk";import bo from"dotenv";import{spawn as wo}from"child_process";bo.config();var et=!0,Ee=["shell","wait"],g=(e=0)=>{et&&process.exit(e)},Ze=()=>te.filter(e=>!Ee.includes(e.command)).map(e=>e.command),vo={command:"shell",describe:"Open a shell to interact with the Dubhe System",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{e=="default"&&(e=await D(),console.log(K.yellow(`Use default network: [${e}]`))),et=!1;let t=[];function o(s){let r=Ze().filter(i=>i?i.startsWith(s.toLowerCase()):!1);return[r.length?r:Ze(),s]}let n=ho.createInterface({input:process.stdin,output:process.stdout,prompt:`dubhe(${K.green(e)}) ${K.bold(">")} `,completer:o,historySize:200});n.on("line",async s=>{let r=s.trim();if(!r){n.prompt();return}t.push(r);let i=r.split(/\s+/),c=i[0].toLowerCase(),d=te.find(l=>l.command===c&&!Ee.includes(c));if(i.includes("--help")||i.includes("-h")){if(d)try{let l=wo("node",[process.argv[1],c,"--help"],{stdio:"inherit",env:{...process.env}});l.on("exit",()=>{n.prompt()}),l.on("error",()=>{console.log(`
55
+ ${d.describe||`${c} command`}`),console.log(`
56
+ Usage: ${c} [options]`),console.log(`
57
+ For complete help with all options, please exit shell and run:`),console.log(K.cyan(` dubhe ${c} --help`)),n.prompt()});return}catch{console.log(`
58
+ ${d.describe||`${c} command`}`),console.log(`
59
+ Usage: ${c} [options]`),console.log(`
60
+ For complete help with all options, please exit shell and run:`),console.log(K.cyan(` dubhe ${c} --help`))}else console.log(`\u{1F937} Unknown command: "${c}". Type 'help' to see available commands.`);n.prompt();return}if(d)try{let{builder:l,handler:m}=d,p=yo().exitProcess(!1);if(l){typeof l=="function"?l(p):p.options(l);let y=p.parseSync([c,"--network",e,...i.slice(1)]);m&&await m(y)}}catch(l){console.log(K.red(l))}else if(c=="help"){console.log("Available dubhe commands:");let l=te.filter(p=>!Ee.includes(p.command)),m=Math.max(...l.map(p=>(typeof p.command=="string"?p.command:Array.isArray(p.command)?p.command[0]:"").length));l.forEach(p=>{let b=(typeof p.command=="string"?p.command:Array.isArray(p.command)?p.command[0]:"").padEnd(m);console.log(` ${K.green(b)} ${p.describe}`)}),n.prompt();return}else if(["exit","quit"].indexOf(c)!==-1){console.log("Goodbye You will have a nice day! \u{1F44B}"),n.close();return}else console.log(`\u{1F937} Unknown command: "${r}". Type 'help' to see available commands.`);n.prompt()}),n.on("close",()=>{process.exit(0)}),Q(),n.prompt()}},tt=vo;var xo={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 Qe(e,t)}catch(o){console.error("Error executing command:",o),g(1)}g()}},ot=xo;import{requestSuiFromFaucetV2 as Co,getFaucetHost as $o}from"@mysten/sui/faucet";import{SuiClient as ko,getFullnodeUrl as So}from"@mysten/sui/client";var Te=60,Po=1e3,nt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],_o={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=H(e).getAddress():o=t,console.log(`
61
+ \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(`
62
+ \u2514\u2500 Operation cancelled by user`),g(1)};process.on("SIGINT",d);try{for(;n<Te&&!s&&!c;)try{await Co({host:$o(e),recipient:o}),s=!0}catch{if(c)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."),console.log(" \u2514\u2500 You can visit https://faucet.testnet.sui.io/ to request funds manually."),g(1));let b=Math.floor((Date.now()-i)/1e3),P=nt[r%nt.length];r++,process.stdout.write(`\r \u251C\u2500 ${P} Retrying... (${b}s)`),await new Promise(A=>setTimeout(A,Po))}}finally{process.removeListener("SIGINT",d)}c&&g(1),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let l=new ko({url:So(e)}),m={owner:o},p=await l.getBalance(m);console.log(`
63
+ \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(p.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
56
64
  \u2705 Faucet Operation Complete
57
- `),process.exit(0)}},Ye=co;import{schemaGen as uo,loadConfig as po}from"@0xobelisk/sui-common";import go from"chalk";import mo from"node:path";var fo={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 po(e),n=mo.dirname(e);await uo(n,o,t),process.exit(0)}catch(o){console.log(go.red("Schemagen failed!")),console.error(o.message)}}},Ge=fo;import{loadConfig as ho}from"@0xobelisk/sui-common";import{execSync as yo}from"child_process";var bo={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},force:{type:"boolean",default:!0,desc:"Force publish: do not update dependencies"}})},async handler({network:e,"config-path":t,"gas-budget":o,force:n}){try{let s=await ho(t);yo(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Ve(s,e,n,o)}catch(s){M(s),process.exit(1)}process.exit(0)}},Je=bo;import{execSync as wo}from"child_process";import{loadConfig as vo}from"@0xobelisk/sui-common";var xo={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 vo(e),a=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;wo(a,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Xe=xo;import{execSync as Co,exec as ko}from"child_process";import $o from"chalk";import{loadConfig as So}from"@0xobelisk/sui-common";var Po={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 So(e),r=`${process.cwd()}/src/${n.name}`;await W(t),await ce(r+"/Move.toml",t);let a=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,u=Co(a,{encoding:"utf-8"});console.log(u),ko(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error($o.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Qe=Po;var _o={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){re()}},Ze=_o;import{Dubhe as et}from"@0xobelisk/sui-client";import*as te from"fs";import ee from"chalk";async function tt(e=!1,t=!1){t&&(console.log(ee.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(ee.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
58
- `)));let o=process.cwd(),n,s="";try{s=te.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 a=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",u=s.split(`
59
- `),d=!1;for(let f=u.length-1;f>=0;f--){let h=u[f];if(h.endsWith(r)){let[b]=h.split("=");t?d=b==="PRIVATE_KEY":d=b==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(d){for(let f=u.length-1;f>=0;f--)if(u[f].endsWith(r)){let b=`${a}=${r}`;u[f]=b,s=u.join(`
60
- `),te.writeFileSync(`${o}/.env`,s);break}}let g=new et({secretKey:r}).getSigner();console.log(ee.blue(`Using existing account: ${g.toSuiAddress()}`));return}}catch{}if(e||!n){let a=new et().getSigner();n=a.getSecretKey();let d=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
61
- `+d:s=d,te.writeFileSync(`${o}/.env`,s),console.log(ee.green(`File created/updated at: ${o}/.env`)),console.log(ee.blue(`New account generated: ${a.toSuiAddress()}`))}}var To={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 tt(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},ot=To;import Do from"chalk";import Eo from"dotenv";Eo.config();async function nt(e){try{let o=await j({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new N("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(Do.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new N("Failed to check balance: "+t)}}var Io={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 nt(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},st=Io;import{mkdirSync as Ao,writeFileSync as No}from"fs";import{dirname as Oo}from"path";async function Mo(e,t,o){let n=await Y(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
65
+ `),g()}},st=_o;import{schemaGen as Eo,loadConfig as To}from"@0xobelisk/sui-common";import rt from"chalk";import Do from"node:path";var Io={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","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");t=="default"&&(t=await D(),console.log(rt.yellow(`Use default network: [${t}]`)));let o=await To(e),n=Do.dirname(e);await Eo(n,o,t),g()}catch(o){console.log(rt.red("Schemagen failed!")),console.error(o.message),g(1)}}},at=Io;import{loadConfig as Ao}from"@0xobelisk/sui-common";import{execSync as No}from"child_process";import Oo from"chalk";var Mo={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0},force:{type:"boolean",default:!0,desc:"Force publish: do not update dependencies"}})},async handler({network:e,"config-path":t,"gas-budget":o,force:n}){try{e=="default"&&(e=await D(),console.log(Oo.yellow(`Use default network: [${e}]`)));let s=await Ao(t);No(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Ye(s,e,n,o)}catch(s){j(s),g(1)}g()}},it=Mo;import{execSync as Ro}from"child_process";import{loadConfig as Fo}from"@0xobelisk/sui-common";var jo={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 Fo(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Ro(i,{stdio:"inherit",encoding:"utf-8"})}catch{g(1)}g()}},lt=jo;import{execSync as Uo,exec as Ho}from"child_process";import ct from"chalk";import{loadConfig as Lo}from"@0xobelisk/sui-common";var Vo={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:"default",choices:["mainnet","testnet","devnet","localnet","default"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{t=="default"&&(t=await D(),console.log(ct.yellow(`Use default network: [${t}]`))),console.log("\u{1F680} Running move build");let n=await Lo(e),r=`${process.cwd()}/src/${n.name}`;await q(t),await ge(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,c=Uo(i,{encoding:"utf-8"});console.log(c),Ho(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(ct.red("Error executing sui move build:")),console.log(n.stdout),g(1)}}},dt=Vo;var zo={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){Q()}},ut=zo;import{Dubhe as pt}from"@0xobelisk/sui-client";import*as ie from"fs";import ae from"chalk";async function mt(e=!1,t=!1){t&&(console.log(ae.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(ae.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
66
+ `)));let o=process.cwd(),n,s="";try{s=ie.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(`
67
+ `),d=!1;for(let p=c.length-1;p>=0;p--){let y=c[p];if(y.endsWith(r)){let[b]=y.split("=");t?d=b==="PRIVATE_KEY":d=b==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(d){for(let p=c.length-1;p>=0;p--)if(c[p].endsWith(r)){let b=`${i}=${r}`;c[p]=b,s=c.join(`
68
+ `),ie.writeFileSync(`${o}/.env`,s);break}}let m=new pt({secretKey:r}).getSigner();console.log(ae.blue(`Using existing account: ${m.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new pt().getSigner();n=i.getSecretKey();let d=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
69
+ `+d:s=d,ie.writeFileSync(`${o}/.env`,s),console.log(ae.green(`File created/updated at: ${o}/.env`)),console.log(ae.blue(`New account generated: ${i.toSuiAddress()}`))}}var Wo={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 mt(e,t)}catch(o){console.error("Error generating account:",o),g(1)}g()}},gt=Wo;import qo from"chalk";import Bo from"dotenv";Bo.config();async function ft(e){try{let o=await H({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new R("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(qo.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new R("Failed to check balance: "+t)}}import Yo from"chalk";var Ko={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],desc:"Network to check balance on",default:"default"}},async handler({network:e}){try{e=="default"&&(e=await D(),console.log(Yo.yellow(`Use default network: [${e}]`))),await ft(e)}catch(t){console.error("Error checking balance:",t),g(1)}g()}},ht=Ko;import{mkdirSync as Go,writeFileSync as Jo}from"fs";import{dirname as Xo}from"path";async function Qo(e,t,o){let n=await Z(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
62
70
 
63
71
  export const NETWORK: NetworkType = '${e}';
64
72
  export const PACKAGE_ID = '${t}';
65
73
  export const DUBHE_SCHEMA_ID = '${n}';
66
- `;Ro(s,o,"storeConfig")}async function Ro(e,t,o){Ao(Oo(t),{recursive:!0}),No(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function rt(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await z(s,t);await Mo(r.network,r.packageId,o)}import{loadConfig as Fo}from"@0xobelisk/sui-common";var jo={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 Fo(e);await rt(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},it=jo;import Ho from"chokidar";import{exec as Vo}from"child_process";var Uo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{Vo("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=Ho.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(`
67
- Watch stopped.`),process.exit()})}},at=Uo;import lt from"wait-on";import ke from"ora";import H from"chalk";import Lo from"net";function ct(e){let t={HTTP_PROXY:process.env.HTTP_PROXY,HTTPS_PROXY:process.env.HTTPS_PROXY,http_proxy:process.env.http_proxy,https_proxy:process.env.https_proxy,NO_PROXY:process.env.NO_PROXY,no_proxy:process.env.no_proxy};try{return delete process.env.HTTP_PROXY,delete process.env.HTTPS_PROXY,delete process.env.http_proxy,delete process.env.https_proxy,process.env.NO_PROXY="127.0.0.1,localhost,*.local",process.env.no_proxy="127.0.0.1,localhost,*.local",e()}finally{Object.keys(t).forEach(o=>{let n=t[o];n!==void 0?process.env[o]=n:delete process.env[o]})}}async function zo(){return new Promise(e=>{let t=new Lo.Socket,o=!1,n=setTimeout(()=>{t.destroy(),o||e(!1)},2e3);t.connect(5432,"127.0.0.1",()=>{o=!0,clearTimeout(n),t.destroy(),e(!0)}),t.on("error",()=>{clearTimeout(n),o||e(!1)})})}async function Wo(e){let t=ke({text:"Waiting for dubhe localnet services...",color:"cyan"});t.start();let o=Date.now();for(;Date.now()-o<e.timeout;){try{if(await ct(()=>lt({resources:["http://127.0.0.1:9123","http://127.0.0.1:4000"],timeout:e.interval,interval:500,validateStatus:s=>s===200})),await zo()){t.succeed(H.green("All dubhe localnet services are ready!"));return}}catch{}await new Promise(n=>setTimeout(n,e.interval))}throw new Error("Timeout waiting for services")}var qo={command:"wait",describe:"Wait for service(s) to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for (single service)"}).option("localnet",{type:"boolean",description:"Wait for all dubhe localnet services (sui localnode:9000&9123, postgres:5432, graphql:4000)",default:!1}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:24*60*60*1e3}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3}).check(t=>{if(!t.url&&!t.localnet)throw new Error("Please provide either --url or --localnet option");if(t.url&&t.localnet)throw new Error("Cannot use both --url and --localnet options together");return!0})},async handler(e){let t=e;try{if(t.localnet)await Wo(t);else{let o=ke({text:`Waiting for ${t.url}...`,color:"cyan"});o.start(),await ct(()=>lt({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200})),o.succeed(H.green("Service is ready!"))}process.exit(0)}catch{ke().fail(H.red(t.localnet?"Timeout waiting for dubhe localnet services":"Timeout waiting for service")),t.localnet?(console.error(H.yellow("Please make sure all required services are running:")),console.error(H.yellow("- Sui localnode on port 9000")),console.error(H.yellow("- Sui faucet on port 9123")),console.error(H.yellow("- PostgreSQL database on port 5432")),console.error(H.yellow("- Dubhe GraphQL server on port 4000"))):console.error(H.yellow("Please make sure the service is running...")),process.exit(1)}}},dt=qo;var Bo={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 W(e.network)}},ut=Bo;import Ko from"dotenv";import J from"chalk";Ko.config();var Yo={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=j({network:e}),o=t.getSigner();console.log(J.blue("Account Information:")),console.log(` Network: ${J.green(e)}`),console.log(` Address: ${J.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${J.green(s)} SUI`)}catch{console.log(` Balance: ${J.red("Failed to fetch balance")} ${J.gray("(Network error)")}`)}}catch(t){M(t),process.exit(1)}}},pt=Yo;import{loadConfig as Go}from"@0xobelisk/sui-common";async function gt(e,t,o){if(o)await Z(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await le(n,t);await Z(e.name,t,s)}}var Jo={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 Go(t);await gt(n,e,o)}catch(n){M(n),process.exit(1)}process.exit(0)}},mt=Jo;import i from"chalk";import{spawn as Zo}from"child_process";import bt from"cli-table3";import fe from"inquirer";import*as x from"fs";import*as D from"path";import*as K from"os";import*as vt from"net";import en from"axios";import me from"chalk";import*as ft from"cli-progress";import*as ht from"fs";import Xo from"axios";async function yt(e,t){try{let o=await Xo.get(e,{responseType:"stream",timeout:3e4,headers:{"User-Agent":"dubhe-cli"},maxRedirects:5,validateStatus:n=>n<400});await Qo(o,t),console.log(me.green(" \u2713 Successfully downloaded"))}catch(o){if(o.code==="ENOTFOUND")throw new Error(`DNS resolution failed: ${o.message}. Please check your internet connection.`);if(o.code==="ECONNRESET")throw new Error(`Connection reset: ${o.message}. Please check your network connection.`);if(o.code==="ETIMEDOUT")throw new Error(`Connection timeout: ${o.message}. Please check your network connection.`);if(o.message.includes("protocol mismatch"))throw new Error(`Protocol mismatch: ${o.message}. Please check your network configuration.`);if(o.response)throw new Error(`HTTP ${o.response.status}: ${o.response.statusText}`);{let n=o instanceof Error?o.message:String(o);throw new Error(`Download failed: ${n}`)}}}async function Qo(e,t){let o=parseInt(e.headers["content-length"]||"0"),n=new ft.SingleBar({format:me.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});o>0?n.start(Math.round(o/1024/1024*100)/100,0,{speed:"0.00"}):console.log(me.blue("\u{1F4E5} Downloading... (unable to get file size)"));let s=ht.createWriteStream(t),r=0,a=Date.now();return new Promise((u,d)=>{e.data.on("data",c=>{if(r+=c.length,o>0){let g=Math.round(r/1024/1024*100)/100,f=(Date.now()-a)/1e3,h=f>0?Math.round(g/f*100)/100:0;n.update(g,{speed:h.toFixed(2)})}}),e.data.pipe(s),s.on("finish",()=>{o>0&&n.stop();let c=Math.round(r/1024/1024*100)/100,g=(Date.now()-a)/1e3,f=g>0?Math.round(c/g*100)/100:0;console.log(me.green(`\u2713 Download completed! ${c} MB, average speed: ${f} MB/s`)),u()}),s.on("error",c=>{o>0&&n.stop(),d(c)})})}function Se(){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 A={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:D.join(K.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe",binaryName:"dubhe-indexer",installDir:D.join(K.homedir(),".dubhe","bin")}};async function V(e,t=[]){return new Promise(o=>{let n=Zo(e,t,{shell:!0}),s="",r="";n.stdout?.on("data",a=>{s+=a.toString()}),n.stderr?.on("data",a=>{r+=a.toString()}),n.on("close",a=>{o({code:a||0,stdout:s,stderr:r})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:r})})})}async function xt(e,t={}){try{let o={timeout:3e4,maxRedirects:5,validateStatus:s=>s<500,...t},n=await en(e,o);return{ok:n.status>=200&&n.status<300,status:n.status,statusText:n.statusText,json:async()=>n.data,headers:n.headers}}catch(o){let n=o.response?.status||0,s=o.response?.statusText||o.message;return o.code==="ENOTFOUND"?s="DNS resolution failed - please check your internet connection":o.code==="ECONNRESET"?s="Connection reset - please check your network connection":o.code==="ETIMEDOUT"?s="Connection timeout - please check your network connection":o.message.includes("protocol mismatch")&&(s="Protocol mismatch - please check your network configuration"),{ok:!1,status:n,statusText:s,json:async()=>o.response?.data||{},headers:o.response?.headers||{}}}}async function Pe(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(i.gray(` Retry ${s}/${o}...`));let r=await xt(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(i.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${r instanceof Error?r.message:String(r)}`)),s===o)return console.error(i.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(a=>setTimeout(a,1e3*s))}return[]}function ne(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"]:[]],a=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],u=r.some(g=>s.includes(g)),d=a.some(g=>s.includes(g)),c=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return u&&d&&c}).map(n=>n.name)}async function tn(e,t){let o=A[e];return o?(await Pe(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:ne(s,t).length>0})):[]}async function on(e){try{let t=se();if(!t){console.log(i.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(x.existsSync(n)&&x.readFileSync(n,"utf8").includes(e)){console.log(i.green(` \u2713 PATH already configured in ${n}`));return}let a=`# Added by dubhe doctor
68
- ${s}`;x.appendFileSync(n,`
69
- ${a}
70
- `),console.log(i.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(i.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(i.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(i.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function se(){let e=K.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:D.join(e,".zshrc")};if(t.includes("bash")){let n=D.join(e,".bash_profile"),s=D.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&x.existsSync(n)?n:s}}else if(t.includes("fish")){let n=D.join(e,".config","fish");return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:D.join(n,"config.fish")}}}let o=[{name:"zsh",file:D.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?D.join(e,".bash_profile"):D.join(e,".bashrc")},{name:"bash",file:D.join(e,".bashrc")}];for(let n of o)if(x.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||x.existsSync("/bin/zsh")?{shellName:"zsh",configFile:D.join(e,".zshrc")}:null}async function $e(e,t){let o=A[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=Se();console.log(i.gray(` System: ${n.platform}/${n.arch}`));try{console.log(i.gray(" Fetching release information..."));let s=await Pe(o.repo,10);if(s.length===0)return console.error(i.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let r=null;if(t){if(t.startsWith("v")||(t=`v${t}`),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(ne(l,n).length>0){r=l;break}if(!r)return console.error("No compatible version found"),!1;let a=ne(r,n);if(a.length===0)return console.error(`Version ${r.tag_name} has no compatible binaries`),!1;let u=a[0],d=r.assets.find(l=>l.name===u);if(!d)return console.error(`Asset file not found: ${u}`),!1;console.log(i.green(` \u2713 Found compatible version: ${r.tag_name}`)),console.log(i.gray(` Download file: ${d.name}`));try{let l=await xt(d.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(i.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let k=l.headers["content-length"];k&&console.log(i.gray(` File size: ${Math.round(parseInt(k)/1024/1024*100)/100} MB`))}}catch{console.log(i.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}x.existsSync(o.installDir)||(x.mkdirSync(o.installDir,{recursive:!0}),console.log(i.gray(` Created install directory: ${o.installDir}`))),console.log(i.blue(" \u{1F4E5} Downloading..."));let c=D.join(K.tmpdir(),d.name),g=3;for(let l=1;l<=g;l++)try{l>1&&console.log(i.gray(` Attempt ${l} to download...`)),await yt(d.browser_download_url,c);break}catch(k){let p=k instanceof Error?k.message:String(k);if(console.log(i.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${p}`)),l===g)throw new Error(`Download failed after ${g} attempts: ${p}`);console.log(i.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(y=>setTimeout(y,l*2e3))}console.log(i.blue(" \u{1F4E6} Extracting and installing..."));let f=D.join(K.tmpdir(),`extract_${Date.now()}`);if(x.mkdirSync(f,{recursive:!0}),d.name.endsWith(".tar.gz")||d.name.endsWith(".tgz")){let l=await V("tar",["-xzf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.bz2")){let l=await V("tar",["-xjf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.xz")){let l=await V("tar",["-xJf",c,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".zip")){let l=await V("unzip",["-q",c,"-d",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${d.name}`);let h=l=>{let k=x.readdirSync(l,{withFileTypes:!0});for(let p of k){let y=D.join(l,p.name);if(p.isDirectory()){let $=h(y);if($)return $}else if(p.name===o.binaryName||p.name===`${o.binaryName}.exe`)return y}return null},b=h(f);if(!b)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let P=D.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return x.copyFileSync(b,P),process.platform!=="win32"&&x.chmodSync(P,493),x.rmSync(c,{force:!0}),x.rmSync(f,{recursive:!0,force:!0}),console.log(i.green(" \u2705 Installation completed!")),console.log(i.gray(` Location: ${P}`)),console.log(i.gray(` Version: ${r.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(i.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(i.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await on(o.installDir)),!0}catch(s){return console.error(i.red(`\u274C Installation failed: ${s}`)),!1}}async function nn(e){let t=Se(),o=await tn(e,t);if(o.length===0)return console.log(i.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(i.red("No compatible versions found for current system")),null;console.log(i.blue(`
71
- \u{1F4CB} Select version for ${e}`)),console.log(i.gray(`System: ${t.platform}/${t.arch}`)),console.log(i.gray(`Compatible versions (latest 5):
72
- `));let s=n.map((r,a)=>({name:`${r.version} ${a===0?i.green("(latest)"):i.gray("(available)")}`,value:r.version,short:r.version}));try{let r=await fe.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new fe.Separator,{name:i.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return r.version==="cancel"?(console.log(i.gray("Installation cancelled")),null):r.version}catch{return console.log(i.gray(`
73
- Installation cancelled`)),null}}function he(e){let t=A[e];if(!t)return!1;let o=D.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return x.existsSync(o)}async function sn(){try{let e=R.version,t=await V("dubhe-indexer",["--version"]);if(t.code!==0)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot get dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let o=t.stdout.trim().match(/dubhe-indexer\s+(\S+)/);if(!o)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot parse dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let n=o[1];return e===n?{name:"Dubhe-indexer Version Consistency",status:"success",message:`Versions match (${e})`}:{name:"Dubhe-indexer Version Consistency",status:"warning",message:`Version mismatch: sui-cli ${e}, dubhe-indexer ${n}`,fixSuggestion:`Consider reinstalling dubhe-indexer to match sui-cli version ${e}`}}catch{return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Version check failed",fixSuggestion:"Unable to verify version consistency"}}}async function oe(e,t="--version"){try{let o=await V(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
74
- `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(he(e)){let n=se(),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:wt(e)}}}catch{if(he(e)){let n=se(),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:wt(e)}}}function wt(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function rn(){try{let e=await V("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 an(){try{return(await V("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 ln(){try{let e=await V("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}async function Ct(e){let t=["127.0.0.1","0.0.0.0"];for(let o of t)if(!await cn(e,o))return!1;return!0}async function cn(e,t){return new Promise(o=>{let n=vt.createServer(),s=setTimeout(()=>{n.close(),o(!1)},2e3);n.listen(e,t,()=>{clearTimeout(s),n.close(()=>{o(!0)})}),n.on("error",r=>{clearTimeout(s),n.close(),r.code,o(!1)})})}async function dn(){try{return await Ct(5432)?{name:"PostgreSQL Port (5432)",status:"success",message:"Available"}:{name:"PostgreSQL Port (5432)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"PostgreSQL Port (5432)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}async function un(){try{return await Ct(4e3)?{name:"GraphQL Server Port (4000)",status:"success",message:"Available"}:{name:"GraphQL Server Port (4000)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"GraphQL Server Port (4000)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}function pn(e){let t={success:i.green("\u2713"),warning:i.yellow("!"),error:i.red("\u2717")},o={success:i.green("Pass"),warning:i.yellow("Warning"),error:i.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 gn(e){if(console.log(i.bold.blue(`
74
+ `;Zo(s,o,"storeConfig")}async function Zo(e,t,o){Go(Xo(t),{recursive:!0}),Jo(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function yt(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await W(s,t);await Qo(r.network,r.packageId,o)}import{loadConfig as en}from"@0xobelisk/sui-common";import tn from"chalk";var on={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","default"],default:"default",desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{t=="default"&&(t=await D(),console.log(tn.yellow(`Use default network: [${t}]`)));let n=await en(e);await yt(n,t,o)}catch(n){console.error("Error storing config:",n),g(1)}g()}},bt=on;import nn from"chokidar";import{exec as sn}from"child_process";var rn={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{sn("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=nn.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(`
75
+ Watch stopped.`),g()})}},wt=rn;import De from"wait-on";import oe from"ora";import G from"chalk";import an from"net";function Ie(e){let t={HTTP_PROXY:process.env.HTTP_PROXY,HTTPS_PROXY:process.env.HTTPS_PROXY,http_proxy:process.env.http_proxy,https_proxy:process.env.https_proxy,NO_PROXY:process.env.NO_PROXY,no_proxy:process.env.no_proxy};try{return delete process.env.HTTP_PROXY,delete process.env.HTTPS_PROXY,delete process.env.http_proxy,delete process.env.https_proxy,process.env.NO_PROXY="127.0.0.1,localhost,*.local",process.env.no_proxy="127.0.0.1,localhost,*.local",e()}finally{Object.keys(t).forEach(o=>{let n=t[o];n!==void 0?process.env[o]=n:delete process.env[o]})}}async function vt(){return xt(5432)}async function xt(e,t="127.0.0.1"){return new Promise(o=>{let n=new an.Socket,s=!1,r=setTimeout(()=>{n.destroy(),s||o(!1)},2e3);n.connect(e,t,()=>{s=!0,clearTimeout(r),n.destroy(),o(!0)}),n.on("error",()=>{clearTimeout(r),s||o(!1)})})}async function ln(){try{return await Ie(()=>De({resources:["http://127.0.0.1:8080/health"],timeout:2e3,interval:500,validateStatus:e=>e===200})),!0}catch{return!1}}async function cn(e){let t=oe({text:"Waiting for dubhe localnet services...",color:"cyan"});t.start();let o=Date.now();for(;Date.now()-o<e.timeout;){try{if(await Ie(()=>De({resources:["http://127.0.0.1:9123","http://127.0.0.1:4000"],timeout:e.interval,interval:500,validateStatus:s=>s===200})),await vt()){t.succeed(G.green("All dubhe localnet services are ready!"));return}}catch{}await new Promise(n=>setTimeout(n,e.interval))}throw new Error("Timeout waiting for services")}async function dn(e){let t=oe({text:"Waiting for local database...",color:"cyan"});t.start();let o=Date.now();for(;Date.now()-o<e.timeout;){if(await vt()){t.succeed(G.green("Local database is ready!"));return}await new Promise(s=>setTimeout(s,e.interval))}throw new Error("Timeout waiting for local database")}async function un(e){let t=oe({text:"Waiting for local Sui node...",color:"cyan"});t.start();let o=Date.now();for(;Date.now()-o<e.timeout;){if(await xt(9123)){t.succeed(G.green("Local Sui node is ready!"));return}await new Promise(s=>setTimeout(s,e.interval))}throw new Error("Timeout waiting for local Sui node")}async function pn(e){let t=oe({text:"Waiting for local indexer...",color:"cyan"});t.start();let o=Date.now();for(;Date.now()-o<e.timeout;){if(await ln()){t.succeed(G.green("Local indexer is ready!"));return}await new Promise(s=>setTimeout(s,e.interval))}throw new Error("Timeout waiting for local indexer")}var mn={command:"wait",describe:"Wait for service(s) to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for (single service)"}).option("localnet",{type:"boolean",description:"Wait for all dubhe localnet services (sui localnode:9000&9123, postgres:5432, graphql:4000)",default:!1}).option("local-database",{type:"boolean",description:"Wait for local database (PostgreSQL on port 5432)",default:!1}).option("local-node",{type:"boolean",description:"Wait for local Sui node (port 9123)",default:!1}).option("local-indexer",{type:"boolean",description:"Wait for local indexer (health check at http://127.0.0.1:8080/health)",default:!1}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:24*60*60*1e3}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3}).check(t=>{let o=!!t.url,n=!!t.localnet,s=!!t["local-database"],r=!!t["local-node"],i=!!t["local-indexer"],c=[o,n,s,r,i].filter(Boolean).length;if(c===0)throw new Error("Please provide at least one option: --url, --localnet, --local-database, --local-node, or --local-indexer");if(o&&c>1)throw new Error("Cannot use --url together with other options");if(n&&(s||r||i))throw new Error("Cannot use --localnet together with individual service options");return!0})},async handler(e){let t=e;try{if(t.localnet)await cn(t);else if(t["local-database"])await dn(t);else if(t["local-node"])await un(t);else if(t["local-indexer"])await pn(t);else{let o=oe({text:`Waiting for ${t.url}...`,color:"cyan"});o.start(),await Ie(()=>De({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200})),o.succeed(G.green("Service is ready!"))}g()}catch{let n=oe(),s="Timeout waiting for service",r="Please make sure the service is running...";t.localnet?(s="Timeout waiting for dubhe localnet services",r=`Please make sure all required services are running:
76
+ - Sui localnode on port 9000
77
+ - Sui faucet on port 9123
78
+ - PostgreSQL database on port 5432
79
+ - Dubhe GraphQL server on port 4000`):t["local-database"]?(s="Timeout waiting for local database",r="Please make sure PostgreSQL is running on port 5432"):t["local-node"]?(s="Timeout waiting for local Sui node",r="Please make sure Sui localnode is running on port 9123"):t["local-indexer"]&&(s="Timeout waiting for local indexer",r="Please make sure indexer is running and health endpoint is available at http://127.0.0.1:8080/health"),n.fail(G.red(s)),console.error(G.yellow(r)),g(1)}}},Ct=mn;var gn={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 q(e.network),g()}},$t=gn;import fn from"dotenv";import J from"chalk";fn.config();var hn={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{e=="default"&&(e=await D(),console.log(J.yellow(`Use default network: [${e}]`)));let t=H({network:e}),o=t.getSigner();console.log(J.blue("Account Information:")),console.log(` Network: ${J.green(e)}`),console.log(` Address: ${J.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${J.green(s)} SUI`)}catch{console.log(` Balance: ${J.red("Failed to fetch balance")} ${J.gray("(Network error)")}`)}g()}catch(t){j(t),g(1)}}},kt=hn;import{loadConfig as yn}from"@0xobelisk/sui-common";async function St(e,t,o){if(o)await re(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await me(n,t);await re(e.name,t,s)}}import bn from"chalk";var wn={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0}})},async handler({network:e,"config-path":t,"package-id":o}){try{e=="default"&&(e=await D(),console.log(bn.yellow(`Use default network: [${e}]`)));let n=await yn(t);await St(n,e,o)}catch(n){j(n),g(1)}g()}},Pt=wn;import a from"chalk";import{spawn as Cn}from"child_process";import Dt from"cli-table3";import ve from"inquirer";import*as C from"fs";import*as I from"path";import*as X from"os";import*as At from"net";import $n from"axios";import we from"chalk";import*as _t from"cli-progress";import*as Et from"fs";import vn from"axios";async function Tt(e,t){try{let o=await vn.get(e,{responseType:"stream",timeout:3e4,headers:{"User-Agent":"dubhe-cli"},maxRedirects:5,validateStatus:n=>n<400});await xn(o,t),console.log(we.green(" \u2713 Successfully downloaded"))}catch(o){if(o.code==="ENOTFOUND")throw new Error(`DNS resolution failed: ${o.message}. Please check your internet connection.`);if(o.code==="ECONNRESET")throw new Error(`Connection reset: ${o.message}. Please check your network connection.`);if(o.code==="ETIMEDOUT")throw new Error(`Connection timeout: ${o.message}. Please check your network connection.`);if(o.message.includes("protocol mismatch"))throw new Error(`Protocol mismatch: ${o.message}. Please check your network configuration.`);if(o.response)throw new Error(`HTTP ${o.response.status}: ${o.response.statusText}`);{let n=o instanceof Error?o.message:String(o);throw new Error(`Download failed: ${n}`)}}}async function xn(e,t){let o=parseInt(e.headers["content-length"]||"0"),n=new _t.SingleBar({format:we.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});o>0?n.start(Math.round(o/1024/1024*100)/100,0,{speed:"0.00"}):console.log(we.blue("\u{1F4E5} Downloading... (unable to get file size)"));let s=Et.createWriteStream(t),r=0,i=Date.now();return new Promise((c,d)=>{e.data.on("data",l=>{if(r+=l.length,o>0){let m=Math.round(r/1024/1024*100)/100,p=(Date.now()-i)/1e3,y=p>0?Math.round(m/p*100)/100:0;n.update(m,{speed:y.toFixed(2)})}}),e.data.pipe(s),s.on("finish",()=>{o>0&&n.stop();let l=Math.round(r/1024/1024*100)/100,m=(Date.now()-i)/1e3,p=m>0?Math.round(l/m*100)/100:0;console.log(we.green(`\u2713 Download completed! ${l} MB, average speed: ${p} MB/s`)),c()}),s.on("error",l=>{o>0&&n.stop(),d(l)})})}function Ne(){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 M={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:I.join(X.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe",binaryName:"dubhe-indexer",installDir:I.join(X.homedir(),".dubhe","bin")}};async function L(e,t=[]){return new Promise(o=>{let n=Cn(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 Nt(e,t={}){try{let o={timeout:3e4,maxRedirects:5,validateStatus:s=>s<500,...t},n=await $n(e,o);return{ok:n.status>=200&&n.status<300,status:n.status,statusText:n.statusText,json:async()=>n.data,headers:n.headers}}catch(o){let n=o.response?.status||0,s=o.response?.statusText||o.message;return o.code==="ENOTFOUND"?s="DNS resolution failed - please check your internet connection":o.code==="ECONNRESET"?s="Connection reset - please check your network connection":o.code==="ETIMEDOUT"?s="Connection timeout - please check your network connection":o.message.includes("protocol mismatch")&&(s="Protocol mismatch - please check your network configuration"),{ok:!1,status:n,statusText:s,json:async()=>o.response?.data||{},headers:o.response?.headers||{}}}}async function Oe(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 Nt(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 ce(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(m=>s.includes(m)),d=i.some(m=>s.includes(m)),l=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return c&&d&&l}).map(n=>n.name)}async function kn(e,t){let o=M[e];return o?(await Oe(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:ce(s,t).length>0})):[]}async function Sn(e){try{let t=de();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(C.existsSync(n)&&C.readFileSync(n,"utf8").includes(e)){console.log(a.green(` \u2713 PATH already configured in ${n}`));return}let i=`# Added by dubhe doctor
80
+ ${s}`;C.appendFileSync(n,`
81
+ ${i}
82
+ `),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 de(){let e=X.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:I.join(e,".zshrc")};if(t.includes("bash")){let n=I.join(e,".bash_profile"),s=I.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&C.existsSync(n)?n:s}}else if(t.includes("fish")){let n=I.join(e,".config","fish");return C.existsSync(n)||C.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:I.join(n,"config.fish")}}}let o=[{name:"zsh",file:I.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?I.join(e,".bash_profile"):I.join(e,".bashrc")},{name:"bash",file:I.join(e,".bashrc")}];for(let n of o)if(C.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||C.existsSync("/bin/zsh")?{shellName:"zsh",configFile:I.join(e,".zshrc")}:null}async function Ae(e,t){let o=M[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=Ne();console.log(a.gray(` System: ${n.platform}/${n.arch}`));try{console.log(a.gray(" Fetching release information..."));let s=await Oe(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(t.startsWith("v")||(t=`v${t}`),r=s.find(u=>u.tag_name===t)||null,!r)return console.error(`Version ${t} not found`),!1}else for(let u of s)if(ce(u,n).length>0){r=u;break}if(!r)return console.error("No compatible version found"),!1;let i=ce(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(u=>u.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 u=await Nt(d.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!u.ok)console.log(a.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${u.status})`));else{let k=u.headers["content-length"];k&&console.log(a.gray(` File size: ${Math.round(parseInt(k)/1024/1024*100)/100} MB`))}}catch{console.log(a.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}C.existsSync(o.installDir)||(C.mkdirSync(o.installDir,{recursive:!0}),console.log(a.gray(` Created install directory: ${o.installDir}`))),console.log(a.blue(" \u{1F4E5} Downloading..."));let l=I.join(X.tmpdir(),d.name),m=3;for(let u=1;u<=m;u++)try{u>1&&console.log(a.gray(` Attempt ${u} to download...`)),await Tt(d.browser_download_url,l);break}catch(k){let f=k instanceof Error?k.message:String(k);if(console.log(a.yellow(` \u26A0\uFE0F Download failed (attempt ${u}): ${f}`)),u===m)throw new Error(`Download failed after ${m} attempts: ${f}`);console.log(a.gray(` Waiting ${u*2} seconds before retry...`)),await new Promise(w=>setTimeout(w,u*2e3))}console.log(a.blue(" \u{1F4E6} Extracting and installing..."));let p=I.join(X.tmpdir(),`extract_${Date.now()}`);if(C.mkdirSync(p,{recursive:!0}),d.name.endsWith(".tar.gz")||d.name.endsWith(".tgz")){let u=await L("tar",["-xzf",l,"-C",p]);if(u.code!==0)throw new Error(`Extraction failed: ${u.stderr}`)}else if(d.name.endsWith(".tar.bz2")){let u=await L("tar",["-xjf",l,"-C",p]);if(u.code!==0)throw new Error(`Extraction failed: ${u.stderr}`)}else if(d.name.endsWith(".tar.xz")){let u=await L("tar",["-xJf",l,"-C",p]);if(u.code!==0)throw new Error(`Extraction failed: ${u.stderr}`)}else if(d.name.endsWith(".zip")){let u=await L("unzip",["-q",l,"-d",p]);if(u.code!==0)throw new Error(`Extraction failed: ${u.stderr}`)}else throw new Error(`Unsupported compression format: ${d.name}`);let y=u=>{let k=C.readdirSync(u,{withFileTypes:!0});for(let f of k){let w=I.join(u,f.name);if(f.isDirectory()){let S=y(w);if(S)return S}else if(f.name===o.binaryName||f.name===`${o.binaryName}.exe`)return w}return null},b=y(p);if(!b)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let P=I.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return C.copyFileSync(b,P),process.platform!=="win32"&&C.chmodSync(P,493),C.rmSync(l,{force:!0}),C.rmSync(p,{recursive:!0,force:!0}),console.log(a.green(" \u2705 Installation completed!")),console.log(a.gray(` Location: ${P}`)),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 Sn(o.installDir)),!0}catch(s){return console.error(a.red(`\u274C Installation failed: ${s}`)),!1}}async function Pn(e){let t=Ne(),o=await kn(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(`
83
+ \u{1F4CB} Select version for ${e}`)),console.log(a.gray(`System: ${t.platform}/${t.arch}`)),console.log(a.gray(`Compatible versions (latest 5):
84
+ `));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 ve.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new ve.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(`
85
+ Installation cancelled`)),null}}function xe(e){let t=M[e];if(!t)return!1;let o=I.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return C.existsSync(o)}async function _n(){try{let e=U.version,t=await L("dubhe-indexer",["--version"]);if(t.code!==0)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot get dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let o=t.stdout.trim().match(/dubhe-indexer\s+(\S+)/);if(!o)return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Cannot parse dubhe-indexer version",fixSuggestion:"Unable to verify version consistency"};let n=o[1];return e===n?{name:"Dubhe-indexer Version Consistency",status:"success",message:`Versions match (${e})`}:{name:"Dubhe-indexer Version Consistency",status:"warning",message:`Version mismatch: sui-cli ${e}, dubhe-indexer ${n}`,fixSuggestion:`Consider reinstalling dubhe-indexer to match sui-cli version ${e}`}}catch{return{name:"Dubhe-indexer Version Consistency",status:"warning",message:"Version check failed",fixSuggestion:"Unable to verify version consistency"}}}async function le(e,t="--version"){try{let o=await L(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
86
+ `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(xe(e)){let n=de(),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:It(e)}}}catch{if(xe(e)){let n=de(),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:It(e)}}}function It(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function En(){try{let e=await L("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 Tn(){try{return(await L("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 Dn(){try{let e=await L("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}async function Ot(e){let t=["127.0.0.1","0.0.0.0"];for(let o of t)if(!await In(e,o))return!1;return!0}async function In(e,t){return new Promise(o=>{let n=At.createServer(),s=setTimeout(()=>{n.close(),o(!1)},2e3);n.listen(e,t,()=>{clearTimeout(s),n.close(()=>{o(!0)})}),n.on("error",r=>{clearTimeout(s),n.close(),r.code,o(!1)})})}async function An(){try{return await Ot(5432)?{name:"PostgreSQL Port (5432)",status:"success",message:"Available"}:{name:"PostgreSQL Port (5432)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"PostgreSQL Port (5432)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}async function Nn(){try{return await Ot(4e3)?{name:"GraphQL Server Port (4000)",status:"success",message:"Available"}:{name:"GraphQL Server Port (4000)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"GraphQL Server Port (4000)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}function On(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 Mn(e){if(console.log(a.bold.blue(`
75
87
  \u{1F50D} Dubhe Doctor - Development Environment Checker
76
- `)),e.listVersions){let p=e.listVersions;A[p]||(console.error(i.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(i.blue(`\u{1F4CB} Available versions for ${p}:`));let y=Se();console.log(i.gray(`System: ${y.platform}/${y.arch}
77
- `));let $=A[p],I=await Pe($.repo,10);I.length===0&&(console.log(i.red("Unable to get version information")),process.exit(1));let S=I.map(m=>({version:m.tag_name,hasCompatibleAsset:ne(m,y).length>0,publishDate:new Date(m.published_at).toLocaleDateString("en-US")})),_=new bt({head:[i.bold.cyan("Version"),i.bold.cyan("Compatibility"),i.bold.cyan("Release Date")],colWidths:[30,15,25]});if(S.forEach(m=>{_.push([m.version,m.hasCompatibleAsset?i.green("\u2713 Compatible"):i.red("\u2717 Incompatible"),m.publishDate])}),console.log(_.toString()),e.debug&&S.length>0){console.log(i.blue(`
78
- \u{1F50D} Debug Information:`));let m=S.find(v=>v.hasCompatibleAsset);if(m){let v=I.find(w=>w.tag_name===m.version);if(v){console.log(i.gray(`Latest compatible version: ${m.version}`)),console.log(i.gray("Available asset files:")),v.assets.forEach(U=>{console.log(i.gray(` - ${U.name}`))});let w=ne(v,y);console.log(i.gray("Compatible asset files:")),w.forEach(U=>{console.log(i.green(` \u2713 ${U}`))})}}}process.exit(0)}if(console.log(i.gray(`Checking your development environment...
79
- `)),e.install){let p=e.install;A[p]||(console.error(i.red(`\u274C Unsupported tool: ${p}`)),console.log(i.gray(`Supported tools: ${Object.keys(A).join(", ")}`)),process.exit(1));let y=null;e.selectVersion?(y=await nn(p),y||process.exit(1)):p==="dubhe-indexer"&&(y=R.version,console.log(i.blue(`\u{1F4E6} Installing dubhe-indexer version ${y} (matching sui-cli version)`)));let $=await $e(p,y||void 0);process.exit($?0:1)}let t=[];console.log(`Running checks...
80
- `);let o=await rn();t.push(o);let n=await oe("pnpm");t.push(n);let s=await ln();s.status==="error"&&(s.status="warning"),t.push(s);let r=await oe("docker");t.push(r);let a=null;r.status==="success"&&(a=await an(),t.push(a));let u=await oe("docker-compose");t.push(u);let d=await oe("sui");t.push(d);let c=await oe("dubhe-indexer");if(t.push(c),c.status==="success"){let p=await sn();t.push(p)}let g=await dn();t.push(g);let f=await un();t.push(f);let h=new bt({head:[i.bold.cyan("Check Item"),i.bold.cyan("Result"),i.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(pn(p))}),console.log(h.toString());let b={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(`
81
- `+i.bold("\u{1F4CA} Check Summary:")),console.log(` ${i.green("\u2713 Passed:")} ${b.success} items`),console.log(` ${i.yellow("! Warning:")} ${b.warning} items`),console.log(` ${i.red("\u2717 Failed:")} ${b.error} items`);let P=t.find(p=>p.name==="Dubhe-indexer Version Consistency"&&p.status==="warning"&&p.message.includes("Version mismatch"));if(P){console.log(i.yellow(`
82
- \u26A0\uFE0F Dubhe-indexer version inconsistency detected!`)),console.log(i.gray(` ${P.message}`));try{(await fe.prompt([{type:"confirm",name:"reinstallDubheIndexer",message:"Would you like to reinstall dubhe-indexer to match the sui-cli version?",default:!0}])).reinstallDubheIndexer?(console.log(i.blue(`
88
+ `)),e.listVersions){let f=e.listVersions;M[f]||(console.error(a.red(`\u274C Unsupported tool: ${f}`)),g(1)),console.log(a.blue(`\u{1F4CB} Available versions for ${f}:`));let w=Ne();console.log(a.gray(`System: ${w.platform}/${w.arch}
89
+ `));let S=M[f],N=await Oe(S.repo,10);N.length===0&&(console.log(a.red("Unable to get version information")),g(1));let _=N.map(h=>({version:h.tag_name,hasCompatibleAsset:ce(h,w).length>0,publishDate:new Date(h.published_at).toLocaleDateString("en-US")})),E=new Dt({head:[a.bold.cyan("Version"),a.bold.cyan("Compatibility"),a.bold.cyan("Release Date")],colWidths:[30,15,25]});if(_.forEach(h=>{E.push([h.version,h.hasCompatibleAsset?a.green("\u2713 Compatible"):a.red("\u2717 Incompatible"),h.publishDate])}),console.log(E.toString()),e.debug&&_.length>0){console.log(a.blue(`
90
+ \u{1F50D} Debug Information:`));let h=_.find(x=>x.hasCompatibleAsset);if(h){let x=N.find(v=>v.tag_name===h.version);if(x){console.log(a.gray(`Latest compatible version: ${h.version}`)),console.log(a.gray("Available asset files:")),x.assets.forEach(V=>{console.log(a.gray(` - ${V.name}`))});let v=ce(x,w);console.log(a.gray("Compatible asset files:")),v.forEach(V=>{console.log(a.green(` \u2713 ${V}`))})}}}g()}if(console.log(a.gray(`Checking your development environment...
91
+ `)),e.install){let f=e.install;M[f]||(console.error(a.red(`\u274C Unsupported tool: ${f}`)),console.log(a.gray(`Supported tools: ${Object.keys(M).join(", ")}`)),g(1));let w=null;e.selectVersion?(w=await Pn(f),w||g(1)):f==="dubhe-indexer"&&(w=U.version,console.log(a.blue(`\u{1F4E6} Installing dubhe-indexer version ${w} (matching sui-cli version)`)));let S=await Ae(f,w||void 0);g(S?0:1)}let t=[];console.log(`Running checks...
92
+ `);let o=await En();t.push(o);let n=await le("pnpm");t.push(n);let s=await Dn();s.status==="error"&&(s.status="warning"),t.push(s);let r=await le("docker");t.push(r);let i=null;r.status==="success"&&(i=await Tn(),t.push(i));let c=await le("docker-compose");t.push(c);let d=await le("sui");t.push(d);let l=await le("dubhe-indexer");if(t.push(l),l.status==="success"){let f=await _n();t.push(f)}let m=await An();t.push(m);let p=await Nn();t.push(p);let y=new Dt({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(f=>{y.push(On(f))}),console.log(y.toString());let b={success:t.filter(f=>f.status==="success").length,warning:t.filter(f=>f.status==="warning").length,error:t.filter(f=>f.status==="error").length};console.log(`
93
+ `+a.bold("\u{1F4CA} Check Summary:")),console.log(` ${a.green("\u2713 Passed:")} ${b.success} items`),console.log(` ${a.yellow("! Warning:")} ${b.warning} items`),console.log(` ${a.red("\u2717 Failed:")} ${b.error} items`);let P=t.find(f=>f.name==="Dubhe-indexer Version Consistency"&&f.status==="warning"&&f.message.includes("Version mismatch"));if(P){console.log(a.yellow(`
94
+ \u26A0\uFE0F Dubhe-indexer version inconsistency detected!`)),console.log(a.gray(` ${P.message}`));try{(await ve.prompt([{type:"confirm",name:"reinstallDubheIndexer",message:"Would you like to reinstall dubhe-indexer to match the sui-cli version?",default:!0}])).reinstallDubheIndexer?(console.log(a.blue(`
83
95
  \u{1F4E6} Reinstalling dubhe-indexer...
84
- `)),console.log(i.blue(`${"=".repeat(60)}`)),console.log(i.blue("\u{1F4E6} Installing dubhe-indexer...")),console.log(i.blue(`${"=".repeat(60)}`)),await $e("dubhe-indexer",R.version)?(console.log(i.green(`
85
- \u2705 Dubhe-indexer reinstallation completed successfully!`)),console.log(i.blue(" Please restart your terminal or run: source ~/.zshrc (or ~/.bashrc)")),console.log(i.blue(" Then run: dubhe doctor to verify the installation"))):(console.log(i.red(`
86
- \u274C Dubhe-indexer reinstallation failed`)),console.log(i.gray(" You can try manual installation: dubhe doctor --install dubhe-indexer")))):(console.log(i.gray(`
87
- Version inconsistency ignored. You can reinstall later with:`)),console.log(i.gray(" dubhe doctor --install dubhe-indexer")))}catch{console.log(i.gray(`
88
- Version inconsistency check cancelled.`))}}let E=t.filter(p=>p.status==="error"),l=E.filter(p=>A[p.name]),k=E.filter(p=>!A[p.name]);if(k.length>0&&(console.log(i.blue(`
89
- \u{1F527} Missing tools that require manual installation:`)),k.forEach(p=>{console.log(` ${i.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),l.length>0){let p=l.filter($=>he($.name)),y=l.filter($=>!he($.name));if(p.length>0){let $=p.map(m=>m.name).join(", "),I=A[p[0].name]?.installDir||"~/.dubhe/bin",S=se(),_=S?S.configFile:"~/.zshrc (or ~/.bashrc)";console.log(i.yellow(`
90
- \u26A0\uFE0F Tools already installed but not in PATH: ${$}`)),console.log(i.gray(` Location: ${I}`)),console.log(i.blue(" To fix this, apply PATH changes:")),console.log(i.green(` source ${_}`)),console.log(i.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(i.gray(` If you want to reinstall, remove the files from ${I} and run dubhe doctor again`))}if(y.length>0){let $=y.map(I=>I.name).join(", ");console.log(i.blue(`
91
- \u{1F680} Auto-installable tools detected: ${$}`));try{if((await fe.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${$})`,default:!0}])).installAll){console.log(i.blue(`
96
+ `)),console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.blue("\u{1F4E6} Installing dubhe-indexer...")),console.log(a.blue(`${"=".repeat(60)}`)),await Ae("dubhe-indexer",U.version)?(console.log(a.green(`
97
+ \u2705 Dubhe-indexer reinstallation completed successfully!`)),console.log(a.blue(" Please restart your terminal or run: source ~/.zshrc (or ~/.bashrc)")),console.log(a.blue(" Then run: dubhe doctor to verify the installation"))):(console.log(a.red(`
98
+ \u274C Dubhe-indexer reinstallation failed`)),console.log(a.gray(" You can try manual installation: dubhe doctor --install dubhe-indexer")))):(console.log(a.gray(`
99
+ Version inconsistency ignored. You can reinstall later with:`)),console.log(a.gray(" dubhe doctor --install dubhe-indexer")))}catch{console.log(a.gray(`
100
+ Version inconsistency check cancelled.`))}}let A=t.filter(f=>f.status==="error"),u=A.filter(f=>M[f.name]),k=A.filter(f=>!M[f.name]);if(k.length>0&&(console.log(a.blue(`
101
+ \u{1F527} Missing tools that require manual installation:`)),k.forEach(f=>{console.log(` ${a.red("\u2717")} ${f.name}: ${f.fixSuggestion||f.message}`)})),u.length>0){let f=u.filter(S=>xe(S.name)),w=u.filter(S=>!xe(S.name));if(f.length>0){let S=f.map(h=>h.name).join(", "),N=M[f[0].name]?.installDir||"~/.dubhe/bin",_=de(),E=_?_.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.yellow(`
102
+ \u26A0\uFE0F Tools already installed but not in PATH: ${S}`)),console.log(a.gray(` Location: ${N}`)),console.log(a.blue(" To fix this, apply PATH changes:")),console.log(a.green(` source ${E}`)),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 ${N} and run dubhe doctor again`))}if(w.length>0){let S=w.map(N=>N.name).join(", ");console.log(a.blue(`
103
+ \u{1F680} Auto-installable tools detected: ${S}`));try{if((await ve.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${S})`,default:!0}])).installAll){console.log(a.blue(`
92
104
  \u{1F4E6} Starting installation of auto-installable tools...
93
- `));let S=[];for(let v of y){console.log(i.blue(`${"=".repeat(60)}`)),console.log(i.blue(`\u{1F4E6} Installing ${v.name}...`)),console.log(i.blue(`${"=".repeat(60)}`));let w=v.name==="dubhe-indexer"?R.version:void 0;v.name==="dubhe-indexer"&&console.log(i.blue(` Using version ${w} (matching sui-cli version)`));let U=await $e(v.name,w);S.push({name:v.name,success:U}),U?console.log(i.green(`
94
- \u2705 ${v.name} installation completed successfully!`)):(console.log(i.red(`
95
- \u274C ${v.name} installation failed`)),console.log(i.gray(` Manual installation: dubhe doctor --install ${v.name}`))),console.log("")}console.log(i.blue(`${"=".repeat(60)}`)),console.log(i.bold("\u{1F4CB} Installation Summary:")),console.log(i.blue(`${"=".repeat(60)}`)),S.forEach(v=>{let w=v.success?i.green("\u2705 Success"):i.red("\u274C Failed");console.log(` ${v.name}: ${w}`)});let _=S.filter(v=>v.success).length,m=S.length-_;if(console.log(`
96
- ${i.green("Successful:")} ${_}/${S.length}`),m>0&&console.log(` ${i.red("Failed:")} ${m}/${S.length}`),_>0){let v=se(),w=v?v.configFile:"~/.zshrc (or ~/.bashrc)";console.log(i.blue(`
97
- \u{1F504} Next Steps:`)),console.log(i.yellow(" 1. Apply PATH changes by running:")),console.log(i.green(` source ${w}`)),console.log(i.yellow(" 2. Or restart your terminal")),console.log(i.yellow(" 3. Then run the doctor check again:")),console.log(i.green(" dubhe doctor")),console.log(i.gray(`
98
- This will verify that all tools are properly configured.`))}else console.log(i.red(`
99
- \u274C All installations failed. Please check the error messages above.`))}else console.log(i.gray(`
100
- Auto-installation skipped. You can install them manually later:`)),y.forEach(S=>{console.log(i.gray(` dubhe doctor --install ${S.name}`))})}catch{console.log(i.gray(`
101
- Installation cancelled. You can install them manually later:`)),y.forEach(S=>{console.log(i.gray(` dubhe doctor --install ${S.name}`))})}}}l.length===0&&(b.error>0?(console.log(i.red(`
102
- \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),process.exit(1)):b.warning>0?console.log(i.yellow(`
103
- \u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(i.green(`
104
- \u2705 Congratulations! Your development environment is fully ready!`))),console.log(i.gray(`
105
- \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var mn={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(A)}).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(A)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await gn({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(i.red("Error occurred during check:"),t),process.exit(1)}}},kt=mn;import fn from"chalk";import{loadConfig as hn}from"@0xobelisk/sui-common";import yn from"fs";var bn={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 hn(e),n=Ne(o);yn.writeFileSync(t,n)}catch(o){console.error(fn.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},$t=bn;import{loadConfig as wn}from"@0xobelisk/sui-common";var vn={command:"upgrade",describe:"Upgrade your move contracts",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Network of the node (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",decs:"Path to the config file"}})},async handler({network:e,"config-path":t}){try{let o=await wn(t);await ze(o,o.name,e)}catch(o){M(o),process.exit(1)}process.exit(0)}},St=vn;var Pt=[Be,Je,Ye,Ge,St,Xe,Qe,Ze,ot,st,it,at,dt,ut,pt,mt,kt,$t];import*as Tt from"dotenv";Tt.config();xn(Cn(process.argv)).scriptName("dubhe").command(Pt).version(R.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(_t.red(e)),e.includes("Missing required argument")&&console.log(_t.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(M(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
105
+ `));let _=[];for(let x of w){console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.blue(`\u{1F4E6} Installing ${x.name}...`)),console.log(a.blue(`${"=".repeat(60)}`));let v=x.name==="dubhe-indexer"?U.version:void 0;x.name==="dubhe-indexer"&&console.log(a.blue(` Using version ${v} (matching sui-cli version)`));let V=await Ae(x.name,v);_.push({name:x.name,success:V}),V?console.log(a.green(`
106
+ \u2705 ${x.name} installation completed successfully!`)):(console.log(a.red(`
107
+ \u274C ${x.name} installation failed`)),console.log(a.gray(` Manual installation: dubhe doctor --install ${x.name}`))),console.log("")}console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.bold("\u{1F4CB} Installation Summary:")),console.log(a.blue(`${"=".repeat(60)}`)),_.forEach(x=>{let v=x.success?a.green("\u2705 Success"):a.red("\u274C Failed");console.log(` ${x.name}: ${v}`)});let E=_.filter(x=>x.success).length,h=_.length-E;if(console.log(`
108
+ ${a.green("Successful:")} ${E}/${_.length}`),h>0&&console.log(` ${a.red("Failed:")} ${h}/${_.length}`),E>0){let x=de(),v=x?x.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.blue(`
109
+ \u{1F504} Next Steps:`)),console.log(a.yellow(" 1. Apply PATH changes by running:")),console.log(a.green(` source ${v}`)),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(`
110
+ This will verify that all tools are properly configured.`))}else console.log(a.red(`
111
+ \u274C All installations failed. Please check the error messages above.`))}else console.log(a.gray(`
112
+ Auto-installation skipped. You can install them manually later:`)),w.forEach(_=>{console.log(a.gray(` dubhe doctor --install ${_.name}`))})}catch{console.log(a.gray(`
113
+ Installation cancelled. You can install them manually later:`)),w.forEach(_=>{console.log(a.gray(` dubhe doctor --install ${_.name}`))})}}}u.length===0&&(b.error>0?(console.log(a.red(`
114
+ \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),g(1)):b.warning>0?console.log(a.yellow(`
115
+ \u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(a.green(`
116
+ \u2705 Congratulations! Your development environment is fully ready!`))),console.log(a.gray(`
117
+ \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var Rn={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(M)}).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(M)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await Mn({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),g(1)}}},Mt=Rn;import Fn from"chalk";import{loadConfig as jn}from"@0xobelisk/sui-common";import Un from"fs";var Hn={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 jn(e),n=He(o);Un.writeFileSync(t,n)}catch(o){console.error(Fn.red("Error executing convert json:")),console.log(o.stdout),g(1)}g()}},Rt=Hn;import{loadConfig as Ln}from"@0xobelisk/sui-common";import Vn from"chalk";var zn={command:"upgrade",describe:"Upgrade your move contracts",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet","default"],default:"default",desc:"Network of the node (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",decs:"Path to the config file"}})},async handler({network:e,"config-path":t}){try{e=="default"&&(e=await D(),console.log(Vn.yellow(`Use default network: [${e}]`)));let o=await Ln(t);await Je(o,o.name,e)}catch(o){j(o),g(1)}g()}},Ft=zn;var te=[ot,it,st,at,Ft,lt,dt,ut,gt,ht,bt,wt,Ct,$t,kt,Pt,Mt,Rt,tt];import*as Ut from"dotenv";Ut.config();Wn(qn(process.argv)).scriptName("dubhe").command(te).version(U.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(jt.red(e)),e.includes("Missing required argument")&&console.log(jt.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(j(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
106
118
  //# sourceMappingURL=dubhe.js.map