@0xobelisk/sui-cli 1.2.0-pre.113 → 1.2.0-pre.115

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