@0xobelisk/sui-cli 1.2.0-pre.4 → 1.2.0-pre.41

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/README.md CHANGED
@@ -12,7 +12,7 @@ It comes with
12
12
 
13
13
  ## Installation
14
14
 
15
- We dont recommend installing the CLI globally.
15
+ We don't recommend installing the CLI globally.
16
16
 
17
17
  Instead, you should add the CLI as a dev dependency to your project (done automatically if you start from a starter kit using `pnpm create dubhe`), and use it with `pnpm build` inside your project directory.
18
18
 
package/dist/dubhe.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import $o from"yargs";import{hideBin as ko}from"yargs/helpers";import{execSync as ne,spawn as Qe}from"child_process";import D from"chalk";import Ze from"chalk";function H(){console.log(Ze.yellow(`
2
+ import jo from"yargs";import{hideBin as Oo}from"yargs/helpers";import tt from"chalk";import{execSync as U,spawn as _e}from"child_process";import $ from"chalk";import nt from"chalk";function J(){console.log(nt.yellow(`
3
3
  Welcome to Dubhe
4
4
  --from team@obelisk
5
5
  ________ ___ ___ ________ ___ ___ _______
@@ -10,79 +10,83 @@ Welcome to Dubhe
10
10
  \\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
11
11
  \\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
12
12
 
13
- `))}import{existsSync as le,mkdirSync as de,appendFileSync as et}from"fs";import{join as R}from"path";function tt(){try{let e=process.platform==="win32"?'tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH':'pgrep -f "sui start"',t=ne(e).toString().trim();return process.platform==="win32"?t.toLowerCase().includes("sui.exe"):t.length>0}catch{return!1}}async function ot(){let e=[{privateKey:"suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v",address:"0xe7f93ad7493035bcd674f287f78526091e195a6df9d64f23def61a7ce3adada9"},{privateKey:"suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s",address:"0x492404a537c32b46610bd6ae9f7f16ba16ff5a607d272543fe86cada69d8cf44"},{privateKey:"suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc",address:"0xd27e203483700d837a462d159ced6104619d8e36f737bf2a20c251153bf39f24"},{privateKey:"suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c",address:"0x018f1f175c9b6739a14bc9c81e7984c134ebf9031015cf796fefcef04b8c4990"},{privateKey:"suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57",address:"0x932f6aab2bc636a25374f99794dc8451c4e27c91e87083e301816ed08bc98ed0"},{privateKey:"suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c",address:"0x9a66b2da3036badd22529e3de8a00b0cd7dbbfe589873aa03d5f885f5f8c6501"}];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{console.log(` \u250C\u2500 Account #${o}: ${t.address}(100000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t.privateKey}`)}),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."))}async function nt(){let e=R(process.cwd(),"node_logs"),t=R(e,"logs");return le(e)||de(e,{recursive:!0}),le(t)||de(t,{recursive:!0}),{nodeLogsDir:e,logsDir:t}}async function rt(e,t){console.log(" \u251C\u2500 Generating genesis configuration..."),ne(`sui genesis --write-config ${R(e,"sui.yaml")}`);let o=`
14
- - address: "0xe7f93ad7493035bcd674f287f78526091e195a6df9d64f23def61a7ce3adada9"
15
- gas_amounts:
16
- - 100000000000000
17
- - address: "0x492404a537c32b46610bd6ae9f7f16ba16ff5a607d272543fe86cada69d8cf44"
18
- gas_amounts:
19
- - 100000000000000
20
- - address: "0xd27e203483700d837a462d159ced6104619d8e36f737bf2a20c251153bf39f24"
21
- gas_amounts:
22
- - 100000000000000
23
- - address: "0x018f1f175c9b6739a14bc9c81e7984c134ebf9031015cf796fefcef04b8c4990"
24
- gas_amounts:
25
- - 100000000000000
26
- - address: "0x932f6aab2bc636a25374f99794dc8451c4e27c91e87083e301816ed08bc98ed0"
27
- gas_amounts:
28
- - 100000000000000
29
- - address: "0x9a66b2da3036badd22529e3de8a00b0cd7dbbfe589873aa03d5f885f5f8c6501"
30
- gas_amounts:
31
- - 100000000000000
32
- `;et(R(e,"sui.yaml"),o),console.log(" \u251C\u2500 Initializing genesis..."),ne(`sui genesis --working-dir ${t} -f --from-config ${R(e,"sui.yaml")}`)}function st(e){let t=()=>{console.log(D.yellow(`
33
- \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function pe(e={}){if(tt()){console.log(D.yellow(`
34
- \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}H(),console.log("\u{1F680} Starting Local Node...");let t=null;try{let{nodeLogsDir:o,logsDir:n}=await nt();e.forceRegenesis?(console.log(" \u251C\u2500 Force Regenesis: Yes"),await rt(o,n)):console.log(" \u251C\u2500 Force Regenesis: No"),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await ot(),console.log(D.green("\u{1F389} Local environment is ready!")),t=Qe("sui",["start","--with-faucet","--network.config",R(n,"network.yaml")],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),st(t),await new Promise(r=>{t?.on("exit",()=>r())})}catch(o){console.error(D.red(`
35
- \u274C Failed to Start Local Node`)),console.error(D.red(` \u2514\u2500 Error: ${o.message}`)),t&&t.kill("SIGINT"),process.exit(1)}}var at={command:"node",describe:"Manage local Sui node",builder(e){return e.option("force-regenesis",{alias:"f",type:"boolean",description:"Force regenesis the local node",default:!0})},async handler(e){try{await pe({forceRegenesis:e["force-regenesis"]})}catch(t){console.error("Error executing command:",t),process.exit(1)}}},ue=at;import{requestSuiFromFaucetV0 as Nt,getFaucetHost as Ot}from"@mysten/sui/faucet";import{SuiClient as Rt,getFullnodeUrl as Ft}from"@mysten/sui/client";import{Transaction as Q}from"@0xobelisk/sui-client";import{execSync as vt}from"child_process";import g from"chalk";import*as ae from"fs/promises";import{mkdirSync as dt,writeFileSync as pt}from"fs";import{dirname as ut}from"path";import{SUI_PRIVATE_KEY_PREFIX as mt}from"@mysten/sui/cryptography";import V from"chalk";import{ZodError as it}from"zod";import{fromZodError as ct,ValidationError as lt}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"},W=class extends Error{name="UpgradeError"};function $(e){if(e instanceof lt)console.log(V.redBright(e.message));else if(e instanceof it){let t=ct(e,{prefixSeparator:`
13
+ `))}import{Transaction as ee}from"@0xobelisk/sui-client";import{execSync as bt}from"child_process";import C from"chalk";import*as ie from"fs/promises";import{mkdirSync as lt,writeFileSync as ct}from"fs";import{dirname as dt}from"path";import{SUI_PRIVATE_KEY_PREFIX as ut}from"@mysten/sui/cryptography";import V from"chalk";import{ZodError as st}from"zod";import{fromZodError as rt,ValidationError as at}from"zod-validation-error";var re=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},E=class extends Error{name="DubheCliError"};function N(e){if(e instanceof at)console.log(V.redBright(e.message));else if(e instanceof st){let t=rt(e,{prefixSeparator:`
36
14
  - `,issueSeparator:`
37
- - `});console.log(V.redBright(t.message))}else e instanceof re?(console.log(V.red(e.message)),console.log(""),console.log(V.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof v?console.log(V.red(e)):console.log(e)}import*as Y from"fs";import K from"chalk";import{spawn as gt}from"child_process";import{Dubhe as ft}from"@0xobelisk/sui-client";function ht(e){if(e.startsWith(mt))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 T(e,t){try{let o=await ae.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 se(e,t){try{let o=await ae.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).schemaId}catch{return""}}async function J(e){let o=`${process.cwd()}/contracts/dubhe-framework`;switch(e){case"mainnet":return await se(o,"mainnet");case"testnet":return"0xa565cbb3641fff8f7e8ef384b215808db5f1837aa72c1cca1803b5d973699aac";case"devnet":return await se(o,"devnet");case"localnet":return await se(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function me(e,t){return(await T(e,t)).schemas}async function ge(e,t){return(await T(e,t)).version}async function F(e,t){return(await T(e,t)).packageId}async function L(e,t){return(await T(e,t)).schemaId}async function fe(e,t){return(await T(e,t)).upgradeCap}function B(e,t,o,n,r,s,c){let a={projectName:e,network:t,packageId:o,schemaId:n,schemas:c,upgradeCap:r,version:s},l=process.cwd(),i=JSON.stringify(a,null,2);yt(i,`${l}/contracts/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function yt(e,t,o){dt(ut(t),{recursive:!0}),pt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function bt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe-framework" }';case"testnet":return'Dubhe = { git = "https://github.com/0xobelisk/dubhe-framework.git", subdir = "contracts/dubhe", rev = "develop" }';case"mainnet":return'Dubhe = { git = "https://github.com/0xobelisk/dubhe-framework.git", subdir = "contracts/dubhe", rev = "develop" }';default:throw new Error(`Unsupported network: ${e}`)}}async function X(e,t){let o=Y.readFileSync(e,"utf-8"),n=bt(t),r=o.replace(/Dubhe = \{.*\}/,n);Y.writeFileSync(e,r,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function A(e){try{return new Promise((t,o)=>{let n=gt("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});n.on("error",r=>{console.error(K.red(`
38
- \u274C Failed to Switch Env`)),console.error(K.red(` Error: ${r.message}`)),o(r)}),n.on("exit",r=>{r!==0?(console.error(K.red(`
39
- \u274C Process exited with code: ${r}`)),o(new Error(`Process exited with code: ${r}`))):t()})})}catch(t){console.error(K.red(`
40
- \u274C Failed to Switch Env`)),console.error(K.red(` \u2514\u2500 Error: ${t}`))}}var Z=e=>new Promise(t=>setTimeout(t,e));function wt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new v(`Missing private key environment variable.
15
+ - `});console.log(V.redBright(t.message))}else e instanceof re?(console.log(V.red(e.message)),console.log(""),console.log(V.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof E?console.log(V.red(e)):console.log(e)}import*as R from"fs";import A from"chalk";import{spawn as he}from"child_process";import{Dubhe as pt,loadMetadata as gt}from"@0xobelisk/sui-client";var L={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.41",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",publishConfig:{access:"public"},engines:{node:">=18"},exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",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",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","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":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"}};function le(e){if(e.startsWith(ut))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 ce(e,t){try{let o=await ie.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 X(e,t){try{let o=await ie.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function Z(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await X(o,"mainnet");case"testnet":return await X(o,"testnet");case"devnet":return await X(o,"devnet");case"localnet":return await X(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function ye(e,t){return(await ce(e,t)).packageId}async function de(e,t,o,n,s,r,i){let c={projectName:e,network:t,packageId:o,dappHub:n,components:i,upgradeCap:s,version:r},d=process.cwd(),u=JSON.stringify(c,null,2);await ae(u,`${d}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function B(e,t,o){let n=process.cwd();try{let s=await gt(t,o);if(s){let r=JSON.stringify(s,null,2);await ae(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await ae(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(A.yellow(`Warning: Failed to save metadata: ${s}`))}}async function ae(e,t,o){lt(dt(t),{recursive:!0}),ct(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function mt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${L.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${L.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function Q(e,t){let o=R.readFileSync(e,"utf-8"),n=mt(t),s=o.replace(/Dubhe = \{.*\}/,n);R.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function ft(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 ht(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 ft(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,r)=>{let i="",c="",d=he("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});d.stdout.on("data",u=>{c+=u.toString()}),d.stderr.on("data",u=>{i+=u.toString()}),d.on("error",u=>{console.error(A.red(`
16
+ \u274C Failed to execute sui command: ${u.message}`)),r(new Error(`Failed to execute sui command: ${u.message}`))}),d.on("exit",u=>{if(i.includes("already exists")||c.includes("already exists")){console.log(A.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(u===0)console.log(A.green(`Successfully added environment ${e}`)),s();else{let h=i||c||`Process exited with code ${u}`;console.error(A.red(`
17
+ \u274C Failed to add environment ${e}`)),console.error(A.red(` \u2514\u2500 ${h.trim()}`)),r(new Error(h))}})})}async function H(e){try{return await ht(e),new Promise((t,o)=>{let n="",s="",r=he("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{n+=i.toString()}),r.on("error",i=>{console.error(A.red(`
18
+ \u274C Failed to execute sui command: ${i.message}`)),o(new Error(`Failed to execute sui command: ${i.message}`))}),r.on("exit",i=>{if(i===0)console.log(A.green(`Successfully switched to environment ${e}`)),t();else{let c=n||s||`Process exited with code ${i}`;console.error(A.red(`
19
+ \u274C Failed to switch to environment ${e}`)),console.error(A.red(` \u2514\u2500 ${c.trim()}`)),o(new Error(c))}})})}catch(t){throw t}}var j=e=>new Promise(t=>setTimeout(t,e));function yt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new E(`Missing private key environment variable.
41
20
  Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
42
21
  or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
43
- in your contracts directory to use the default sui private key.`);let t=ht(e);if(t===!1)throw new v("Please check your privateKey.");return t}function S({network:e,packageId:t,metadata:o}){let n=wt();return new ft({networkType:e,secretKey:n,packageId:t,metadata:o})}import*as P from"fs";import*as he from"path";var x=60,q=1e3,k=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];async function ye(e,t){if(!P.existsSync(e))return;let o=P.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),r=o.replace(n,"");P.writeFileSync(e,r,"utf-8")}function be(e,t,o,n,r){let s=he.resolve(e),c=P.readFileSync(s,"utf-8"),a=c.split(`
44
- `),l=a.findIndex(f=>f.trim()===`[env.${t}]`),i={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(l===-1)if(o==="publish")i.originalPublishedId=r,i.latestPublishedId=r,i.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let f=l+1;f<a.length;f++){let m=a[f].trim();if(m.startsWith("["))break;let[y,_]=m.split("=").map(b=>b.trim().replace(/"/g,""));switch(y){case"original-published-id":i.originalPublishedId=_;break;case"latest-published-id":i.latestPublishedId=_;break;case"published-version":i.publishedVersion=parseInt(_,10);break}}o==="publish"?(i.originalPublishedId=r,i.latestPublishedId=r,i.publishedVersion=1):o==="upgrade"&&(i.latestPublishedId=r,i.publishedVersion+=1)}let p=`
22
+ in your contracts directory to use the default sui private key.`);let t=le(e);if(t===!1)throw new E("Please check your privateKey.");return t}function F({network:e,packageId:t,metadata:o}){let n=yt();return new pt({networkType:e,secretKey:n,packageId:t,metadata:o})}function be(e){let t=Object.entries(e.components).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{entity_id:"address"},{value:r}],keys:["entity_id"]}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"]}};let i=r.fields||{},c=r.keys||["entity_id"];return!i.entity_id&&c.includes("entity_id")&&(i.entity_id="address"),{[s]:{fields:Object.entries(i).map(([d,u])=>({[d]:u})),keys:c}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[]}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[]}};let i=r.fields||{},c=r.keys||[];return{[s]:{fields:Object.entries(i).map(([d,u])=>({[d]:u})),keys:c}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((c,d)=>c.localeCompare(d)).map((c,d)=>({[d]:c}));return{[s]:{fields:i}}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function ue(e,t){let o=`${e}/Move.toml`,s=R.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);R.writeFileSync(o,s,"utf-8")}import*as T from"fs";import*as we from"path";async function ve(e,t){if(!T.existsSync(e))return;let o=T.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");T.writeFileSync(e,s,"utf-8")}function xe(e,t,o,n,s){let r=we.resolve(e),i=T.readFileSync(r,"utf-8"),c=i.split(`
23
+ `),d=c.findIndex(y=>y.trim()===`[env.${t}]`),u={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(d===-1)if(o==="publish")u.originalPublishedId=s,u.latestPublishedId=s,u.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 v=c[y].trim();if(v.startsWith("["))break;let[_,p]=v.split("=").map(l=>l.trim().replace(/"/g,""));switch(_){case"original-published-id":u.originalPublishedId=p;break;case"latest-published-id":u.latestPublishedId=p;break;case"published-version":u.publishedVersion=parseInt(p,10);break}}o==="publish"?(u.originalPublishedId=s,u.latestPublishedId=s,u.publishedVersion=1):o==="upgrade"&&(u.latestPublishedId=s,u.publishedVersion+=1)}let h=`
45
24
  [env.${t}]
46
- chain-id = "${i.chainId}"
47
- original-published-id = "${i.originalPublishedId}"
48
- latest-published-id = "${i.latestPublishedId}"
49
- published-version = "${i.publishedVersion}"
50
- `,u=l===-1?c+p:a.slice(0,l).join(`
51
- `)+p;P.writeFileSync(s,u,"utf-8")}function we(e){let t,o;try{let n=JSON.parse(vt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(g.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function ve(e){let t=0,o=0,n=Date.now(),r=!1,s="",c=!1,a=()=>{r=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
52
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",a);try{for(;t<x&&!r&&!s;){try{s=await e.suiInteractor.currentClient.getChainIdentifier()}catch{}if(r)break;if(!s){t++,t===x&&(console.log(g.red(` \u2514\u2500 Failed to connect to node after ${x} attempts`)),console.log(g.red(" \u2514\u2500 Please check if the Sui node is running.")),process.exit(1));let l=Math.floor((Date.now()-n)/1e3),i=k[o%k.length];o++,process.stdout.write(`\r \u251C\u2500 ${i} Waiting for node... (${l}s)`),await new Promise(p=>setTimeout(p,q))}}for(process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(` \u251C\u2500 ChainId: ${s}`),t=0;t<x&&!r;)try{let l=e.getAddress(),i=await e.suiInteractor.currentClient.getCoins({owner:l,coinType:"0x2::sui::SUI"});if(i.data.length>0){let f=i.data.reduce((m,y)=>m+Number(y.balance),0);if(f>0)return process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(` \u251C\u2500 Deployer balance: ${f/10**9} SUI`),s;c||(process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(g.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance")),c=!0)}else c||(process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(g.yellow(" \u251C\u2500 No SUI coins found in deployer account, please ensure your account has sufficient SUI balance")),c=!0);t++,t===x&&(console.log(g.red(` \u2514\u2500 Deployer account has no SUI balance after ${x} attempts`)),console.log(g.red(" \u2514\u2500 Please ensure your account has sufficient SUI balance.")),process.exit(1));let p=Math.floor((Date.now()-n)/1e3),u=k[o%k.length];o++,process.stdout.write(`\r \u251C\u2500 ${u} Checking deployer balance... (${p}s)`),await new Promise(f=>setTimeout(f,q))}catch{if(r)break;t++,t===x&&(console.log(g.red(` \u2514\u2500 Failed to check deployer balance after ${x} attempts`)),console.log(g.red(" \u2514\u2500 Please check your account and network connection.")),process.exit(1));let i=Math.floor((Date.now()-n)/1e3),p=k[o%k.length];o++,process.stdout.write(`\r \u251C\u2500 ${p} Checking deployer balance... (${i}s)`),await new Promise(u=>setTimeout(u,q))}}finally{process.removeListener("SIGINT",a)}throw r&&process.exit(0),new Error("Failed to connect to node")}async function xt(e,t,o,n,r){console.log(`
53
- \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 s=await ve(e);console.log(" \u251C\u2500 Validating Environment..."),await ye(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
54
- \u{1F4E6} Building Contract...`);let[c,a]=we(n);console.log(`
55
- \u{1F504} Publishing Contract...`);let l=new Q;r&&l.setGasBudget(r);let[i]=l.publish({modules:c,dependencies:a});l.transferObjects([i],e.getAddress());let p=null,u=0,f=0,m=Date.now(),y=!1,_=()=>{y=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
56
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",_);try{for(;u<x&&!p&&!y;)try{p=await e.signAndSendTxn({tx:l})}catch{if(y)break;u++,u===x&&(console.log(g.red(` \u2514\u2500 Publication failed after ${x} attempts`)),console.log(g.red(" \u2514\u2500 Please check your network connection and try again later.")),process.exit(1));let U=Math.floor((Date.now()-m)/1e3),oe=k[f%k.length];f++,process.stdout.write(`\r \u251C\u2500 ${oe} Retrying... (${U}s)`),await new Promise(Xe=>setTimeout(Xe,q))}}finally{process.removeListener("SIGINT",_)}y&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),(!p||p.effects?.status.status==="failure")&&(console.log(g.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let b=1,E="",N="",O=t.schemas,C="";p.objectChanges.map(d=>{d.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${d.packageId}`),E=d.packageId||""),d.type==="created"&&d.objectType&&d.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${d.objectId}`),C=d.objectId||"")}),console.log(` \u2514\u2500 Transaction: ${p.digest}`),be(`${n}/Move.lock`,o,"publish",s,E),console.log(`
57
- \u26A1 Executing Deploy Hook...`),await Z(5e3);let w=new Q,h=[];if(t.name!=="dubhe"){let d=await J(o);h.push(w.object(d))}h.push(w.object("0x6")),w.moveCall({target:`${E}::${t.name}_genesis::run`,arguments:h});let I;try{I=await e.signAndSendTxn({tx:w})}catch(d){console.error(g.red(" \u2514\u2500 Deploy hook execution failed")),console.error(d.message),process.exit(1)}I.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${I.digest}`),console.log(`
58
- \u{1F4CB} Created Schemas:`),I.objectChanges?.map(d=>{d.type==="created"&&d.objectType&&d.objectType.includes("schema::Schema")&&(N=d.objectId||""),d.type==="created"&&d.objectType&&d.objectType.includes("schema")&&!d.objectType.includes("dynamic_field")&&(console.log(` \u251C\u2500 Type: ${d.objectType}`),console.log(` \u2514\u2500 ID: ${d.objectId}`))}),B(t.name,o,E,N,C,b,O),console.log(`
25
+ chain-id = "${u.chainId}"
26
+ original-published-id = "${u.originalPublishedId}"
27
+ latest-published-id = "${u.latestPublishedId}"
28
+ published-version = "${u.publishedVersion}"
29
+ `,f=d===-1?i+h:c.slice(0,d).join(`
30
+ `)+h;T.writeFileSync(r,f,"utf-8")}function $e(e){let t,o;try{let n=JSON.parse(bt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(C.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function ke(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.data.reduce((r,i)=>r+Number(i.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(C.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function wt(e,t,o,n,s){console.log(`
31
+ \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let r=await ke(e);console.log(" \u251C\u2500 Validating Environment..."),await ve(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
+ \u{1F4E6} Building Contract...`);let[i,c]=$e(n);console.log(`
33
+ \u{1F504} Publishing Contract...`);let d=new ee;s&&d.setGasBudget(s);let[u]=d.publish({modules:i,dependencies:c});d.transferObjects([u],e.getAddress());let h;try{h=await e.signAndSendTxn({tx:d})}catch(m){console.error(C.red(" \u2514\u2500 Publication failed")),console.error(m.message),process.exit(1)}(!h||h.effects?.status.status==="failure")&&(console.log(C.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let f=1,y="",v="",_=t.components,p="",l=[];h.objectChanges.map(m=>{m.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${m.packageId}`),y=m.packageId||""),m.type==="created"&&m.objectType&&m.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${m.objectId}`),p=m.objectId||""),m.type==="created"&&m.objectType&&m.objectType.includes("dapp_hub::DappHub")&&(v=m.objectId||""),m.type==="created"&&l.push(m)}),console.log(` \u2514\u2500 Transaction: ${h.digest}`),xe(`${n}/Move.lock`,o,"publish",r,y),console.log(`
34
+ \u26A1 Executing Deploy Hook...`),await j(5e3);let g=new ee,x=[],b=t.name==="dubhe"?v:await Z(o);x.push(g.object(b)),x.push(g.object("0x6")),g.moveCall({target:`${y}::genesis::run`,arguments:x});let S;try{S=await e.signAndSendTxn({tx:g})}catch(m){console.error(C.red(" \u2514\u2500 Deploy hook execution failed")),console.error(m.message),process.exit(1)}if(S.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${S.digest}`),console.log(`
35
+ \u{1F4CB} Created Objects:`),l.map(k=>{console.log(` \u251C\u2500 Type: ${k.objectType}`),console.log(` \u2514\u2500 ID: ${k.objectId}`)}),await de(t.name,o,y,v,p,f,_),await B(t.name,o,y);let m=JSON.parse(T.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));m.package_id=y,T.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(m,null,2)),console.log(`
59
36
  \u2705 Contract Publication Complete
60
- `)):(console.log(g.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(g.yellow(" Please republish or manually call deploy_hook::run")),console.log(g.yellow(" Please check the transaction digest:")),console.log(g.yellow(` ${I.digest}`)),process.exit(1))}async function _t(e){return P.existsSync(e)?!0:(console.log(g.yellow(`
61
- \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(g.yellow(" \u251C\u2500 Expected Path:"),e),console.log(g.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(g.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe-framework")),console.log(g.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe-framework contracts/dubhe-framework")),console.log(g.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe-framework")),console.log(g.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function It(e,t){let n=`${process.cwd()}/contracts/dubhe-framework`;if(!await _t(n))return;console.log(`
62
- \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let r=await ve(e);await ye(`${n}/Move.lock`,t);let[s,c]=we(n),a=new Q,[l]=a.publish({modules:s,dependencies:c});a.transferObjects([l],e.getAddress());let i=null,p=0,u=0,f=Date.now(),m=!1,y=()=>{m=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
63
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",y);try{for(;p<x&&!i&&!m;)try{i=await e.signAndSendTxn({tx:a})}catch{if(m)break;p++,p===x&&(console.log(g.red(` \u2514\u2500 Publication failed after ${x} attempts`)),console.log(g.red(" \u2514\u2500 Please check your network connection and try again later.")),process.exit(1));let I=Math.floor((Date.now()-f)/1e3),d=k[u%k.length];u++,process.stdout.write(`\r \u251C\u2500 ${d} Retrying... (${I}s)`),await new Promise(U=>setTimeout(U,q))}}finally{process.removeListener("SIGINT",y)}m&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),(!i||i.effects?.status.status==="failure")&&(console.log(g.red(" \u2514\u2500 Publication failed")),process.exit(1));let _=1,b="",E="",N={},O="";i.objectChanges.map(h=>{h.type==="published"&&(b=h.packageId||""),h.type==="created"&&h.objectType&&h.objectType==="0x2::package::UpgradeCap"&&(O=h.objectId||"")}),await Z(3e3);let C=new Q;C.moveCall({target:`${b}::dubhe_genesis::run`,arguments:[C.object("0x6")]});let w;try{w=await e.signAndSendTxn({tx:C})}catch(h){console.error(g.red(" \u2514\u2500 Deploy hook execution failed")),console.error(h.message),process.exit(1)}w.effects?.status.status==="success"&&w.objectChanges?.map(h=>{h.type==="created"&&h.objectType&&h.objectType.includes("dubhe_schema::Schema")&&(E=h.objectId||"")}),B("dubhe-framework",t,b,E,O,_,N),be(`${n}/Move.lock`,t,"publish",r,b),await Z(1e3)}async function xe(e,t,o){await A(t);let n=S({network:t});t==="localnet"&&await It(n,t);let s=`${process.cwd()}/contracts/${e.name}`;await X(`${s}/Move.toml`,t),await xt(n,e,t,s,o)}import{loadMetadata as Ct}from"@0xobelisk/sui-client";import*as _e from"fs";import*as Ie from"path";function St(e,t){switch(e.split("<")[0].trim()){case"StorageValue":return t.length===0;case"StorageMap":return t.length===1;case"StorageDoubleMap":return t.length===2;default:return!1}}function $t(e){switch(e.split("<")[0].trim()){case"StorageValue":return 0;case"StorageMap":return 1;case"StorageDoubleMap":return 2;default:return 0}}async function Ce({dubheConfig:e,schema:t,params:o,network:n,objectId:r,packageId:s,metadataFilePath:c}){let l=`${process.cwd()}/contracts/${e.name}`;s=s||await F(l,n),r=r||await L(l,n);let i;if(c?i=await ie(c):i=await Ct(n,s),!i)throw new v("Metadata file not found. Please provide a metadata file path or set the packageId.");if(!e.schemas[t])throw new v(`Schema "${t}" not found in dubhe config. Available schemas: ${Object.keys(e.schemas).join(", ")}`);let p=e.schemas[t],u=o||[];if(!St(p,u))throw new Error(`Invalid params count for ${p}. Expected: ${$t(p)}, Got: ${u.length}`);let m=await S({network:n,packageId:s,metadata:i}).parseState({schema:t,objectId:r,storageType:p,params:u});console.log(m)}async function ie(e){if(Ie.extname(e)!==".json")throw new Error("Metadata file must be in JSON format");try{let t=_e.readFileSync(e,"utf8"),o=JSON.parse(t);if(!o||typeof o!="object")throw new Error("Invalid JSON format");return{...o}}catch(t){throw t instanceof Error?new Error(`Failed to read metadata file: ${t.message}`):t}}import{loadMetadata as kt,Transaction as Et}from"@0xobelisk/sui-client";var Dt=["u8","u16","u32","u64","u128","u256","bool","id","string","address","object"];function Pt(e){try{e.forEach(t=>{let[o,n]=t.split(":");if(!Dt.includes(o))throw new Error(`Invalid param type: ${o}`)})}catch(t){throw new Error(`Invalid params: ${t}`)}}function Tt(e,t){let[o,n]=t.split(":");switch(o){case"u8":return e.pure.u8(parseInt(n));case"u16":return e.pure.u16(parseInt(n));case"u32":return e.pure.u32(parseInt(n));case"u64":return e.pure.u64(parseInt(n));case"u128":return e.pure.u128(parseInt(n));case"u256":return e.pure.u256(parseInt(n));case"object":return e.object(n);case"address":return e.pure.address(n);case"bool":return e.pure.bool(n==="true");case"string":return e.pure.string(n);default:throw new Error(`Invalid param type: ${o}`)}}function Mt(e,t){return t.map(o=>Tt(e,o))}async function Se({dubheConfig:e,moduleName:t,funcName:o,params:n,network:r,packageId:s,metadataFilePath:c}){let l=`${process.cwd()}/contracts/${e.name}`;s=s||await F(l,r);let i;if(c?i=await ie(c):i=await kt(r,s),!i)throw new v("Metadata file not found. Please provide a metadata file path or set the packageId.");let p=n||[];Pt(p);let u=S({network:r,packageId:s,metadata:i}),f=new Et,m=Mt(f,p),y=await u.tx[t][o]({tx:f,params:m});console.log(JSON.stringify(y,null,2))}var ce=60,At=1e3,$e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],jt={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=S(e).getAddress():o=t,console.log(`
64
- \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,r=!1,s=0,c=Date.now(),a=!1,l=()=>{a=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
65
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",l);try{for(;n<ce&&!r&&!a;)try{await Nt({host:Ot(e),recipient:o}),r=!0}catch{if(a)break;n++,n===ce&&(console.log(` \u2514\u2500 Failed to request funds after ${ce} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let m=Math.floor((Date.now()-c)/1e3),y=$e[s%$e.length];s++,process.stdout.write(`\r \u251C\u2500 ${y} Retrying... (${m}s)`),await new Promise(_=>setTimeout(_,At))}}finally{process.removeListener("SIGINT",l)}a&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let i=new Rt({url:Ft(e)}),p={owner:o},u=await i.getBalance(p);console.log(`
66
- \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(u.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
37
+ `)}else console.log(C.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(C.yellow(" Please republish or manually call deploy_hook::run")),console.log(C.yellow(" Please check the transaction digest:")),console.log(C.yellow(` ${S.digest}`)),process.exit(1)}async function vt(e){return T.existsSync(e)?!0:(console.log(C.yellow(`
38
+ \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(C.yellow(" \u251C\u2500 Expected Path:"),e),console.log(C.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(C.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(C.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(C.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(C.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function xt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await vt(n))return;console.log(`
39
+ \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await ke(e);await ve(`${n}/Move.lock`,t),await ue(n,"0x0");let[r,i]=$e(n),c=new ee,[d]=c.publish({modules:r,dependencies:i});c.transferObjects([d],e.getAddress());let u;try{u=await e.signAndSendTxn({tx:c})}catch(g){console.error(C.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}(!u||u.effects?.status.status==="failure")&&(console.log(C.red(" \u2514\u2500 Publication failed")),process.exit(1));let h=1,f="",y="",v={},_="";u.objectChanges.map(g=>{g.type==="published"&&(f=g.packageId||""),g.type==="created"&&g.objectType&&g.objectType==="0x2::package::UpgradeCap"&&(_=g.objectId||""),g.type==="created"&&g.objectType&&g.objectType.includes("dapp_hub::DappHub")&&(y=g.objectId||"")}),await j(3e3);let p=new ee;p.moveCall({target:`${f}::dubhe_genesis::run`,arguments:[p.object(y),p.object("0x6")]});let l;try{l=await e.signAndSendTxn({tx:p})}catch(g){console.error(C.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}if(l.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await ue(n,f),await de("dubhe",t,f,y,_,h,v),xe(`${n}/Move.lock`,t,"publish",s,f)}async function Ce(e,t,o){await H(t);let n=F({network:t}),r=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await xt(n,t),e.name!=="dubhe"&&await Q(`${r}/Move.toml`,t),await wt(n,e,t,r,o)}import{Dubhe as $t}from"@0xobelisk/sui-client";import*as te from"fs";function kt(){console.log($.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{U("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=U(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
+ `).filter(r=>r);console.log($.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{U(`kill -TERM ${r}`,{stdio:"ignore"}),console.log($.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{U(`kill -KILL ${r}`,{stdio:"ignore"}),console.log($.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log($.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?$.green(" \u2514\u2500 Local Node stopped successfully"):$.gray(" \u2514\u2500 No running Local Node found"))}function Ct(e){try{te.existsSync(e)?(console.log($.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),te.rmSync(e,{recursive:!0,force:!0}),console.log($.green(" \u2514\u2500 Directory removed successfully"))):console.log($.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error($.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function _t(){try{if(process.platform==="win32")return U('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=U(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function St(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new $t({secretKey:t}).getSigner();_e("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${s.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log($.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log($.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Pt(e){let t=()=>{console.log($.yellow(`
41
+ \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Se(e,t){if(t)console.log($.cyan(`
42
+ \u{1F504} Force mode enabled`)),kt(),console.log($.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await j(3e3),Ct(e),console.log("");else if(_t()){console.log($.yellow(`
43
+ \u26A0\uFE0F Warning: Local Node Already Running`)),console.log($.yellow(" \u251C\u2500 Cannot start a new instance")),console.log($.yellow(" \u2514\u2500 Please stop the existing process first"));return}J(),console.log("\u{1F680} Starting Local Node...");let o=null;try{if(o=_e("sui",["start","--with-faucet","--force-regenesis","--data-ingestion-dir",e],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",s=>{console.error($.red(`
44
+ \u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${s.message}`))}),await j(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await St(),await j(2e3),le("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new E("Please check your privateKey.");console.log($.green("\u{1F389} Local environment is ready!")),Pt(o),await new Promise(s=>{o?.on("exit",()=>s())})}catch(n){console.error($.red(`
45
+ \u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var Dt={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 Se(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},Pe=Dt;import{requestSuiFromFaucetV0 as Et,getFaucetHost as Tt}from"@mysten/sui/faucet";import{SuiClient as It,getFullnodeUrl as At}from"@mysten/sui/client";var pe=60,Nt=1e3,De=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ft={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=F(e).getAddress():o=t,console.log(`
46
+ \u{1F30A} Starting Faucet Operation...`),console.log(` \u251C\u2500 Network: ${e}`),t===void 0?(console.log(" \u251C\u2500 Using Environment PrivateKey"),console.log(` \u251C\u2500 Generated Address: ${o}`)):console.log(` \u251C\u2500 Using Provided Address: ${o}`),console.log(" \u251C\u2500 Requesting funds from faucet...");let n=0,s=!1,r=0,i=Date.now(),c=!1,d=()=>{c=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
47
+ \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",d);try{for(;n<pe&&!s&&!c;)try{await Et({host:Tt(e),recipient:o}),s=!0}catch{if(c)break;n++,n===pe&&(console.log(` \u2514\u2500 Failed to request funds after ${pe} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let v=Math.floor((Date.now()-i)/1e3),_=De[r%De.length];r++,process.stdout.write(`\r \u251C\u2500 ${_} Retrying... (${v}s)`),await new Promise(p=>setTimeout(p,Nt))}}finally{process.removeListener("SIGINT",d)}c&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let u=new It({url:At(e)}),h={owner:o},f=await u.getBalance(h);console.log(`
48
+ \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(f.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
67
49
  \u2705 Faucet Operation Complete
68
- `),process.exit(0)}},ke=jt;import{schemaGen as Ut,loadConfig as Vt}from"@0xobelisk/sui-common";import Kt from"chalk";var Lt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{let o=await Vt(e);await Ut(o,void 0,t),process.exit(0)}catch(o){console.log(Kt.red("Schemagen failed!")),console.error(o.message)}}},Ee=Lt;import{loadConfig as Bt}from"@0xobelisk/sui-common";var qt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await Bt(t);await xe(n,e,o)}catch(n){$(n),process.exit(1)}process.exit(0)}},De=qt;import{Transaction as Pe,UpgradePolicy as zt}from"@0xobelisk/sui-client";import{execSync as Gt}from"child_process";import M from"chalk";import*as j from"fs";import*as Te from"path";function Ht(e,t){let o=`${e}/sources/codegen/core/schema.move`,n=j.readFileSync(o,"utf-8"),r=new RegExp("public fun migrate\\(_schema: &mut Schema, _ctx: &mut TxContext\\) {[^}]*}"),s=`
69
- public fun migrate(_schema: &mut Schema, _ctx: &mut TxContext) {
70
- ${t.map(a=>{let l="";return a.fields.includes("StorageValue")?l=`storage_value::new(b"${a.schemaName}", _ctx)`:a.fields.includes("StorageMap")?l=`storage_map::new(b"${a.schemaName}", _ctx)`:a.fields.includes("StorageDoubleMap")&&(l=`storage_double_map::new(b"${a.schemaName}", _ctx)`),`storage::add_field<${a.fields}>(&mut _schema.id, b"${a.schemaName}", ${l});`}).join("")}
71
- }
72
- `,c=n.replace(r,s);j.writeFileSync(o,c,"utf-8")}function ee(e,t,o,n){let r=Te.resolve(e),c=j.readFileSync(r,"utf-8").split(`
73
- `),a=c.findIndex(p=>p.trim()===`[env.${t}]`);if(a===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let l=-1,i="";for(let p=a+1;p<c.length;p++){let u=c[p].trim();if(u.startsWith("["))break;if(u.startsWith(o)){l=p,i=u.split("=")[1].trim().replace(/"/g,"");break}}if(l!==-1){c[l]=`${o} = "${n}"`;let p=c.join(`
74
- `);j.writeFileSync(r,p,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return i}async function Me(e,t,o){await A(o);let n=process.cwd(),r=`${n}/contracts/${t}`,s=S({network:o}),c=Number(await ge(r,o)),a=await F(r,o),l=await fe(r,o),i=await L(r,o),p=ee(`${r}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),u=[],f=await me(r,o);Object.entries(e.schemas).forEach(([m,y])=>{f.hasOwnProperty(m)||u.push({schemaName:m,fields:y})}),Ht(r,u);try{let m,y,_;try{let{modules:d,dependencies:U,digest:oe}=JSON.parse(Gt(`sui move build --dump-bytecode-as-base64 --path ${n}/contracts/${t}`,{encoding:"utf-8"}));m=d,y=U,_=oe}catch(d){throw new W(d.stdout)}console.log(`
75
- \u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",a),console.log("\u{1F4CB} UpgradeCap Object Id:",l),console.log("\u{1F4CB} OldVersion:",c);let b=new Pe,E=b.moveCall({target:"0x2::package::authorize_upgrade",arguments:[b.object(l),b.pure.u8(zt.COMPATIBLE),b.pure.vector("u8",_)]}),N=b.upgrade({modules:m,dependencies:y,package:a,ticket:E});b.moveCall({target:"0x2::package::commit_upgrade",arguments:[b.object(l),N]});let O=await s.signAndSendTxn({tx:b,onSuccess:d=>{console.log(M.green(`Upgrade Transaction Digest: ${d.digest}`))},onError:d=>{console.log(M.red("Upgrade Transaction failed!")),console.error(d)}}),C="";O.objectChanges.map(d=>{d.type==="published"&&(console.log(M.blue(`${t} new PackageId: ${d.packageId}`)),console.log(M.blue(`${t} new Version: ${c+1}`)),C=d.packageId)}),ee(`${r}/Move.lock`,o,"original-published-id",p),ee(`${r}/Move.lock`,o,"latest-published-id",C),ee(`${r}/Move.lock`,o,"published-version",c+1+""),B(t,o,C,i,l,c+1,e.schemas),console.log(`
76
- \u{1F680} Starting Migration Process...`),u.forEach(d=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(d,null,2))}),await new Promise(d=>setTimeout(d,5e3));let w=new Pe,h=c+1,I=[];if(t!=="dubhe"){let d=await L(`${process.cwd()}/contracts/dubhe-framework`,o);I.push(w.object(d))}I.push(w.object(i)),I.push(w.pure.address(C)),I.push(w.pure.u32(h)),w.moveCall({target:`${C}::${t}_migrate::migrate_to_v${h}`,arguments:I}),await s.signAndSendTxn({tx:w,onSuccess:d=>{console.log(M.green(`Migration Transaction Digest: ${d.digest}`))},onError:d=>{console.log(M.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(d)}})}catch(m){console.log(M.red("upgrade handler execution failed!")),console.error(m.message)}}import{loadConfig as Wt}from"@0xobelisk/sui-common";var Yt={command:"upgrade",describe:"Upgrade your move contracts",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Network of the node (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",decs:"Path to the config file"}})},async handler({network:e,"config-path":t}){try{let o=await Wt(t);await Me(o,o.name,e)}catch(o){$(o),process.exit(1)}process.exit(0)}},Ne=Yt;import{execSync as Jt}from"child_process";import{loadConfig as Xt}from"@0xobelisk/sui-common";var Zt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Xt(e),c=`sui move test --path ${`${process.cwd()}/contracts/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Jt(c,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Oe=Zt;import{execSync as Qt}from"child_process";import eo from"chalk";import{loadConfig as to}from"@0xobelisk/sui-common";var oo={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await to(e),s=`${process.cwd()}/contracts/${n.name}`;await A(t),await X(s+"/Move.toml",t);let c=`sui move build --path ${s} ${o?" --dump-bytecode-as-base64":""}`,a=Qt(c,{encoding:"utf-8"});console.log(a)}catch(n){console.error(eo.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Re=oo;var no={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){H()}},Fe=no;import{Dubhe as Ae}from"@0xobelisk/sui-client";import*as G from"fs";import z from"chalk";async function je(e=!1,t=!1){t&&(console.log(z.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(z.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
77
- `)));let o=process.cwd(),n,r="";try{r=G.readFileSync(`${o}/.env`,"utf8");let s=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(s=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),s){let c=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",a=r.split(`
78
- `),l=!1;for(let u=a.length-1;u>=0;u--){let f=a[u];if(f.endsWith(s)){let[m]=f.split("=");t?l=m==="PRIVATE_KEY":l=m==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(l){for(let u=a.length-1;u>=0;u--)if(a[u].endsWith(s)){let m=`${c}=${s}`;a[u]=m,r=a.join(`
79
- `),G.writeFileSync(`${o}/.env`,r);break}}let p=new Ae({secretKey:s}).getSigner();console.log(z.blue(`Using existing account: ${p.toSuiAddress()}`));return}}catch{}if(e||!n){let c=new Ae().getSigner();n=c.getSecretKey();let l=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;r?r=r.trim()+`
80
- `+l:r=l,G.writeFileSync(`${o}/.env`,r),console.log(z.green(`File created/updated at: ${o}/.env`)),console.log(z.blue(`New account generated: ${c.toSuiAddress()}`))}}var ro={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 je(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ue=ro;import so from"chalk";import ao from"dotenv";ao.config();async function Ve(e){try{let o=await S({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(so.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var io={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await Ve(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ke=io;import{mkdirSync as co,writeFileSync as lo}from"fs";import{dirname as po}from"path";async function uo(e,t,o,n){let r=await J(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
50
+ `),process.exit(0)}},Ee=Ft;import{schemaGen as Mt,loadConfig as jt}from"@0xobelisk/sui-common";import Ot from"chalk";import Rt from"node:path";var Ht={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await jt(e),n=Rt.dirname(e);await Mt(n,o,t),process.exit(0)}catch(o){console.log(Ot.red("Schemagen failed!")),console.error(o.message)}}},Te=Ht;import{loadConfig as Ut}from"@0xobelisk/sui-common";import{execSync as zt}from"child_process";var Vt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await Ut(t);zt(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Ce(n,e,o)}catch(n){N(n),process.exit(1)}process.exit(0)}},Ie=Vt;import{execSync as Lt}from"child_process";import{loadConfig as Bt}from"@0xobelisk/sui-common";var qt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Bt(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Lt(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Ae=qt;import{execSync as Wt,exec as Kt}from"child_process";import Gt from"chalk";import{loadConfig as Yt}from"@0xobelisk/sui-common";var Jt={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await Yt(e),r=`${process.cwd()}/src/${n.name}`;await H(t),await Q(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,c=Wt(i,{encoding:"utf-8"});console.log(c),Kt(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(Gt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Ne=Jt;var Xt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){J()}},Fe=Xt;import{Dubhe as Me}from"@0xobelisk/sui-client";import*as W from"fs";import q from"chalk";async function je(e=!1,t=!1){t&&(console.log(q.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(q.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
+ `)));let o=process.cwd(),n,s="";try{s=W.readFileSync(`${o}/.env`,"utf8");let r=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(r=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),r){let i=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",c=s.split(`
52
+ `),d=!1;for(let f=c.length-1;f>=0;f--){let y=c[f];if(y.endsWith(r)){let[v]=y.split("=");t?d=v==="PRIVATE_KEY":d=v==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(d){for(let f=c.length-1;f>=0;f--)if(c[f].endsWith(r)){let v=`${i}=${r}`;c[f]=v,s=c.join(`
53
+ `),W.writeFileSync(`${o}/.env`,s);break}}let h=new Me({secretKey:r}).getSigner();console.log(q.blue(`Using existing account: ${h.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new Me().getSigner();n=i.getSecretKey();let d=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
+ `+d:s=d,W.writeFileSync(`${o}/.env`,s),console.log(q.green(`File created/updated at: ${o}/.env`)),console.log(q.blue(`New account generated: ${i.toSuiAddress()}`))}}var Zt={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 je(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Oe=Zt;import Qt from"chalk";import eo from"dotenv";eo.config();async function Re(e){try{let o=await F({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new E("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(Qt.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new E("Failed to check balance: "+t)}}var to={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await Re(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},He=to;import{mkdirSync as oo,writeFileSync as no}from"fs";import{dirname as so}from"path";async function ro(e,t,o){let n=await Z(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
81
55
 
82
56
  export const NETWORK: NetworkType = '${e}';
83
57
  export const PACKAGE_ID = '${t}';
84
- export const SCHEMA_ID = '${o}';
85
- export const DUBHE_SCHEMA_ID = '${r}';
86
- `;mo(s,n,"storeConfig")}async function mo(e,t,o){co(po(t),{recursive:!0}),lo(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Le(e,t,o){let r=`${process.cwd()}/contracts/${e.name}`,s=await T(r,t);await uo(s.network,s.packageId,s.schemaId,o)}import{loadConfig as go}from"@0xobelisk/sui-common";var fo={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await go(e);await Le(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Be=fo;import{loadConfig as ho}from"@0xobelisk/sui-common";var yo={command:"query",describe:"Query dubhe schema struct state",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},schema:{type:"string",desc:"Schema name",demandOption:!0},"object-id":{type:"string",desc:"Object ID (optional)"},"package-id":{type:"string",desc:"Package ID (optional)"},"metadata-path":{type:"string",desc:"Path to metadata JSON file (optional)"},params:{type:"array",desc:"Params for storage type: StorageValue(no params), StorageMap(1 param), StorageDoubleMap(2 params)",string:!0}},async handler({network:e,"config-path":t,schema:o,"object-id":n,"package-id":r,"metadata-path":s,params:c}){try{let a=await ho(t);await Ce({dubheConfig:a,schema:o,objectId:n,network:e,packageId:r,metadataFilePath:s,params:c})}catch(a){$(a),process.exit(1)}process.exit(0)}},qe=yo;import{loadConfig as bo}from"@0xobelisk/sui-common";var wo={command:"call",describe:"Call a function in a module",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)",default:"localnet"},module:{type:"string",desc:"Module name",demandOption:!0},function:{type:"string",desc:"Function name",demandOption:!0},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"package-id":{type:"string",desc:"Package ID (optional)"},"metadata-path":{type:"string",desc:"Path to metadata JSON file (optional)"},params:{type:"array",desc:"Params for the function",string:!0}},async handler({network:e,"config-path":t,module:o,function:n,"package-id":r,"metadata-path":s,params:c}){try{let a=await bo(t);await Se({dubheConfig:a,moduleName:o,funcName:n,network:e,packageId:r,metadataFilePath:s,params:c})}catch(a){$(a),process.exit(1)}process.exit(0)}},ze=wo;import vo from"chokidar";import{exec as xo}from"child_process";var _o={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{xo("pnpm dubhe schemagen",(n,r,s)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(s){console.error(`schemagen stderr: ${s}`);return}console.log(`schemagen stdout: ${r}`)})},o=vo.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(`
87
- Watch stopped.`),process.exit()})}},Ge=_o;import Io from"wait-on";import Co from"ora";import te from"chalk";var So={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=Co({text:`Waiting for service to start ${te.cyan(t.url)}...`,color:"cyan"});o.start();try{await Io({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(te.green("Service is ready!")),process.exit(0)}catch{o.fail(te.red("Timeout waiting for service")),console.error(te.yellow("Please make sure the service is running...")),process.exit(1)}}},He=So;var We=[ue,De,ze,qe,ke,Ee,Ne,Oe,Re,Fe,Ue,Ke,Be,Ge,He];import*as Je from"dotenv";import Ye from"chalk";Je.config();$o(ko(process.argv)).scriptName("dubhe").command(We).strict().fail((e,t)=>{console.error(Ye.red(e)),e.includes("Missing required argument")&&console.log(Ye.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),$(t),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
58
+ export const DUBHE_SCHEMA_ID = '${n}';
59
+ `;ao(s,o,"storeConfig")}async function ao(e,t,o){oo(so(t),{recursive:!0}),no(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Ue(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await ce(s,t);await ro(r.network,r.packageId,o)}import{loadConfig as io}from"@0xobelisk/sui-common";var lo={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await io(e);await Ue(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},ze=lo;import co from"chokidar";import{exec as uo}from"child_process";var po={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{uo("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=co.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(`
60
+ Watch stopped.`),process.exit()})}},Ve=po;import go from"wait-on";import mo from"ora";import oe from"chalk";var fo={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=mo({text:`Waiting for service to start ${oe.cyan(t.url)}...`,color:"cyan"});o.start();try{await go({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(oe.green("Service is ready!")),process.exit(0)}catch{o.fail(oe.red("Timeout waiting for service")),console.error(oe.yellow("Please make sure the service is running...")),process.exit(1)}}},Le=fo;var ho={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 H(e.network)}},Be=ho;import yo from"dotenv";import z from"chalk";yo.config();var bo={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=F({network:e}),o=t.getSigner();console.log(z.blue("Account Information:")),console.log(` Network: ${z.green(e)}`),console.log(` Address: ${z.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${z.green(s)} SUI`)}catch{console.log(` Balance: ${z.red("Failed to fetch balance")} ${z.gray("(Network error)")}`)}}catch(t){N(t),process.exit(1)}}},qe=bo;import{loadConfig as wo}from"@0xobelisk/sui-common";async function We(e,t,o){if(o)await B(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await ye(n,t);await B(e.name,t,s)}}var vo={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await wo(t);await We(n,e,o)}catch(n){N(n),process.exit(1)}process.exit(0)}},Ke=vo;import a from"chalk";import{spawn as xo}from"child_process";import Ge from"cli-table3";import ge from"inquirer";import*as Xe from"cli-progress";import*as w from"fs";import*as P from"path";import*as O from"os";function me(){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 D={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:P.join(O.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe-wip",binaryName:"dubhe-indexer",installDir:P.join(O.homedir(),".dubhe","bin")}};async function M(e,t=[]){return new Promise(o=>{let n=xo(e,t,{shell:!0}),s="",r="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{r+=i.toString()}),n.on("close",i=>{o({code:i||0,stdout:s,stderr:r})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:r})})})}async function $o(e,t){let o=await fetch(e,{headers:{"User-Agent":"dubhe-cli"}});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let n=o.headers.get("content-length"),s=n?parseInt(n):0,r=new Xe.SingleBar({format:a.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});s>0?r.start(Math.round(s/1024/1024*100)/100,0,{speed:"0.00"}):console.log(a.blue("\u{1F4E5} Downloading... (unable to get file size)"));let i=o.body?.getReader();if(!i)throw new Error("Unable to get response stream");let c=[],d=0,u=Date.now();try{for(;;){let{done:l,value:g}=await i.read();if(l)break;if(c.push(g),d+=g.length,s>0){let x=Math.round(d/1024/1024*100)/100,b=(Date.now()-u)/1e3,S=b>0?Math.round(x/b*100)/100:0;r.update(x,{speed:S.toFixed(2)})}}let h=c.reduce((l,g)=>l+g.length,0),f=new Uint8Array(h),y=0;for(let l of c)f.set(l,y),y+=l.length;w.writeFileSync(t,f),s>0&&r.stop();let v=Math.round(d/1024/1024*100)/100,_=(Date.now()-u)/1e3,p=_>0?Math.round(v/_*100)/100:0;console.log(a.green(`\u2713 Download completed! ${v} MB, average speed: ${p} MB/s`))}catch(h){throw s>0&&r.stop(),h}}async function fe(e,t=10,o=3){let n=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=o;s++)try{s>1&&console.log(a.gray(` Retry ${s}/${o}...`));let r=await fetch(n,{headers:{"User-Agent":"dubhe-cli",Accept:"application/vnd.github.v3+json"}});if(!r.ok)throw r.status===403?new Error(`GitHub API rate limit: ${r.status}. Please retry later or set GITHUB_TOKEN environment variable`):new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);return await r.json()}catch(r){if(s>1&&console.log(a.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${r instanceof Error?r.message:String(r)}`)),s===o)return console.error(a.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(i=>setTimeout(i,1e3*s))}return[]}function G(e,t){return e.assets.filter(n=>{let s=n.name.toLowerCase(),r=[t.platformForAsset.toLowerCase(),...t.platformForAsset==="macos"?["darwin","apple"]:[],...t.platformForAsset==="windows"?["win","win32","windows"]:[],...t.platformForAsset==="ubuntu"?["linux","gnu"]:[]],i=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],c=r.some(h=>s.includes(h)),d=i.some(h=>s.includes(h)),u=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return c&&d&&u}).map(n=>n.name)}async function ko(e,t){let o=D[e];return o?(await fe(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:G(s,t).length>0})):[]}async function Co(e){try{let t=Y();if(!t){console.log(a.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:o,configFile:n}=t,s=o==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(w.existsSync(n)&&w.readFileSync(n,"utf8").includes(e)){console.log(a.green(` \u2713 PATH already configured in ${n}`));return}let i=`# Added by dubhe doctor
61
+ ${s}`;w.appendFileSync(n,`
62
+ ${i}
63
+ `),console.log(a.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(a.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(a.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(a.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function Y(){let e=O.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:P.join(e,".zshrc")};if(t.includes("bash")){let n=P.join(e,".bash_profile"),s=P.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&w.existsSync(n)?n:s}}else if(t.includes("fish")){let n=P.join(e,".config","fish");return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:P.join(n,"config.fish")}}}let o=[{name:"zsh",file:P.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?P.join(e,".bash_profile"):P.join(e,".bashrc")},{name:"bash",file:P.join(e,".bashrc")}];for(let n of o)if(w.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||w.existsSync("/bin/zsh")?{shellName:"zsh",configFile:P.join(e,".zshrc")}:null}async function Ye(e,t){let o=D[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=me();console.log(a.gray(` System: ${n.platform}/${n.arch}`));try{console.log(a.gray(" Fetching release information..."));let s=await fe(o.repo,10);if(s.length===0)return console.error(a.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let r=null;if(t){if(r=s.find(l=>l.tag_name===t)||null,!r)return console.error(`Version ${t} not found`),!1}else for(let l of s)if(G(l,n).length>0){r=l;break}if(!r)return console.error("No compatible version found"),!1;let i=G(r,n);if(i.length===0)return console.error(`Version ${r.tag_name} has no compatible binaries`),!1;let c=i[0],d=r.assets.find(l=>l.name===c);if(!d)return console.error(`Asset file not found: ${c}`),!1;console.log(a.green(` \u2713 Found compatible version: ${r.tag_name}`)),console.log(a.gray(` Download file: ${d.name}`));try{let l=await fetch(d.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(a.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let g=l.headers.get("content-length");g&&console.log(a.gray(` File size: ${Math.round(parseInt(g)/1024/1024*100)/100} MB`))}}catch{console.log(a.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}w.existsSync(o.installDir)||(w.mkdirSync(o.installDir,{recursive:!0}),console.log(a.gray(` Created install directory: ${o.installDir}`))),console.log(a.blue(" \u{1F4E5} Downloading..."));let u=P.join(O.tmpdir(),d.name),h=3;for(let l=1;l<=h;l++)try{l>1&&console.log(a.gray(` Attempt ${l} to download...`)),await $o(d.browser_download_url,u);break}catch(g){let x=g instanceof Error?g.message:String(g);if(console.log(a.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${x}`)),l===h)throw new Error(`Download failed after ${h} attempts: ${x}`);console.log(a.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(b=>setTimeout(b,l*2e3))}console.log(a.blue(" \u{1F4E6} Extracting and installing..."));let f=P.join(O.tmpdir(),`extract_${Date.now()}`);if(w.mkdirSync(f,{recursive:!0}),d.name.endsWith(".tar.gz")||d.name.endsWith(".tgz")){let l=await M("tar",["-xzf",u,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.bz2")){let l=await M("tar",["-xjf",u,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".tar.xz")){let l=await M("tar",["-xJf",u,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(d.name.endsWith(".zip")){let l=await M("unzip",["-q",u,"-d",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${d.name}`);let y=l=>{let g=w.readdirSync(l,{withFileTypes:!0});for(let x of g){let b=P.join(l,x.name);if(x.isDirectory()){let S=y(b);if(S)return S}else if(x.name===o.binaryName||x.name===`${o.binaryName}.exe`)return b}return null},v=y(f);if(!v)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let _=P.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return w.copyFileSync(v,_),process.platform!=="win32"&&w.chmodSync(_,493),w.rmSync(u,{force:!0}),w.rmSync(f,{recursive:!0,force:!0}),console.log(a.green(" \u2705 Installation completed!")),console.log(a.gray(` Location: ${_}`)),console.log(a.gray(` Version: ${r.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(a.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(a.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await Co(o.installDir)),!0}catch(s){return console.error(a.red(`\u274C Installation failed: ${s}`)),!1}}async function _o(e){let t=me(),o=await ko(e,t);if(o.length===0)return console.log(a.red(`Unable to get version information for ${e}`)),null;let n=o.filter(r=>r.hasCompatibleAsset).slice(0,5);if(n.length===0)return console.log(a.red("No compatible versions found for current system")),null;console.log(a.blue(`
64
+ \u{1F4CB} Select version for ${e}`)),console.log(a.gray(`System: ${t.platform}/${t.arch}`)),console.log(a.gray(`Compatible versions (latest 5):
65
+ `));let s=n.map((r,i)=>({name:`${r.version} ${i===0?a.green("(latest)"):a.gray("(available)")}`,value:r.version,short:r.version}));try{let r=await ge.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new ge.Separator,{name:a.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return r.version==="cancel"?(console.log(a.gray("Installation cancelled")),null):r.version}catch{return console.log(a.gray(`
66
+ Installation cancelled`)),null}}function ne(e){let t=D[e];if(!t)return!1;let o=P.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return w.existsSync(o)}async function K(e,t="--version"){try{let o=await M(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
67
+ `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(ne(e)){let n=Y(),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:Je(e)}}}catch{if(ne(e)){let n=Y(),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:Je(e)}}}function Je(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-wip/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function So(){try{let e=await M("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 Po(){try{return(await M("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 Do(){try{let e=await M("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"}}}function Eo(e){let t={success:a.green("\u2713"),warning:a.yellow("!"),error:a.red("\u2717")},o={success:a.green("Pass"),warning:a.yellow("Warning"),error:a.red("Fail")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function To(e){if(console.log(a.bold.blue(`
68
+ \u{1F50D} Dubhe Doctor - Development Environment Checker
69
+ `)),e.listVersions){let p=e.listVersions;D[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(a.blue(`\u{1F4CB} Available versions for ${p}:`));let l=me();console.log(a.gray(`System: ${l.platform}/${l.arch}
70
+ `));let g=D[p],x=await fe(g.repo,10);x.length===0&&(console.log(a.red("Unable to get version information")),process.exit(1));let b=x.map(m=>({version:m.tag_name,hasCompatibleAsset:G(m,l).length>0,publishDate:new Date(m.published_at).toLocaleDateString("en-US")})),S=new Ge({head:[a.bold.cyan("Version"),a.bold.cyan("Compatibility"),a.bold.cyan("Release Date")],colWidths:[30,15,25]});if(b.forEach(m=>{S.push([m.version,m.hasCompatibleAsset?a.green("\u2713 Compatible"):a.red("\u2717 Incompatible"),m.publishDate])}),console.log(S.toString()),e.debug&&b.length>0){console.log(a.blue(`
71
+ \u{1F50D} Debug Information:`));let m=b.find(k=>k.hasCompatibleAsset);if(m){let k=x.find(I=>I.tag_name===m.version);if(k){console.log(a.gray(`Latest compatible version: ${m.version}`)),console.log(a.gray("Available asset files:")),k.assets.forEach(se=>{console.log(a.gray(` - ${se.name}`))});let I=G(k,l);console.log(a.gray("Compatible asset files:")),I.forEach(se=>{console.log(a.green(` \u2713 ${se}`))})}}}process.exit(0)}if(console.log(a.gray(`Checking your development environment...
72
+ `)),e.install){let p=e.install;D[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),console.log(a.gray(`Supported tools: ${Object.keys(D).join(", ")}`)),process.exit(1));let l=null;e.selectVersion&&(l=await _o(p),l||process.exit(1));let g=await Ye(p,l||void 0);process.exit(g?0:1)}let t=[];console.log(`Running checks...
73
+ `);let o=await So();t.push(o);let n=await K("pnpm");t.push(n);let s=await Do();s.status==="error"&&(s.status="warning"),t.push(s);let r=await K("docker");t.push(r);let i=null;r.status==="success"&&(i=await Po(),t.push(i));let c=await K("docker-compose");t.push(c);let d=await K("sui");t.push(d);let u=await K("dubhe-indexer");t.push(u);let h=new Ge({head:[a.bold.cyan("Check Item"),a.bold.cyan("Result"),a.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(Eo(p))}),console.log(h.toString());let f={success:t.filter(p=>p.status==="success").length,warning:t.filter(p=>p.status==="warning").length,error:t.filter(p=>p.status==="error").length};console.log(`
74
+ `+a.bold("\u{1F4CA} Check Summary:")),console.log(` ${a.green("\u2713 Passed:")} ${f.success} items`),console.log(` ${a.yellow("! Warning:")} ${f.warning} items`),console.log(` ${a.red("\u2717 Failed:")} ${f.error} items`);let y=t.filter(p=>p.status==="error"),v=y.filter(p=>D[p.name]),_=y.filter(p=>!D[p.name]);if(_.length>0&&(console.log(a.blue(`
75
+ \u{1F527} Missing tools that require manual installation:`)),_.forEach(p=>{console.log(` ${a.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),v.length>0){let p=v.filter(g=>ne(g.name)),l=v.filter(g=>!ne(g.name));if(p.length>0){let g=p.map(m=>m.name).join(", "),x=D[p[0].name]?.installDir||"~/.dubhe/bin",b=Y(),S=b?b.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.yellow(`
76
+ \u26A0\uFE0F Tools already installed but not in PATH: ${g}`)),console.log(a.gray(` Location: ${x}`)),console.log(a.blue(" To fix this, apply PATH changes:")),console.log(a.green(` source ${S}`)),console.log(a.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(a.gray(` If you want to reinstall, remove the files from ${x} and run dubhe doctor again`))}if(l.length>0){let g=l.map(x=>x.name).join(", ");console.log(a.blue(`
77
+ \u{1F680} Auto-installable tools detected: ${g}`));try{if((await ge.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${g})`,default:!0}])).installAll){console.log(a.blue(`
78
+ \u{1F4E6} Starting installation of auto-installable tools...
79
+ `));let b=[];for(let k of l){console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.blue(`\u{1F4E6} Installing ${k.name}...`)),console.log(a.blue(`${"=".repeat(60)}`));let I=await Ye(k.name);b.push({name:k.name,success:I}),I?console.log(a.green(`
80
+ \u2705 ${k.name} installation completed successfully!`)):(console.log(a.red(`
81
+ \u274C ${k.name} installation failed`)),console.log(a.gray(` Manual installation: dubhe doctor --install ${k.name}`))),console.log("")}console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.bold("\u{1F4CB} Installation Summary:")),console.log(a.blue(`${"=".repeat(60)}`)),b.forEach(k=>{let I=k.success?a.green("\u2705 Success"):a.red("\u274C Failed");console.log(` ${k.name}: ${I}`)});let S=b.filter(k=>k.success).length,m=b.length-S;if(console.log(`
82
+ ${a.green("Successful:")} ${S}/${b.length}`),m>0&&console.log(` ${a.red("Failed:")} ${m}/${b.length}`),S>0){let k=Y(),I=k?k.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.blue(`
83
+ \u{1F504} Next Steps:`)),console.log(a.yellow(" 1. Apply PATH changes by running:")),console.log(a.green(` source ${I}`)),console.log(a.yellow(" 2. Or restart your terminal")),console.log(a.yellow(" 3. Then run the doctor check again:")),console.log(a.green(" dubhe doctor")),console.log(a.gray(`
84
+ This will verify that all tools are properly configured.`))}else console.log(a.red(`
85
+ \u274C All installations failed. Please check the error messages above.`))}else console.log(a.gray(`
86
+ Auto-installation skipped. You can install them manually later:`)),l.forEach(b=>{console.log(a.gray(` dubhe doctor --install ${b.name}`))})}catch{console.log(a.gray(`
87
+ Installation cancelled. You can install them manually later:`)),l.forEach(b=>{console.log(a.gray(` dubhe doctor --install ${b.name}`))})}}}v.length===0&&(f.error>0?(console.log(a.red(`
88
+ \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),process.exit(1)):f.warning>0?console.log(a.yellow(`
89
+ \u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(a.green(`
90
+ \u2705 Congratulations! Your development environment is fully ready!`))),console.log(a.gray(`
91
+ \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var Io={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(D)}).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(D)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await To({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(a.red("Error occurred during check:"),t),process.exit(1)}}},Ze=Io;import Ao from"chalk";import{loadConfig as No}from"@0xobelisk/sui-common";import Fo from"fs";var Mo={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 No(e),n=be(o);Fo.writeFileSync(t,n)}catch(o){console.error(Ao.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},Qe=Mo;var et=[Pe,Ie,Ee,Te,Ae,Ne,Fe,Oe,He,ze,Ve,Le,Be,qe,Ke,Ze,Qe];import*as ot from"dotenv";ot.config();jo(Oo(process.argv)).scriptName("dubhe").command(et).version(L.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(tt.red(e)),e.includes("Missing required argument")&&console.log(tt.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(N(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
88
92
  //# sourceMappingURL=dubhe.js.map