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