@0xobelisk/sui-cli 1.2.0-pre.1 → 1.2.0-pre.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dubhe.js +38 -56
- package/dist/dubhe.js.map +1 -1
- package/package.json +3 -3
- package/src/commands/localnode.ts +2 -8
- package/src/utils/publishHandler.ts +12 -3
- package/src/utils/startNode.ts +55 -97
- package/src/utils/utils.ts +4 -3
package/dist/dubhe.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Io from"yargs";import{hideBin as Co}from"yargs/helpers";import{execSync as Ct,spawn as _e}from"child_process";import $ from"chalk";import Ze from"chalk";function H(){console.log(Ze.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,79 +10,61 @@ Welcome to Dubhe
|
|
|
10
10
|
\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
|
|
11
11
|
\\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
|
|
12
12
|
|
|
13
|
-
`))}import{
|
|
14
|
-
- address: "0xe7f93ad7493035bcd674f287f78526091e195a6df9d64f23def61a7ce3adada9"
|
|
15
|
-
gas_amounts:
|
|
16
|
-
- 100000000000000
|
|
17
|
-
- address: "0x492404a537c32b46610bd6ae9f7f16ba16ff5a607d272543fe86cada69d8cf44"
|
|
18
|
-
gas_amounts:
|
|
19
|
-
- 100000000000000
|
|
20
|
-
- address: "0xd27e203483700d837a462d159ced6104619d8e36f737bf2a20c251153bf39f24"
|
|
21
|
-
gas_amounts:
|
|
22
|
-
- 100000000000000
|
|
23
|
-
- address: "0x018f1f175c9b6739a14bc9c81e7984c134ebf9031015cf796fefcef04b8c4990"
|
|
24
|
-
gas_amounts:
|
|
25
|
-
- 100000000000000
|
|
26
|
-
- address: "0x932f6aab2bc636a25374f99794dc8451c4e27c91e87083e301816ed08bc98ed0"
|
|
27
|
-
gas_amounts:
|
|
28
|
-
- 100000000000000
|
|
29
|
-
- address: "0x9a66b2da3036badd22529e3de8a00b0cd7dbbfe589873aa03d5f885f5f8c6501"
|
|
30
|
-
gas_amounts:
|
|
31
|
-
- 100000000000000
|
|
32
|
-
`;et(R(e,"sui.yaml"),o),console.log(" \u251C\u2500 Initializing genesis..."),ne(`sui genesis --working-dir ${t} -f --from-config ${R(e,"sui.yaml")}`)}function st(e){let t=()=>{console.log(D.yellow(`
|
|
33
|
-
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function pe(e={}){if(tt()){console.log(D.yellow(`
|
|
34
|
-
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(D.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(D.yellow(" \u2514\u2500 Please stop the existing process first"));return}H(),console.log("\u{1F680} Starting Local Node...");let t=null;try{let{nodeLogsDir:o,logsDir:n}=await nt();e.forceRegenesis?(console.log(" \u251C\u2500 Force Regenesis: Yes"),await rt(o,n)):console.log(" \u251C\u2500 Force Regenesis: No"),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await ot(),console.log(D.green("\u{1F389} Local environment is ready!")),t=Qe("sui",["start","--with-faucet","--network.config",R(n,"network.yaml")],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),st(t),await new Promise(r=>{t?.on("exit",()=>r())})}catch(o){console.error(D.red(`
|
|
35
|
-
\u274C Failed to Start Local Node`)),console.error(D.red(` \u2514\u2500 Error: ${o.message}`)),t&&t.kill("SIGINT"),process.exit(1)}}var at={command:"node",describe:"Manage local Sui node",builder(e){return e.option("force-regenesis",{alias:"f",type:"boolean",description:"Force regenesis the local node",default:!0})},async handler(e){try{await pe({forceRegenesis:e["force-regenesis"]})}catch(t){console.error("Error executing command:",t),process.exit(1)}}},ue=at;import{requestSuiFromFaucetV0 as Nt,getFaucetHost as Ot}from"@mysten/sui/faucet";import{SuiClient as Rt,getFullnodeUrl as Ft}from"@mysten/sui/client";import{Transaction as Q}from"@0xobelisk/sui-client";import{execSync as vt}from"child_process";import g from"chalk";import*as ae from"fs/promises";import{mkdirSync as dt,writeFileSync as pt}from"fs";import{dirname as ut}from"path";import{SUI_PRIVATE_KEY_PREFIX as mt}from"@mysten/sui/cryptography";import V from"chalk";import{ZodError as it}from"zod";import{fromZodError as ct,ValidationError as lt}from"zod-validation-error";var re=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},v=class extends Error{name="DubheCliError"},W=class extends Error{name="UpgradeError"};function $(e){if(e instanceof lt)console.log(V.redBright(e.message));else if(e instanceof it){let t=ct(e,{prefixSeparator:`
|
|
13
|
+
`))}import{Transaction as Z}from"@0xobelisk/sui-client";import{execSync as ut}from"child_process";import f from"chalk";import*as se from"fs/promises";import{mkdirSync as nt,writeFileSync as rt}from"fs";import{dirname as st}from"path";import{SUI_PRIVATE_KEY_PREFIX as at}from"@mysten/sui/cryptography";import V from"chalk";import{ZodError as Qe}from"zod";import{fromZodError as et,ValidationError as tt}from"zod-validation-error";var oe=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},v=class extends Error{name="DubheCliError"},W=class extends Error{name="UpgradeError"};function E(e){if(e instanceof tt)console.log(V.redBright(e.message));else if(e instanceof Qe){let t=et(e,{prefixSeparator:`
|
|
36
14
|
- `,issueSeparator:`
|
|
37
|
-
- `});console.log(V.redBright(t.message))}else e instanceof
|
|
38
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
39
|
-
\u274C Process exited with code: ${r}`)),o(new Error(`Process exited with code: ${r}`))):t()})})}catch(t){console.error(
|
|
40
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
15
|
+
- `});console.log(V.redBright(t.message))}else e instanceof oe?(console.log(V.red(e.message)),console.log(""),console.log(V.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof v?console.log(V.red(e)):console.log(e)}import*as Y from"fs";import q from"chalk";import{spawn as it}from"child_process";import{Dubhe as ct}from"@0xobelisk/sui-client";var ne={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.11",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",publishConfig:{access:"public"},engines:{node:">=18"},exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"}};function ae(e){if(e.startsWith(at))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 M(e,t){try{let o=await se.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 re(e,t){try{let o=await se.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).schemaId}catch{return""}}async function J(e){let o=`${process.cwd()}/contracts/dubhe-framework`;switch(e){case"mainnet":return await re(o,"mainnet");case"testnet":return"0xa565cbb3641fff8f7e8ef384b215808db5f1837aa72c1cca1803b5d973699aac";case"devnet":return await re(o,"devnet");case"localnet":return await re(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function le(e,t){return(await M(e,t)).schemas}async function de(e,t){return(await M(e,t)).version}async function R(e,t){return(await M(e,t)).packageId}async function K(e,t){return(await M(e,t)).schemaId}async function pe(e,t){return(await M(e,t)).upgradeCap}function L(e,t,o,n,r,s,c){let a={projectName:e,network:t,packageId:o,schemaId:n,schemas:c,upgradeCap:r,version:s},l=process.cwd(),i=JSON.stringify(a,null,2);lt(i,`${l}/contracts/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function lt(e,t,o){nt(st(t),{recursive:!0}),rt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function dt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/contracts/dubhe", rev = "${ne.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/contracts/dubhe", rev = "${ne.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function X(e,t){let o=Y.readFileSync(e,"utf-8"),n=dt(t),r=o.replace(/Dubhe = \{.*\}/,n);Y.writeFileSync(e,r,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function A(e){try{return new Promise((t,o)=>{let n=it("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});n.on("error",r=>{console.error(q.red(`
|
|
16
|
+
\u274C Failed to Switch Env`)),console.error(q.red(` Error: ${r.message}`)),o(r)}),n.on("exit",r=>{r!==0?(console.error(q.red(`
|
|
17
|
+
\u274C Process exited with code: ${r}`)),o(new Error(`Process exited with code: ${r}`))):t()})})}catch(t){console.error(q.red(`
|
|
18
|
+
\u274C Failed to Switch Env`)),console.error(q.red(` \u2514\u2500 Error: ${t}`))}}var O=e=>new Promise(t=>setTimeout(t,e));function pt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new v(`Missing private key environment variable.
|
|
41
19
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
42
20
|
or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
43
|
-
in your contracts directory to use the default sui private key.`);let t=
|
|
44
|
-
`),l=a.findIndex(
|
|
21
|
+
in your contracts directory to use the default sui private key.`);let t=ae(e);if(t===!1)throw new v("Please check your privateKey.");return t}function C({network:e,packageId:t,metadata:o}){let n=pt();return new ct({networkType:e,secretKey:n,packageId:t,metadata:o})}import*as T from"fs";import*as ue from"path";var _=60,z=1e3,D=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];async function me(e,t){if(!T.existsSync(e))return;let o=T.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),r=o.replace(n,"");T.writeFileSync(e,r,"utf-8")}function ge(e,t,o,n,r){let s=ue.resolve(e),c=T.readFileSync(s,"utf-8"),a=c.split(`
|
|
22
|
+
`),l=a.findIndex(h=>h.trim()===`[env.${t}]`),i={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(l===-1)if(o==="publish")i.originalPublishedId=r,i.latestPublishedId=r,i.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let h=l+1;h<a.length;h++){let m=a[h].trim();if(m.startsWith("["))break;let[b,k]=m.split("=").map(w=>w.trim().replace(/"/g,""));switch(b){case"original-published-id":i.originalPublishedId=k;break;case"latest-published-id":i.latestPublishedId=k;break;case"published-version":i.publishedVersion=parseInt(k,10);break}}o==="publish"?(i.originalPublishedId=r,i.latestPublishedId=r,i.publishedVersion=1):o==="upgrade"&&(i.latestPublishedId=r,i.publishedVersion+=1)}let d=`
|
|
45
23
|
[env.${t}]
|
|
46
24
|
chain-id = "${i.chainId}"
|
|
47
25
|
original-published-id = "${i.originalPublishedId}"
|
|
48
26
|
latest-published-id = "${i.latestPublishedId}"
|
|
49
27
|
published-version = "${i.publishedVersion}"
|
|
50
|
-
`,
|
|
51
|
-
`)+
|
|
52
|
-
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",a);try{for(;t<
|
|
53
|
-
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let s=await
|
|
54
|
-
\u{1F4E6} Building Contract...`);let[c,a]=
|
|
55
|
-
\u{1F504} Publishing Contract...`);let l=new
|
|
56
|
-
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",
|
|
57
|
-
\u26A1 Executing Deploy Hook...`),await
|
|
58
|
-
\u{1F4CB} Created
|
|
28
|
+
`,p=l===-1?c+d:a.slice(0,l).join(`
|
|
29
|
+
`)+d;T.writeFileSync(s,p,"utf-8")}function fe(e){let t,o;try{let n=JSON.parse(ut(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(f.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function he(e){let t=0,o=0,n=Date.now(),r=!1,s="",c=!1,a=()=>{r=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
30
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",a);try{for(;t<_&&!r&&!s;){try{s=await e.suiInteractor.currentClient.getChainIdentifier()}catch{}if(r)break;if(!s){t++,t===_&&(console.log(f.red(` \u2514\u2500 Failed to connect to node after ${_} attempts`)),console.log(f.red(" \u2514\u2500 Please check if the Sui node is running.")),process.exit(1));let l=Math.floor((Date.now()-n)/1e3),i=D[o%D.length];o++,process.stdout.write(`\r \u251C\u2500 ${i} Waiting for node... (${l}s)`),await new Promise(d=>setTimeout(d,z))}}for(process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(` \u251C\u2500 ChainId: ${s}`),t=0;t<_&&!r;)try{let l=e.getAddress(),i=await e.suiInteractor.currentClient.getCoins({owner:l,coinType:"0x2::sui::SUI"});if(i.data.length>0){let h=i.data.reduce((m,b)=>m+Number(b.balance),0);if(h>0)return process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(` \u251C\u2500 Deployer balance: ${h/10**9} SUI`),s;c||(process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(f.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance")),c=!0)}else c||(process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(f.yellow(" \u251C\u2500 No SUI coins found in deployer account, please ensure your account has sufficient SUI balance")),c=!0);t++,t===_&&(console.log(f.red(` \u2514\u2500 Deployer account has no SUI balance after ${_} attempts`)),console.log(f.red(" \u2514\u2500 Please ensure your account has sufficient SUI balance.")),process.exit(1));let d=Math.floor((Date.now()-n)/1e3),p=D[o%D.length];o++,process.stdout.write(`\r \u251C\u2500 ${p} Checking deployer balance... (${d}s)`),await new Promise(h=>setTimeout(h,z))}catch{if(r)break;t++,t===_&&(console.log(f.red(` \u2514\u2500 Failed to check deployer balance after ${_} attempts`)),console.log(f.red(" \u2514\u2500 Please check your account and network connection.")),process.exit(1));let i=Math.floor((Date.now()-n)/1e3),d=D[o%D.length];o++,process.stdout.write(`\r \u251C\u2500 ${d} Checking deployer balance... (${i}s)`),await new Promise(p=>setTimeout(p,z))}}finally{process.removeListener("SIGINT",a)}throw r&&process.exit(0),new Error("Failed to connect to node")}async function mt(e,t,o,n,r){console.log(`
|
|
31
|
+
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let s=await he(e);console.log(" \u251C\u2500 Validating Environment..."),await me(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
|
|
32
|
+
\u{1F4E6} Building Contract...`);let[c,a]=fe(n);console.log(`
|
|
33
|
+
\u{1F504} Publishing Contract...`);let l=new Z;r&&l.setGasBudget(r);let[i]=l.publish({modules:c,dependencies:a});l.transferObjects([i],e.getAddress());let d=null,p=0,h=0,m=Date.now(),b=!1,k=()=>{b=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
34
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",k);try{for(;p<_&&!d&&!b;)try{d=await e.signAndSendTxn({tx:l})}catch{if(b)break;p++,p===_&&(console.log(f.red(` \u2514\u2500 Publication failed after ${_} attempts`)),console.log(f.red(" \u2514\u2500 Please check your network connection and try again later.")),process.exit(1));let te=Math.floor((Date.now()-m)/1e3),Je=D[h%D.length];h++,process.stdout.write(`\r \u251C\u2500 ${Je} Retrying... (${te}s)`),await new Promise(Xe=>setTimeout(Xe,z))}}finally{process.removeListener("SIGINT",k)}b&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),(!d||d.effects?.status.status==="failure")&&(console.log(f.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let w=1,P="",j="",F=t.schemas,I="",x=[];d.objectChanges.map(u=>{u.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${u.packageId}`),P=u.packageId||""),u.type==="created"&&u.objectType&&u.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${u.objectId}`),I=u.objectId||""),u.type==="created"&&x.push(u)}),console.log(` \u2514\u2500 Transaction: ${d.digest}`),ge(`${n}/Move.lock`,o,"publish",s,P),console.log(`
|
|
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(`
|
|
59
37
|
\u2705 Contract Publication Complete
|
|
60
|
-
`)):(console.log(
|
|
61
|
-
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(
|
|
62
|
-
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let r=await
|
|
63
|
-
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",
|
|
38
|
+
`)):(console.log(f.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(f.yellow(" Please republish or manually call deploy_hook::run")),console.log(f.yellow(" Please check the transaction digest:")),console.log(f.yellow(` ${g.digest}`)),process.exit(1))}async function gt(e){return T.existsSync(e)?!0:(console.log(f.yellow(`
|
|
39
|
+
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(f.yellow(" \u251C\u2500 Expected Path:"),e),console.log(f.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(f.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe-framework")),console.log(f.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe-framework contracts/dubhe-framework")),console.log(f.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe-framework")),console.log(f.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function ft(e,t){let n=`${process.cwd()}/contracts/dubhe-framework`;if(!await gt(n))return;console.log(`
|
|
40
|
+
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let r=await he(e);await me(`${n}/Move.lock`,t);let[s,c]=fe(n),a=new Z,[l]=a.publish({modules:s,dependencies:c});a.transferObjects([l],e.getAddress());let i=null,d=0,p=0,h=Date.now(),m=!1,b=()=>{m=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
41
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",b);try{for(;d<_&&!i&&!m;)try{i=await e.signAndSendTxn({tx:a})}catch{if(m)break;d++,d===_&&(console.log(f.red(` \u2514\u2500 Publication failed after ${_} attempts`)),console.log(f.red(" \u2514\u2500 Please check your network connection and try again later.")),process.exit(1));let S=Math.floor((Date.now()-h)/1e3),g=D[p%D.length];p++,process.stdout.write(`\r \u251C\u2500 ${g} Retrying... (${S}s)`),await new Promise(u=>setTimeout(u,z))}}finally{process.removeListener("SIGINT",b)}m&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),(!i||i.effects?.status.status==="failure")&&(console.log(f.red(" \u2514\u2500 Publication failed")),process.exit(1));let k=1,w="",P="",j={},F="";i.objectChanges.map(y=>{y.type==="published"&&(w=y.packageId||""),y.type==="created"&&y.objectType&&y.objectType==="0x2::package::UpgradeCap"&&(F=y.objectId||"")}),await O(3e3);let I=new Z;I.moveCall({target:`${w}::dubhe_genesis::run`,arguments:[I.object("0x6")]});let x;try{x=await e.signAndSendTxn({tx:I})}catch(y){console.error(f.red(" \u2514\u2500 Deploy hook execution failed")),console.error(y.message),process.exit(1)}x.effects?.status.status==="success"&&x.objectChanges?.map(y=>{y.type==="created"&&y.objectType&&y.objectType.includes("dubhe_schema::Schema")&&(P=y.objectId||"")}),L("dubhe-framework",t,w,P,F,k,j),ge(`${n}/Move.lock`,t,"publish",r,w),await O(1e3)}async function ye(e,t,o){await A(t);let n=C({network:t});t==="localnet"&&await ft(n,t);let s=`${process.cwd()}/contracts/${e.name}`;await X(`${s}/Move.toml`,t),await mt(n,e,t,s,o)}import{loadMetadata as ht}from"@0xobelisk/sui-client";import*as be from"fs";import*as we from"path";function yt(e,t){switch(e.split("<")[0].trim()){case"StorageValue":return t.length===0;case"StorageMap":return t.length===1;case"StorageDoubleMap":return t.length===2;default:return!1}}function bt(e){switch(e.split("<")[0].trim()){case"StorageValue":return 0;case"StorageMap":return 1;case"StorageDoubleMap":return 2;default:return 0}}async function ve({dubheConfig:e,schema:t,params:o,network:n,objectId:r,packageId:s,metadataFilePath:c}){let l=`${process.cwd()}/contracts/${e.name}`;s=s||await R(l,n),r=r||await K(l,n);let i;if(c?i=await ie(c):i=await ht(n,s),!i)throw new v("Metadata file not found. Please provide a metadata file path or set the packageId.");if(!e.schemas[t])throw new v(`Schema "${t}" not found in dubhe config. Available schemas: ${Object.keys(e.schemas).join(", ")}`);let d=e.schemas[t],p=o||[];if(!yt(d,p))throw new Error(`Invalid params count for ${d}. Expected: ${bt(d)}, Got: ${p.length}`);let m=await C({network:n,packageId:s,metadata:i}).parseState({schema:t,objectId:r,storageType:d,params:p});console.log(m)}async function ie(e){if(we.extname(e)!==".json")throw new Error("Metadata file must be in JSON format");try{let t=be.readFileSync(e,"utf8"),o=JSON.parse(t);if(!o||typeof o!="object")throw new Error("Invalid JSON format");return{...o}}catch(t){throw t instanceof Error?new Error(`Failed to read metadata file: ${t.message}`):t}}import{loadMetadata as wt,Transaction as vt}from"@0xobelisk/sui-client";var xt=["u8","u16","u32","u64","u128","u256","bool","id","string","address","object"];function _t(e){try{e.forEach(t=>{let[o,n]=t.split(":");if(!xt.includes(o))throw new Error(`Invalid param type: ${o}`)})}catch(t){throw new Error(`Invalid params: ${t}`)}}function kt(e,t){let[o,n]=t.split(":");switch(o){case"u8":return e.pure.u8(parseInt(n));case"u16":return e.pure.u16(parseInt(n));case"u32":return e.pure.u32(parseInt(n));case"u64":return e.pure.u64(parseInt(n));case"u128":return e.pure.u128(parseInt(n));case"u256":return e.pure.u256(parseInt(n));case"object":return e.object(n);case"address":return e.pure.address(n);case"bool":return e.pure.bool(n==="true");case"string":return e.pure.string(n);default:throw new Error(`Invalid param type: ${o}`)}}function It(e,t){return t.map(o=>kt(e,o))}async function xe({dubheConfig:e,moduleName:t,funcName:o,params:n,network:r,packageId:s,metadataFilePath:c}){let l=`${process.cwd()}/contracts/${e.name}`;s=s||await R(l,r);let i;if(c?i=await ie(c):i=await wt(r,s),!i)throw new v("Metadata file not found. Please provide a metadata file path or set the packageId.");let d=n||[];_t(d);let p=C({network:r,packageId:s,metadata:i}),h=new vt,m=It(h,d),b=await p.tx[t][o]({tx:h,params:m});console.log(JSON.stringify(b,null,2))}import{Dubhe as St}from"@0xobelisk/sui-client";function $t(){try{let e=process.platform==="win32"?'tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH':'pgrep -f "sui start"',t=Ct(e).toString().trim();return process.platform==="win32"?t.toLowerCase().includes("sui.exe"):t.length>0}catch{return!1}}async function Et(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let r=new St({secretKey:t}).getSigner();_e("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${r.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${r.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log($.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log($.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Dt(e){let t=()=>{console.log($.yellow(`
|
|
42
|
+
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function ke(){if($t()){console.log($.yellow(`
|
|
43
|
+
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log($.yellow(" \u251C\u2500 Cannot start a new instance")),console.log($.yellow(" \u2514\u2500 Please stop the existing process first"));return}H(),console.log("\u{1F680} Starting Local Node...");let e=null;try{if(e=_e("sui",["start","--with-faucet","--force-regenesis"],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),e.on("error",o=>{console.error($.red(`
|
|
44
|
+
\u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${o.message}`))}),await O(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await Et(),await O(2e3),ae("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new v("Please check your privateKey.");console.log($.green("\u{1F389} Local environment is ready!")),Dt(e),await new Promise(o=>{e?.on("exit",()=>o())})}catch(t){console.error($.red(`
|
|
45
|
+
\u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${t.message}`)),e&&e.kill("SIGINT"),process.exit(1)}}var Pt={command:"node",describe:"Manage local Sui node",builder(e){return e},async handler(){try{await ke()}catch(e){console.error("Error executing command:",e),process.exit(1)}}},Ie=Pt;import{requestSuiFromFaucetV0 as Tt,getFaucetHost as Mt}from"@mysten/sui/faucet";import{SuiClient as Ot,getFullnodeUrl as Nt}from"@mysten/sui/client";var ce=60,jt=1e3,Ce=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ft={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=C(e).getAddress():o=t,console.log(`
|
|
64
46
|
\u{1F30A} Starting Faucet Operation...`),console.log(` \u251C\u2500 Network: ${e}`),t===void 0?(console.log(" \u251C\u2500 Using Environment PrivateKey"),console.log(` \u251C\u2500 Generated Address: ${o}`)):console.log(` \u251C\u2500 Using Provided Address: ${o}`),console.log(" \u251C\u2500 Requesting funds from faucet...");let n=0,r=!1,s=0,c=Date.now(),a=!1,l=()=>{a=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
65
|
-
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",l);try{for(;n<ce&&!r&&!a;)try{await
|
|
66
|
-
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(
|
|
47
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",l);try{for(;n<ce&&!r&&!a;)try{await Tt({host:Mt(e),recipient:o}),r=!0}catch{if(a)break;n++,n===ce&&(console.log(` \u2514\u2500 Failed to request funds after ${ce} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let m=Math.floor((Date.now()-c)/1e3),b=Ce[s%Ce.length];s++,process.stdout.write(`\r \u251C\u2500 ${b} Retrying... (${m}s)`),await new Promise(k=>setTimeout(k,jt))}}finally{process.removeListener("SIGINT",l)}a&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let i=new Ot({url:Nt(e)}),d={owner:o},p=await i.getBalance(d);console.log(`
|
|
48
|
+
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(p.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
|
|
67
49
|
\u2705 Faucet Operation Complete
|
|
68
|
-
`),process.exit(0)}},
|
|
50
|
+
`),process.exit(0)}},Se=Ft;import{schemaGen as Rt,loadConfig as At}from"@0xobelisk/sui-common";import Ut from"chalk";var Vt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{let o=await At(e);await Rt(o,void 0,t),process.exit(0)}catch(o){console.log(Ut.red("Schemagen failed!")),console.error(o.message)}}},$e=Vt;import{loadConfig as qt}from"@0xobelisk/sui-common";var Kt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await qt(t);await ye(n,e,o)}catch(n){E(n),process.exit(1)}process.exit(0)}},Ee=Kt;import{Transaction as De,UpgradePolicy as Lt}from"@0xobelisk/sui-client";import{execSync as zt}from"child_process";import N from"chalk";import*as U from"fs";import*as Pe from"path";function Bt(e,t){let o=`${e}/sources/codegen/core/schema.move`,n=U.readFileSync(o,"utf-8"),r=new RegExp("public fun migrate\\(_schema: &mut Schema, _ctx: &mut TxContext\\) {[^}]*}"),s=`
|
|
69
51
|
public fun migrate(_schema: &mut Schema, _ctx: &mut TxContext) {
|
|
70
52
|
${t.map(a=>{let l="";return a.fields.includes("StorageValue")?l=`storage_value::new(b"${a.schemaName}", _ctx)`:a.fields.includes("StorageMap")?l=`storage_map::new(b"${a.schemaName}", _ctx)`:a.fields.includes("StorageDoubleMap")&&(l=`storage_double_map::new(b"${a.schemaName}", _ctx)`),`storage::add_field<${a.fields}>(&mut _schema.id, b"${a.schemaName}", ${l});`}).join("")}
|
|
71
53
|
}
|
|
72
|
-
`,c=n.replace(r,s);
|
|
73
|
-
`),a=c.findIndex(
|
|
74
|
-
`);
|
|
75
|
-
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",a),console.log("\u{1F4CB} UpgradeCap Object Id:",l),console.log("\u{1F4CB} OldVersion:",c);let
|
|
76
|
-
\u{1F680} Starting Migration Process...`),
|
|
54
|
+
`,c=n.replace(r,s);U.writeFileSync(o,c,"utf-8")}function Q(e,t,o,n){let r=Pe.resolve(e),c=U.readFileSync(r,"utf-8").split(`
|
|
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.
|
|
77
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(`
|
|
78
|
-
`),l=!1;for(let
|
|
79
|
-
`),G.writeFileSync(`${o}/.env`,r);break}}let
|
|
80
|
-
`+l:r=l,G.writeFileSync(`${o}/.env`,r),console.log(
|
|
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';
|
|
81
63
|
|
|
82
64
|
export const NETWORK: NetworkType = '${e}';
|
|
83
65
|
export const PACKAGE_ID = '${t}';
|
|
84
66
|
export const SCHEMA_ID = '${o}';
|
|
85
67
|
export const DUBHE_SCHEMA_ID = '${r}';
|
|
86
|
-
`;
|
|
87
|
-
Watch stopped.`),process.exit()})}},
|
|
68
|
+
`;po(s,n,"storeConfig")}async function po(e,t,o){ao(co(t),{recursive:!0}),io(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function qe(e,t,o){let r=`${process.cwd()}/contracts/${e.name}`,s=await M(r,t);await lo(s.network,s.packageId,s.schemaId,o)}import{loadConfig as uo}from"@0xobelisk/sui-common";var mo={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await uo(e);await qe(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Ke=mo;import{loadConfig as go}from"@0xobelisk/sui-common";var fo={command:"query",describe:"Query dubhe schema struct state",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},schema:{type:"string",desc:"Schema name",demandOption:!0},"object-id":{type:"string",desc:"Object ID (optional)"},"package-id":{type:"string",desc:"Package ID (optional)"},"metadata-path":{type:"string",desc:"Path to metadata JSON file (optional)"},params:{type:"array",desc:"Params for storage type: StorageValue(no params), StorageMap(1 param), StorageDoubleMap(2 params)",string:!0}},async handler({network:e,"config-path":t,schema:o,"object-id":n,"package-id":r,"metadata-path":s,params:c}){try{let a=await go(t);await ve({dubheConfig:a,schema:o,objectId:n,network:e,packageId:r,metadataFilePath:s,params:c})}catch(a){E(a),process.exit(1)}process.exit(0)}},Le=fo;import{loadConfig as ho}from"@0xobelisk/sui-common";var yo={command:"call",describe:"Call a function in a module",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)",default:"localnet"},module:{type:"string",desc:"Module name",demandOption:!0},function:{type:"string",desc:"Function name",demandOption:!0},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"package-id":{type:"string",desc:"Package ID (optional)"},"metadata-path":{type:"string",desc:"Path to metadata JSON file (optional)"},params:{type:"array",desc:"Params for the function",string:!0}},async handler({network:e,"config-path":t,module:o,function:n,"package-id":r,"metadata-path":s,params:c}){try{let a=await ho(t);await xe({dubheConfig:a,moduleName:o,funcName:n,network:e,packageId:r,metadataFilePath:s,params:c})}catch(a){E(a),process.exit(1)}process.exit(0)}},ze=yo;import bo from"chokidar";import{exec as wo}from"child_process";var vo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{wo("pnpm dubhe schemagen",(n,r,s)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(s){console.error(`schemagen stderr: ${s}`);return}console.log(`schemagen stdout: ${r}`)})},o=bo.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(`
|
|
69
|
+
Watch stopped.`),process.exit()})}},Be=vo;import xo from"wait-on";import _o from"ora";import ee from"chalk";var ko={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=_o({text:`Waiting for service to start ${ee.cyan(t.url)}...`,color:"cyan"});o.start();try{await xo({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(ee.green("Service is ready!")),process.exit(0)}catch{o.fail(ee.red("Timeout waiting for service")),console.error(ee.yellow("Please make sure the service is running...")),process.exit(1)}}},Ge=ko;var He=[Ie,Ee,ze,Le,Se,$e,Me,Oe,Ne,je,Ae,Ve,Ke,Be,Ge];import*as Ye from"dotenv";import We from"chalk";Ye.config();Io(Co(process.argv)).scriptName("dubhe").command(He).strict().fail((e,t)=>{console.error(We.red(e)),e.includes("Missing required argument")&&console.log(We.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),E(t),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
|
|
88
70
|
//# sourceMappingURL=dubhe.js.map
|