@0xobelisk/sui-cli 1.2.0-pre.119 → 1.2.0-pre.120

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