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

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