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