@0xobelisk/sui-cli 1.2.0-pre.22 → 1.2.0-pre.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dubhe.js +46 -46
- package/dist/dubhe.js.map +1 -1
- package/package.json +4 -3
- package/src/commands/build.ts +2 -1
- package/src/commands/call.ts +83 -83
- package/src/commands/convertJson.ts +49 -0
- package/src/commands/doctor.ts +348 -0
- package/src/commands/index.ts +10 -7
- package/src/commands/loadMetadata.ts +50 -0
- package/src/commands/localnode.ts +19 -5
- package/src/commands/publish.ts +3 -1
- package/src/commands/query.ts +101 -101
- package/src/commands/schemagen.ts +4 -1
- package/src/commands/upgrade.ts +38 -38
- package/src/dubhe.ts +7 -7
- package/src/utils/callHandler.ts +118 -118
- package/src/utils/index.ts +2 -2
- package/src/utils/metadataHandler.ts +16 -0
- package/src/utils/publishHandler.ts +82 -266
- package/src/utils/queryStorage.ts +141 -141
- package/src/utils/startNode.ts +113 -16
- package/src/utils/storeConfig.ts +5 -11
- package/src/utils/upgradeHandler.ts +250 -250
- package/src/utils/utils.ts +161 -21
package/dist/dubhe.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import xo from"yargs";import{hideBin as Co}from"yargs/helpers";import Ue from"chalk";import{execSync as P,spawn as pe}from"child_process";import p from"chalk";import qe from"chalk";function U(){console.log(qe.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,62 +10,62 @@ Welcome to Dubhe
|
|
|
10
10
|
\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
|
|
11
11
|
\\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
|
|
12
12
|
|
|
13
|
-
`))}import{Transaction as
|
|
13
|
+
`))}import{Transaction as L}from"@0xobelisk/sui-client";import{execSync as nt}from"child_process";import y from"chalk";import*as G from"fs/promises";import{mkdirSync as Ye,writeFileSync as We}from"fs";import{dirname as Je}from"path";import{SUI_PRIVATE_KEY_PREFIX as Ge}from"@mysten/sui/cryptography";import N from"chalk";import{ZodError as Le}from"zod";import{fromZodError as He,ValidationError as Be}from"zod-validation-error";var W=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},v=class extends Error{name="DubheCliError"};function _(e){if(e instanceof Be)console.log(N.redBright(e.message));else if(e instanceof Le){let t=He(e,{prefixSeparator:`
|
|
14
14
|
- `,issueSeparator:`
|
|
15
|
-
- `});console.log(
|
|
16
|
-
\u274C Failed to execute sui command: ${c.message}`)),
|
|
17
|
-
\u274C Failed to add environment ${e}`)),console.error(
|
|
18
|
-
\u274C Failed to execute sui command: ${
|
|
19
|
-
\u274C Failed to switch to environment ${e}`)),console.error(
|
|
15
|
+
- `});console.log(N.redBright(t.message))}else e instanceof W?(console.log(N.red(e.message)),console.log(""),console.log(N.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof v?console.log(N.red(e)):console.log(e)}import*as D from"fs";import x from"chalk";import{spawn as ne}from"child_process";import{Dubhe as Xe,loadMetadata as Ze}from"@0xobelisk/sui-client";var M={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.25",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-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3",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/ejs":"^3.1.1","@types/glob":"^7.2.0","@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 X(e){if(e.startsWith(Ge))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 Z(e,t){try{let o=await G.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 V(e,t){try{let o=await G.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function K(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await V(o,"mainnet");case"testnet":return await V(o,"testnet");case"devnet":return await V(o,"devnet");case"localnet":return await V(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function se(e,t){return(await Z(e,t)).packageId}async function Q(e,t,o,n,s,r,i){let a={projectName:e,network:t,packageId:o,dappHub:n,components:i,upgradeCap:s,version:r},l=process.cwd(),c=JSON.stringify(a,null,2);await J(c,`${l}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function O(e,t,o){let n=process.cwd();try{let s=await Ze(t,o);if(s){let r=JSON.stringify(s,null,2);await J(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await J(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(x.yellow(`Warning: Failed to save metadata: ${s}`))}}async function J(e,t,o){Ye(Je(t),{recursive:!0}),We(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Qe(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${M.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${M.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function q(e,t){let o=D.readFileSync(e,"utf-8"),n=Qe(t),s=o.replace(/Dubhe = \{.*\}/,n);D.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function et(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 tt(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 et(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="",a="",l=ne("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});l.stdout.on("data",c=>{a+=c.toString()}),l.stderr.on("data",c=>{i+=c.toString()}),l.on("error",c=>{console.error(x.red(`
|
|
16
|
+
\u274C Failed to execute sui command: ${c.message}`)),r(new Error(`Failed to execute sui command: ${c.message}`))}),l.on("exit",c=>{if(i.includes("already exists")||a.includes("already exists")){console.log(x.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(c===0)console.log(x.green(`Successfully added environment ${e}`)),s();else{let g=i||a||`Process exited with code ${c}`;console.error(x.red(`
|
|
17
|
+
\u274C Failed to add environment ${e}`)),console.error(x.red(` \u2514\u2500 ${g.trim()}`)),r(new Error(g))}})})}async function I(e){try{return await tt(e),new Promise((t,o)=>{let n="",s="",r=ne("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(x.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(x.green(`Successfully switched to environment ${e}`)),t();else{let a=n||s||`Process exited with code ${i}`;console.error(x.red(`
|
|
19
|
+
\u274C Failed to switch to environment ${e}`)),console.error(x.red(` \u2514\u2500 ${a.trim()}`)),o(new Error(a))}})})}catch(t){throw t}}var E=e=>new Promise(t=>setTimeout(t,e));function ot(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new v(`Missing private key environment variable.
|
|
20
20
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
21
21
|
or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
22
|
-
in your contracts directory to use the default sui private key.`);let t=
|
|
23
|
-
`),l=
|
|
22
|
+
in your contracts directory to use the default sui private key.`);let t=X(e);if(t===!1)throw new v("Please check your privateKey.");return t}function $({network:e,packageId:t,metadata:o}){let n=ot();return new Xe({networkType:e,secretKey:n,packageId:t,metadata:o})}function re(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||{},a=r.keys||["entity_id"];return!i.entity_id&&a.includes("entity_id")&&(i.entity_id="address"),{[s]:{fields:Object.entries(i).map(([l,c])=>({[l]:c})),keys:a}}}),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||{},a=r.keys||[];return{[s]:{fields:Object.entries(i).map(([l,c])=>({[l]:c})),keys:a}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((a,l)=>a.localeCompare(l)).map((a,l)=>({[l]:a}));return{[s]:{fields:i}}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function ee(e,t){let o=`${e}/Move.toml`,s=D.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);D.writeFileSync(o,s,"utf-8")}import*as k from"fs";import*as ie from"path";async function ae(e,t){if(!k.existsSync(e))return;let o=k.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");k.writeFileSync(e,s,"utf-8")}function ce(e,t,o,n,s){let r=ie.resolve(e),i=k.readFileSync(r,"utf-8"),a=i.split(`
|
|
23
|
+
`),l=a.findIndex(d=>d.trim()===`[env.${t}]`),c={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(l===-1)if(o==="publish")c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let d=l+1;d<a.length;d++){let b=a[d].trim();if(b.startsWith("["))break;let[C,w]=b.split("=").map(S=>S.trim().replace(/"/g,""));switch(C){case"original-published-id":c.originalPublishedId=w;break;case"latest-published-id":c.latestPublishedId=w;break;case"published-version":c.publishedVersion=parseInt(w,10);break}}o==="publish"?(c.originalPublishedId=s,c.latestPublishedId=s,c.publishedVersion=1):o==="upgrade"&&(c.latestPublishedId=s,c.publishedVersion+=1)}let g=`
|
|
24
24
|
[env.${t}]
|
|
25
25
|
chain-id = "${c.chainId}"
|
|
26
26
|
original-published-id = "${c.originalPublishedId}"
|
|
27
27
|
latest-published-id = "${c.latestPublishedId}"
|
|
28
28
|
published-version = "${c.publishedVersion}"
|
|
29
|
-
`,
|
|
30
|
-
`)+
|
|
31
|
-
|
|
32
|
-
\u{
|
|
33
|
-
\u{
|
|
34
|
-
\
|
|
35
|
-
|
|
36
|
-
\u26A1 Executing Deploy Hook...`),await F(5e3);let y=new ee,$=[];if(t.name!=="dubhe"){let u=await U(o);$.push(y.object(u))}$.push(y.object("0x6")),y.moveCall({target:`${D}::${t.name}_genesis::run`,arguments:$});let g;try{g=await e.signAndSendTxn({tx:y})}catch(u){console.error(f.red(" \u2514\u2500 Deploy hook execution failed")),console.error(u.message),process.exit(1)}g.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${g.digest}`),console.log(`
|
|
37
|
-
\u{1F4CB} Created Objects:`),g.objectChanges?.map(u=>{u.type==="created"&&u.objectType&&u.objectType.includes("schema::Schema")&&(A=u.objectId||""),u.type==="created"&&u.objectType&&u.objectType.includes("schema")&&!u.objectType.includes("dynamic_field")&&x.push(u)}),x.map(u=>{console.log(` \u251C\u2500 Type: ${u.objectType}`),console.log(` \u2514\u2500 ID: ${u.objectId}`)}),L(t.name,o,D,A,k,w,R),console.log(`
|
|
29
|
+
`,u=l===-1?i+g:a.slice(0,l).join(`
|
|
30
|
+
`)+g;k.writeFileSync(r,u,"utf-8")}function le(e){let t,o;try{let n=JSON.parse(nt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(y.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function de(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(y.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function st(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 de(e);console.log(" \u251C\u2500 Validating Environment..."),await ae(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
|
|
32
|
+
\u{1F4E6} Building Contract...`);let[i,a]=le(n);console.log(`
|
|
33
|
+
\u{1F504} Publishing Contract...`);let l=new L;s&&l.setGasBudget(s);let[c]=l.publish({modules:i,dependencies:a});l.transferObjects([c],e.getAddress());let g;try{g=await e.signAndSendTxn({tx:l})}catch(m){console.error(y.red(" \u2514\u2500 Publication failed")),console.error(m.message),process.exit(1)}(!g||g.effects?.status.status==="failure")&&(console.log(y.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let u=1,d="",b="",C=t.components,w="",S=[];g.objectChanges.map(m=>{m.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${m.packageId}`),d=m.packageId||""),m.type==="created"&&m.objectType&&m.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${m.objectId}`),w=m.objectId||""),m.type==="created"&&m.objectType&&m.objectType.includes("dapp_hub::DappHub")&&(b=m.objectId||""),m.type==="created"&&S.push(m)}),console.log(` \u2514\u2500 Transaction: ${g.digest}`),ce(`${n}/Move.lock`,o,"publish",r,d),console.log(`
|
|
34
|
+
\u26A1 Executing Deploy Hook...`),await E(5e3);let h=new L,Y=[],Ke=t.name==="dubhe"?b:await K(o);Y.push(h.object(Ke)),Y.push(h.object("0x6")),h.moveCall({target:`${d}::genesis::run`,arguments:Y});let A;try{A=await e.signAndSendTxn({tx:h})}catch(m){console.error(y.red(" \u2514\u2500 Deploy hook execution failed")),console.error(m.message),process.exit(1)}if(A.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${A.digest}`),console.log(`
|
|
35
|
+
\u{1F4CB} Created Objects:`),S.map(oe=>{console.log(` \u251C\u2500 Type: ${oe.objectType}`),console.log(` \u2514\u2500 ID: ${oe.objectId}`)}),await Q(t.name,o,d,b,w,u,C),await O(t.name,o,d);let m=JSON.parse(k.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));m.package_id=d,k.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(m,null,2)),console.log(`
|
|
38
36
|
\u2705 Contract Publication Complete
|
|
39
|
-
`)
|
|
40
|
-
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(
|
|
41
|
-
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let
|
|
42
|
-
|
|
43
|
-
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function
|
|
44
|
-
\
|
|
45
|
-
\
|
|
46
|
-
\u274C Failed to Start Local Node`)),console.error(
|
|
47
|
-
\
|
|
48
|
-
\
|
|
49
|
-
\
|
|
37
|
+
`)}else console.log(y.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(y.yellow(" Please republish or manually call deploy_hook::run")),console.log(y.yellow(" Please check the transaction digest:")),console.log(y.yellow(` ${A.digest}`)),process.exit(1)}async function rt(e){return k.existsSync(e)?!0:(console.log(y.yellow(`
|
|
38
|
+
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(y.yellow(" \u251C\u2500 Expected Path:"),e),console.log(y.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(y.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(y.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(y.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(y.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function it(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await rt(n))return;console.log(`
|
|
39
|
+
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await de(e);await ae(`${n}/Move.lock`,t),await ee(n,"0x0");let[r,i]=le(n),a=new L,[l]=a.publish({modules:r,dependencies:i});a.transferObjects([l],e.getAddress());let c;try{c=await e.signAndSendTxn({tx:a})}catch(h){console.error(y.red(" \u2514\u2500 Publication failed")),console.error(h.message),process.exit(1)}(!c||c.effects?.status.status==="failure")&&(console.log(y.red(" \u2514\u2500 Publication failed")),process.exit(1));let g=1,u="",d="",b={},C="";c.objectChanges.map(h=>{h.type==="published"&&(u=h.packageId||""),h.type==="created"&&h.objectType&&h.objectType==="0x2::package::UpgradeCap"&&(C=h.objectId||""),h.type==="created"&&h.objectType&&h.objectType.includes("dapp_hub::DappHub")&&(d=h.objectId||"")}),await E(3e3);let w=new L;w.moveCall({target:`${u}::dubhe_genesis::run`,arguments:[w.object(d),w.object("0x6")]});let S;try{S=await e.signAndSendTxn({tx:w})}catch(h){console.error(y.red(" \u2514\u2500 Deploy hook execution failed")),console.error(h.message),process.exit(1)}if(S.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await ee(n,u),await Q("dubhe",t,u,d,C,g,b),ce(`${n}/Move.lock`,t,"publish",s,u)}async function ue(e,t,o){await I(t);let n=$({network:t}),r=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await it(n,t),e.name!=="dubhe"&&await q(`${r}/Move.toml`,t),await st(n,e,t,r,o)}import{Dubhe as at}from"@0xobelisk/sui-client";import*as H from"fs";function ct(){console.log(p.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{P("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=P(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
|
|
40
|
+
`).filter(r=>r);console.log(p.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{P(`kill -TERM ${r}`,{stdio:"ignore"}),console.log(p.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{P(`kill -KILL ${r}`,{stdio:"ignore"}),console.log(p.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log(p.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?p.green(" \u2514\u2500 Local Node stopped successfully"):p.gray(" \u2514\u2500 No running Local Node found"))}function lt(e){try{H.existsSync(e)?(console.log(p.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),H.rmSync(e,{recursive:!0,force:!0}),console.log(p.green(" \u2514\u2500 Directory removed successfully"))):console.log(p.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(p.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function dt(){try{if(process.platform==="win32")return P('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=P(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function ut(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new at({secretKey:t}).getSigner();pe("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(p.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(p.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function pt(e){let t=()=>{console.log(p.yellow(`
|
|
41
|
+
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function me(e,t){if(t)console.log(p.cyan(`
|
|
42
|
+
\u{1F504} Force mode enabled`)),ct(),console.log(p.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await E(3e3),lt(e),console.log("");else if(dt()){console.log(p.yellow(`
|
|
43
|
+
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(p.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(p.yellow(" \u2514\u2500 Please stop the existing process first"));return}U(),console.log("\u{1F680} Starting Local Node...");let o=null;try{if(o=pe("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(p.red(`
|
|
44
|
+
\u274C Failed to Start Local Node`)),console.error(p.red(` \u2514\u2500 Error: ${s.message}`))}),await E(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 ut(),await E(2e3),X("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new v("Please check your privateKey.");console.log(p.green("\u{1F389} Local environment is ready!")),pt(o),await new Promise(s=>{o?.on("exit",()=>s())})}catch(n){console.error(p.red(`
|
|
45
|
+
\u274C Failed to Start Local Node`)),console.error(p.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var mt={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 me(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},ge=mt;import{requestSuiFromFaucetV0 as gt,getFaucetHost as ft}from"@mysten/sui/faucet";import{SuiClient as ht,getFullnodeUrl as yt}from"@mysten/sui/client";var te=60,bt=1e3,fe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],wt={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=$(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(),a=!1,l=()=>{a=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
47
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",l);try{for(;n<te&&!s&&!a;)try{await gt({host:ft(e),recipient:o}),s=!0}catch{if(a)break;n++,n===te&&(console.log(` \u2514\u2500 Failed to request funds after ${te} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let b=Math.floor((Date.now()-i)/1e3),C=fe[r%fe.length];r++,process.stdout.write(`\r \u251C\u2500 ${C} Retrying... (${b}s)`),await new Promise(w=>setTimeout(w,bt))}}finally{process.removeListener("SIGINT",l)}a&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let c=new ht({url:yt(e)}),g={owner:o},u=await c.getBalance(g);console.log(`
|
|
48
|
+
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(u.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
|
|
50
49
|
\u2705 Faucet Operation Complete
|
|
51
|
-
`),process.exit(0)}},
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
`),i=a.findIndex(d=>d.trim()===`[env.${t}]`);if(i===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let l=-1,c="";for(let d=i+1;d<a.length;d++){let p=a[d].trim();if(p.startsWith("["))break;if(p.startsWith(o)){l=d,c=p.split("=")[1].trim().replace(/"/g,"");break}}if(l!==-1){a[l]=`${o} = "${n}"`;let d=a.join(`
|
|
57
|
-
`);q.writeFileSync(r,d,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return c}async function Oe(e,t,o){await O(o);let n=process.cwd(),r=`${n}/src/${t}`,s=_({network:o}),a=Number(await ue(r,o)),i=await V(r,o),l=await me(r,o),c=await Z(r,o),d=te(`${r}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),p=[],h=await pe(r,o);Object.entries(e.schemas).forEach(([m,b])=>{h.hasOwnProperty(m)||p.push({schemaName:m,fields:b})}),Jt(r,p);try{let m,b,I;try{let{modules:g,dependencies:u,digest:ne}=JSON.parse(Yt(`sui move build --dump-bytecode-as-base64 --path ${n}/src/${t}`,{encoding:"utf-8"}));m=g,b=u,I=ne}catch(g){throw new Y(g.stdout)}console.log(`
|
|
58
|
-
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",i),console.log("\u{1F4CB} UpgradeCap Object Id:",l),console.log("\u{1F4CB} OldVersion:",a);let w=new Te,D=w.moveCall({target:"0x2::package::authorize_upgrade",arguments:[w.object(l),w.pure.u8(Wt.COMPATIBLE),w.pure.vector("u8",I)]}),A=w.upgrade({modules:m,dependencies:b,package:i,ticket:D});w.moveCall({target:"0x2::package::commit_upgrade",arguments:[w.object(l),A]});let R=await s.signAndSendTxn({tx:w,onSuccess:g=>{console.log(j.green(`Upgrade Transaction Digest: ${g.digest}`))},onError:g=>{console.log(j.red("Upgrade Transaction failed!")),console.error(g)}}),k="";R.objectChanges.map(g=>{g.type==="published"&&(console.log(j.blue(`${t} new PackageId: ${g.packageId}`)),console.log(j.blue(`${t} new Version: ${a+1}`)),k=g.packageId)}),te(`${r}/Move.lock`,o,"original-published-id",d),te(`${r}/Move.lock`,o,"latest-published-id",k),te(`${r}/Move.lock`,o,"published-version",a+1+""),L(t,o,k,c,l,a+1,e.schemas),console.log(`
|
|
59
|
-
\u{1F680} Starting Migration Process...`),p.forEach(g=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(g,null,2))}),await new Promise(g=>setTimeout(g,5e3));let x=new Te,y=a+1,$=[];if(t!=="dubhe"){let g=await U(o);$.push(x.object(g))}$.push(x.object(c)),$.push(x.pure.address(k)),$.push(x.pure.u32(y)),x.moveCall({target:`${k}::${t}_migrate::migrate_to_v${y}`,arguments:$}),await s.signAndSendTxn({tx:x,onSuccess:g=>{console.log(j.green(`Migration Transaction Digest: ${g.digest}`))},onError:g=>{console.log(j.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(g)}})}catch(m){console.log(j.red("upgrade handler execution failed!")),console.error(m.message)}}import{loadConfig as Xt}from"@0xobelisk/sui-common";var Zt={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 Xt(t);await Oe(o,o.name,e)}catch(o){S(o),process.exit(1)}process.exit(0)}},Ne=Zt;import{execSync as Qt}from"child_process";import{loadConfig as eo}from"@0xobelisk/sui-common";var to={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 eo(e),a=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Qt(a,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Fe=to;import{execSync as oo}from"child_process";import no from"chalk";import{loadConfig as ro}from"@0xobelisk/sui-common";var so={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 ro(e),s=`${process.cwd()}/src/${n.name}`;await O(t),await Q(s+"/Move.toml",t);let a=`sui move build --path ${s} ${o?" --dump-bytecode-as-base64":""}`,i=oo(a,{encoding:"utf-8"});console.log(i)}catch(n){console.error(no.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},je=so;var ao={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){W()}},Ae=ao;import{Dubhe as Re}from"@0xobelisk/sui-client";import*as H from"fs";import G from"chalk";async function Ue(e=!1,t=!1){t&&(console.log(G.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(G.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
|
|
60
|
-
`)));let o=process.cwd(),n,r="";try{r=H.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 a=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",i=r.split(`
|
|
61
|
-
`),l=!1;for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.endsWith(s)){let[m]=h.split("=");t?l=m==="PRIVATE_KEY":l=m==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(l){for(let p=i.length-1;p>=0;p--)if(i[p].endsWith(s)){let m=`${a}=${s}`;i[p]=m,r=i.join(`
|
|
62
|
-
`),H.writeFileSync(`${o}/.env`,r);break}}let d=new Re({secretKey:s}).getSigner();console.log(G.blue(`Using existing account: ${d.toSuiAddress()}`));return}}catch{}if(e||!n){let a=new Re().getSigner();n=a.getSecretKey();let l=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;r?r=r.trim()+`
|
|
63
|
-
`+l:r=l,H.writeFileSync(`${o}/.env`,r),console.log(G.green(`File created/updated at: ${o}/.env`)),console.log(G.blue(`New account generated: ${a.toSuiAddress()}`))}}var io={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 Ue(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ve=io;import co from"chalk";import lo from"dotenv";lo.config();async function qe(e){try{let o=await _({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(co.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var po={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 qe(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ke=po;import{mkdirSync as uo,writeFileSync as mo}from"fs";import{dirname as go}from"path";async function fo(e,t,o,n){let r=await U(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
50
|
+
`),process.exit(0)}},he=wt;import{schemaGen as vt,loadConfig as kt}from"@0xobelisk/sui-common";import xt from"chalk";import Ct from"node:path";var _t={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 kt(e),n=Ct.dirname(e);await vt(n,o,t),process.exit(0)}catch(o){console.log(xt.red("Schemagen failed!")),console.error(o.message)}}},ye=_t;import{loadConfig as $t}from"@0xobelisk/sui-common";import{execSync as St}from"child_process";var Et={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 $t(t);St(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await ue(n,e,o)}catch(n){_(n),process.exit(1)}process.exit(0)}},be=Et;import{execSync as Dt}from"child_process";import{loadConfig as It}from"@0xobelisk/sui-common";var Pt={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 It(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Dt(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},we=Pt;import{execSync as Tt,exec as Nt}from"child_process";import Mt from"chalk";import{loadConfig as Ot}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 Ot(e),r=`${process.cwd()}/src/${n.name}`;await I(t),await q(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,a=Tt(i,{encoding:"utf-8"});console.log(a),Nt(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(Mt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},ve=jt;var Rt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){U()}},ke=Rt;import{Dubhe as xe}from"@0xobelisk/sui-client";import*as R from"fs";import j from"chalk";async function Ce(e=!1,t=!1){t&&(console.log(j.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(j.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
|
|
51
|
+
`)));let o=process.cwd(),n,s="";try{s=R.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",a=s.split(`
|
|
52
|
+
`),l=!1;for(let u=a.length-1;u>=0;u--){let d=a[u];if(d.endsWith(r)){let[b]=d.split("=");t?l=b==="PRIVATE_KEY":l=b==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(l){for(let u=a.length-1;u>=0;u--)if(a[u].endsWith(r)){let b=`${i}=${r}`;a[u]=b,s=a.join(`
|
|
53
|
+
`),R.writeFileSync(`${o}/.env`,s);break}}let g=new xe({secretKey:r}).getSigner();console.log(j.blue(`Using existing account: ${g.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new xe().getSigner();n=i.getSecretKey();let l=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
|
|
54
|
+
`+l:s=l,R.writeFileSync(`${o}/.env`,s),console.log(j.green(`File created/updated at: ${o}/.env`)),console.log(j.blue(`New account generated: ${i.toSuiAddress()}`))}}var Ft={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 Ce(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},_e=Ft;import At from"chalk";import Ut from"dotenv";Ut.config();async function $e(e){try{let o=await $({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(At.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var Vt={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 $e(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Se=Vt;import{mkdirSync as Kt,writeFileSync as qt}from"fs";import{dirname as Lt}from"path";async function Ht(e,t,o){let n=await K(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
64
55
|
|
|
65
56
|
export const NETWORK: NetworkType = '${e}';
|
|
66
57
|
export const PACKAGE_ID = '${t}';
|
|
67
|
-
export const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
58
|
+
export const DUBHE_SCHEMA_ID = '${n}';
|
|
59
|
+
`;Bt(s,o,"storeConfig")}async function Bt(e,t,o){Kt(Lt(t),{recursive:!0}),qt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Ee(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await Z(s,t);await Ht(r.network,r.packageId,o)}import{loadConfig as zt}from"@0xobelisk/sui-common";var Yt={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 zt(e);await Ee(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},De=Yt;import Wt from"chokidar";import{exec as Jt}from"child_process";var Gt={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{Jt("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=Wt.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()})}},Ie=Gt;import Xt from"wait-on";import Zt from"ora";import B from"chalk";var Qt={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=Zt({text:`Waiting for service to start ${B.cyan(t.url)}...`,color:"cyan"});o.start();try{await Xt({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(B.green("Service is ready!")),process.exit(0)}catch{o.fail(B.red("Timeout waiting for service")),console.error(B.yellow("Please make sure the service is running...")),process.exit(1)}}},Pe=Qt;var eo={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 I(e.network)}},Te=eo;import to from"dotenv";import T from"chalk";to.config();var oo={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=$({network:e}),o=t.getSigner();console.log(T.blue("Account Information:")),console.log(` Network: ${T.green(e)}`),console.log(` Address: ${T.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${T.green(s)} SUI`)}catch{console.log(` Balance: ${T.red("Failed to fetch balance")} ${T.gray("(Network error)")}`)}}catch(t){_(t),process.exit(1)}}},Ne=oo;import{loadConfig as no}from"@0xobelisk/sui-common";async function Me(e,t,o){if(o)await O(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await se(n,t);await O(e.name,t,s)}}var so={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 no(t);await Me(n,e,o)}catch(n){_(n),process.exit(1)}process.exit(0)}},Oe=so;import f from"chalk";import{spawn as ro}from"child_process";import{existsSync as io}from"fs";import{homedir as ao}from"os";import{join as co}from"path";import lo from"cli-table3";async function z(e,t=[]){return new Promise(o=>{let n=ro(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 F(e,t="--version"){try{let o=await z(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
|
|
61
|
+
`)[0];return{name:e,status:"success",message:`Installed ${n}`}}else return{name:e,status:"error",message:"Not installed",fixSuggestion:je(e)}}catch{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:"Visit https://docs.sui.io/guides/developer/getting-started/sui-install to install Sui CLI",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js",git:"Visit https://git-scm.com/downloads to install Git"}[e]||`Please install ${e}`}function uo(e,t){let o=io(e);return{name:t,status:o?"success":"warning",message:o?"Available":"Not found",fixSuggestion:o?void 0:`Please create file: ${e}`}}async function po(){try{let e=await z("node",["--version"]);if(e.code===0){let t=e.stdout.trim();return parseFloat(t.replace("v",""))>=18?{name:"Node.js version",status:"success",message:`${t} (meets requirement >=18.0)`}:{name:"Node.js version",status:"warning",message:`${t} (recommend upgrade to >=18.0)`,fixSuggestion:"Please upgrade Node.js to 18.0 or higher"}}else return{name:"Node.js version",status:"error",message:"Not installed",fixSuggestion:"Please install Node.js 18.0 or higher"}}catch{return{name:"Node.js version",status:"error",message:"Check failed",fixSuggestion:"Please install Node.js"}}}async function mo(){try{return(await z("docker",["info"])).code===0?{name:"Docker service",status:"success",message:"Running"}:{name:"Docker service",status:"warning",message:"Not running",fixSuggestion:"Please start Docker service"}}catch{return{name:"Docker service",status:"error",message:"Check failed",fixSuggestion:"Please install and start Docker"}}}async function go(){try{let e=await z("npm",["config","get","registry"]);return e.code===0?{name:"NPM configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM config: npm config list"}}catch{return{name:"NPM configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}function fo(e){let t={success:f.green("\u2713"),warning:f.yellow("!"),error:f.red("\u2717")},o={success:f.green("YES"),warning:f.yellow("WARN"),error:f.red("NO")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function ho(){console.log(f.bold.blue(`
|
|
62
|
+
\u{1F50D} Dubhe Doctor - Environment Check Tool
|
|
63
|
+
`)),console.log(f.gray(`Checking your development environment...
|
|
64
|
+
`));let e=[];console.log(`Running checks...
|
|
65
|
+
`);let t=await po();e.push(t);let o=await F("pnpm");e.push(o);let n=await F("git");e.push(n);let s=await go();s.status==="error"&&(s.status="warning"),e.push(s);let r=await F("docker");e.push(r);let i=null;r.status==="success"&&(i=await mo(),e.push(i));let a=await F("docker-compose");e.push(a);let l=await F("sui");e.push(l);let c=uo(co(ao(),".gitconfig"),"Git configuration");e.push(c);let g=new lo({head:[f.bold.cyan("Criteria"),f.bold.cyan("Result"),f.bold.cyan("Fix")],colWidths:[25,15,50],style:{head:["cyan"],border:["grey"]},wordWrap:!0});e.forEach(d=>{g.push(fo(d))}),console.log(g.toString());let u={success:e.filter(d=>d.status==="success").length,warning:e.filter(d=>d.status==="warning").length,error:e.filter(d=>d.status==="error").length};console.log(`
|
|
66
|
+
`+f.bold("\u{1F4CA} Check Summary:")),console.log(` ${f.green("\u2713 Passed:")} ${u.success} items`),console.log(` ${f.yellow("! Warning:")} ${u.warning} items`),console.log(` ${f.red("\u2717 Error:")} ${u.error} items`),u.error>0?(console.log(f.red(`
|
|
67
|
+
\u274C Your environment has some issues, please fix them according to the suggestions above.`)),process.exit(1)):u.warning>0?console.log(f.yellow(`
|
|
68
|
+
\u26A0\uFE0F Your environment is basically ready, but it is recommended to fix warning items for a better development experience.`)):console.log(f.green(`
|
|
69
|
+
\u2705 Congratulations! Your development environment is fully ready!`)),console.log(f.gray(`
|
|
70
|
+
\u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var yo={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("verbose",{alias:"v",type:"boolean",description:"Show verbose output",default:!1})},async handler(){try{await ho()}catch(e){console.error(f.red("Error occurred during check:"),e),process.exit(1)}}},Re=yo;import bo from"chalk";import{loadConfig as wo}from"@0xobelisk/sui-common";import vo from"fs";var ko={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 wo(e),n=re(o);vo.writeFileSync(t,n)}catch(o){console.error(bo.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},Fe=ko;var Ae=[ge,be,he,ye,we,ve,ke,_e,Se,De,Ie,Pe,Te,Ne,Oe,Re,Fe];import*as Ve from"dotenv";Ve.config();xo(Co(process.argv)).scriptName("dubhe").command(Ae).version(M.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(Ue.red(e)),e.includes("Missing required argument")&&console.log(Ue.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(_(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
|
|
71
71
|
//# sourceMappingURL=dubhe.js.map
|