@0xobelisk/sui-cli 1.2.0-pre.95 → 1.2.0-pre.97

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