@0xobelisk/sui-cli 1.2.0-pre.2 → 1.2.0-pre.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dubhe.js +46 -63
- package/dist/dubhe.js.map +1 -1
- package/package.json +3 -3
- package/src/commands/build.ts +1 -1
- package/src/commands/index.ts +3 -1
- package/src/commands/localnode.ts +2 -8
- package/src/commands/switchEnv.ts +24 -0
- package/src/commands/test.ts +1 -1
- package/src/utils/callHandler.ts +1 -1
- package/src/utils/publishHandler.ts +18 -9
- package/src/utils/queryStorage.ts +1 -1
- package/src/utils/startNode.ts +55 -97
- package/src/utils/storeConfig.ts +1 -1
- package/src/utils/upgradeHandler.ts +4 -3
- package/src/utils/utils.ts +131 -15
package/dist/dubhe.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Eo from"yargs";import{hideBin as Po}from"yargs/helpers";import{execSync as Et,spawn as Ce}from"child_process";import $ from"chalk";import et from"chalk";function H(){console.log(et.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,79 +10,62 @@ 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 Q}from"@0xobelisk/sui-client";import{execSync as ft}from"child_process";import f from"chalk";import*as se from"fs/promises";import{mkdirSync as st,writeFileSync as at}from"fs";import{dirname as it}from"path";import{SUI_PRIVATE_KEY_PREFIX as ct}from"@mysten/sui/cryptography";import K from"chalk";import{ZodError as tt}from"zod";import{fromZodError as ot,ValidationError as nt}from"zod-validation-error";var ne=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 nt)console.log(K.redBright(e.message));else if(e instanceof tt){let t=ot(e,{prefixSeparator:`
|
|
36
14
|
- `,issueSeparator:`
|
|
37
|
-
- `});console.log(
|
|
38
|
-
\u274C Failed to
|
|
39
|
-
\u274C
|
|
40
|
-
\u274C Failed to
|
|
15
|
+
- `});console.log(K.redBright(t.message))}else e instanceof ne?(console.log(K.red(e.message)),console.log(""),console.log(K.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof v?console.log(K.red(e)):console.log(e)}import*as J from"fs";import T from"chalk";import{spawn as le}from"child_process";import{Dubhe as lt}from"@0xobelisk/sui-client";var re={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.20",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(ct))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 N(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 Y(e,t){try{let o=await se.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).schemaId}catch{return""}}async function U(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await Y(o,"mainnet");case"testnet":return await Y(o,"testnet");case"devnet":return await Y(o,"devnet");case"localnet":return await Y(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function de(e,t){return(await N(e,t)).schemas}async function pe(e,t){return(await N(e,t)).version}async function V(e,t){return(await N(e,t)).packageId}async function X(e,t){return(await N(e,t)).schemaId}async function ue(e,t){return(await N(e,t)).upgradeCap}function L(e,t,o,n,r,s,a){let i={projectName:e,network:t,packageId:o,schemaId:n,schemas:a,upgradeCap:r,version:s},l=process.cwd(),c=JSON.stringify(i,null,2);dt(c,`${l}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function dt(e,t,o){st(it(t),{recursive:!0}),at(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function pt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${re.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${re.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function Z(e,t){let o=J.readFileSync(e,"utf-8"),n=pt(t),r=o.replace(/Dubhe = \{.*\}/,n);J.writeFileSync(e,r,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function ut(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 mt(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 ut(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((r,s)=>{let a="",i="",l=le("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});l.stdout.on("data",c=>{i+=c.toString()}),l.stderr.on("data",c=>{a+=c.toString()}),l.on("error",c=>{console.error(T.red(`
|
|
16
|
+
\u274C Failed to execute sui command: ${c.message}`)),s(new Error(`Failed to execute sui command: ${c.message}`))}),l.on("exit",c=>{if(a.includes("already exists")||i.includes("already exists")){console.log(T.yellow(`Environment ${e} already exists, proceeding...`)),r();return}if(c===0)console.log(T.green(`Successfully added environment ${e}`)),r();else{let d=a||i||`Process exited with code ${c}`;console.error(T.red(`
|
|
17
|
+
\u274C Failed to add environment ${e}`)),console.error(T.red(` \u2514\u2500 ${d.trim()}`)),s(new Error(d))}})})}async function O(e){try{return await mt(e),new Promise((t,o)=>{let n="",r="",s=le("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});s.stdout.on("data",a=>{r+=a.toString()}),s.stderr.on("data",a=>{n+=a.toString()}),s.on("error",a=>{console.error(T.red(`
|
|
18
|
+
\u274C Failed to execute sui command: ${a.message}`)),o(new Error(`Failed to execute sui command: ${a.message}`))}),s.on("exit",a=>{if(a===0)console.log(T.green(`Successfully switched to environment ${e}`)),t();else{let i=n||r||`Process exited with code ${a}`;console.error(T.red(`
|
|
19
|
+
\u274C Failed to switch to environment ${e}`)),console.error(T.red(` \u2514\u2500 ${i.trim()}`)),o(new Error(i))}})})}catch(t){throw t}}var j=e=>new Promise(t=>setTimeout(t,e));function gt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new v(`Missing private key environment variable.
|
|
41
20
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
42
21
|
or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
43
|
-
in your contracts directory to use the default sui private key.`);let t=
|
|
44
|
-
`),l=
|
|
22
|
+
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 k({network:e,packageId:t,metadata:o}){let n=gt();return new lt({networkType:e,secretKey:n,packageId:t,metadata:o})}import*as M from"fs";import*as me from"path";var _=60,z=1e3,P=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];async function ge(e,t){if(!M.existsSync(e))return;let o=M.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),r=o.replace(n,"");M.writeFileSync(e,r,"utf-8")}function fe(e,t,o,n,r){let s=me.resolve(e),a=M.readFileSync(s,"utf-8"),i=a.split(`
|
|
23
|
+
`),l=i.findIndex(h=>h.trim()===`[env.${t}]`),c={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(l===-1)if(o==="publish")c.originalPublishedId=r,c.latestPublishedId=r,c.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<i.length;h++){let m=i[h].trim();if(m.startsWith("["))break;let[b,C]=m.split("=").map(w=>w.trim().replace(/"/g,""));switch(b){case"original-published-id":c.originalPublishedId=C;break;case"latest-published-id":c.latestPublishedId=C;break;case"published-version":c.publishedVersion=parseInt(C,10);break}}o==="publish"?(c.originalPublishedId=r,c.latestPublishedId=r,c.publishedVersion=1):o==="upgrade"&&(c.latestPublishedId=r,c.publishedVersion+=1)}let d=`
|
|
45
24
|
[env.${t}]
|
|
46
|
-
chain-id = "${
|
|
47
|
-
original-published-id = "${
|
|
48
|
-
latest-published-id = "${
|
|
49
|
-
published-version = "${
|
|
50
|
-
`,
|
|
51
|
-
`)+
|
|
52
|
-
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",
|
|
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[
|
|
55
|
-
\u{1F504} Publishing Contract...`);let l=new Q;r&&l.setGasBudget(r);let[
|
|
56
|
-
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",
|
|
57
|
-
\u26A1 Executing Deploy Hook...`),await
|
|
58
|
-
\u{1F4CB} Created
|
|
25
|
+
chain-id = "${c.chainId}"
|
|
26
|
+
original-published-id = "${c.originalPublishedId}"
|
|
27
|
+
latest-published-id = "${c.latestPublishedId}"
|
|
28
|
+
published-version = "${c.publishedVersion}"
|
|
29
|
+
`,p=l===-1?a+d:i.slice(0,l).join(`
|
|
30
|
+
`)+d;M.writeFileSync(s,p,"utf-8")}function he(e){let t,o;try{let n=JSON.parse(ft(`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 ye(e){let t=0,o=0,n=Date.now(),r=!1,s="",a=!1,i=()=>{r=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
31
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",i);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),c=P[o%P.length];o++,process.stdout.write(`\r \u251C\u2500 ${c} 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(),c=await e.suiInteractor.currentClient.getCoins({owner:l,coinType:"0x2::sui::SUI"});if(c.data.length>0){let h=c.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;a||(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")),a=!0)}else a||(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")),a=!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=P[o%P.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 c=Math.floor((Date.now()-n)/1e3),d=P[o%P.length];o++,process.stdout.write(`\r \u251C\u2500 ${d} Checking deployer balance... (${c}s)`),await new Promise(p=>setTimeout(p,z))}}finally{process.removeListener("SIGINT",i)}throw r&&process.exit(0),new Error("Failed to connect to node")}async function ht(e,t,o,n,r){console.log(`
|
|
32
|
+
\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 ye(e);console.log(" \u251C\u2500 Validating Environment..."),await ge(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
|
|
33
|
+
\u{1F4E6} Building Contract...`);let[a,i]=he(n);console.log(`
|
|
34
|
+
\u{1F504} Publishing Contract...`);let l=new Q;r&&l.setGasBudget(r);let[c]=l.publish({modules:a,dependencies:i});l.transferObjects([c],e.getAddress());let d=null,p=0,h=0,m=Date.now(),b=!1,C=()=>{b=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
35
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",C);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 oe=Math.floor((Date.now()-m)/1e3),Ze=P[h%P.length];h++,process.stdout.write(`\r \u251C\u2500 ${Ze} Retrying... (${oe}s)`),await new Promise(Qe=>setTimeout(Qe,z))}}finally{process.removeListener("SIGINT",C)}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,D="",R="",A=t.schemas,I="",x=[];d.objectChanges.map(u=>{u.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${u.packageId}`),D=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}`),fe(`${n}/Move.lock`,o,"publish",s,D),console.log(`
|
|
36
|
+
\u26A1 Executing Deploy Hook...`),await j(5e3);let y=new Q,S=[];if(t.name!=="dubhe"){let u=await U(o);S.push(y.object(u))}S.push(y.object("0x6")),y.moveCall({target:`${D}::${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(`
|
|
37
|
+
\u{1F4CB} Created Objects:`),g.objectChanges?.map(u=>{u.type==="created"&&u.objectType&&u.objectType.includes("schema::Schema")&&(R=u.objectId||""),u.type==="created"&&u.objectType&&u.objectType.includes("schema")&&!u.objectType.includes("dynamic_field")&&x.push(u)}),x.map(u=>{console.log(` \u251C\u2500 Type: ${u.objectType}`),console.log(` \u2514\u2500 ID: ${u.objectId}`)}),L(t.name,o,D,R,I,w,A),console.log(`
|
|
59
38
|
\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",
|
|
64
|
-
\u{
|
|
65
|
-
|
|
66
|
-
\
|
|
39
|
+
`)):(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 yt(e){return M.existsSync(e)?!0:(console.log(f.yellow(`
|
|
40
|
+
\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")),console.log(f.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(f.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(f.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function bt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await yt(n))return;console.log(`
|
|
41
|
+
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let r=await ye(e);await ge(`${n}/Move.lock`,t);let[s,a]=he(n),i=new Q,[l]=i.publish({modules:s,dependencies:a});i.transferObjects([l],e.getAddress());let c=null,d=0,p=0,h=Date.now(),m=!1,b=()=>{m=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
42
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",b);try{for(;d<_&&!c&&!m;)try{c=await e.signAndSendTxn({tx:i})}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=P[p%P.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"),(!c||c.effects?.status.status==="failure")&&(console.log(f.red(" \u2514\u2500 Publication failed")),process.exit(1));let C=1,w="",D="",R={},A="";c.objectChanges.map(y=>{y.type==="published"&&(w=y.packageId||""),y.type==="created"&&y.objectType&&y.objectType==="0x2::package::UpgradeCap"&&(A=y.objectId||"")}),await j(3e3);let I=new Q;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")&&(D=y.objectId||"")}),L("dubhe",t,w,D,A,C,R),fe(`${n}/Move.lock`,t,"publish",r,w),await j(1e3)}async function be(e,t,o){await O(t);let n=k({network:t});t==="localnet"&&await bt(n,t);let s=`${process.cwd()}/src/${e.name}`;await Z(`${s}/Move.toml`,t),await ht(n,e,t,s,o)}import{loadMetadata as wt}from"@0xobelisk/sui-client";import*as we from"fs";import*as ve from"path";function vt(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 xt(e){switch(e.split("<")[0].trim()){case"StorageValue":return 0;case"StorageMap":return 1;case"StorageDoubleMap":return 2;default:return 0}}async function xe({dubheConfig:e,schema:t,params:o,network:n,objectId:r,packageId:s,metadataFilePath:a}){let l=`${process.cwd()}/src/${e.name}`;s=s||await V(l,n),r=r||await X(l,n);let c;if(a?c=await ie(a):c=await wt(n,s),!c)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(!vt(d,p))throw new Error(`Invalid params count for ${d}. Expected: ${xt(d)}, Got: ${p.length}`);let m=await k({network:n,packageId:s,metadata:c}).parseState({schema:t,objectId:r,storageType:d,params:p});console.log(m)}async function ie(e){if(ve.extname(e)!==".json")throw new Error("Metadata file must be in JSON format");try{let t=we.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 _t,Transaction as Ct}from"@0xobelisk/sui-client";var It=["u8","u16","u32","u64","u128","u256","bool","id","string","address","object"];function kt(e){try{e.forEach(t=>{let[o,n]=t.split(":");if(!It.includes(o))throw new Error(`Invalid param type: ${o}`)})}catch(t){throw new Error(`Invalid params: ${t}`)}}function St(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 $t(e,t){return t.map(o=>St(e,o))}async function _e({dubheConfig:e,moduleName:t,funcName:o,params:n,network:r,packageId:s,metadataFilePath:a}){let l=`${process.cwd()}/src/${e.name}`;s=s||await V(l,r);let c;if(a?c=await ie(a):c=await _t(r,s),!c)throw new v("Metadata file not found. Please provide a metadata file path or set the packageId.");let d=n||[];kt(d);let p=k({network:r,packageId:s,metadata:c}),h=new Ct,m=$t(h,d),b=await p.tx[t][o]({tx:h,params:m});console.log(JSON.stringify(b,null,2))}import{Dubhe as Pt}from"@0xobelisk/sui-client";function Dt(){try{let e=process.platform==="win32"?'tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH':'pgrep -f "sui start"',t=Et(e).toString().trim();return process.platform==="win32"?t.toLowerCase().includes("sui.exe"):t.length>0}catch{return!1}}async function Tt(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let r=new Pt({secretKey:t}).getSigner();Ce("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 Mt(e){let t=()=>{console.log($.yellow(`
|
|
43
|
+
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Ie(){if(Dt()){console.log($.yellow(`
|
|
44
|
+
\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=Ce("sui",["start","--with-faucet","--force-regenesis"],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),e.on("error",o=>{console.error($.red(`
|
|
45
|
+
\u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${o.message}`))}),await j(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await Tt(),await j(2e3),ae("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new v("Please check your privateKey.");console.log($.green("\u{1F389} Local environment is ready!")),Mt(e),await new Promise(o=>{e?.on("exit",()=>o())})}catch(t){console.error($.red(`
|
|
46
|
+
\u274C Failed to Start Local Node`)),console.error($.red(` \u2514\u2500 Error: ${t.message}`)),e&&e.kill("SIGINT"),process.exit(1)}}var Ot={command:"node",describe:"Manage local Sui node",builder(e){return e},async handler(){try{await Ie()}catch(e){console.error("Error executing command:",e),process.exit(1)}}},ke=Ot;import{requestSuiFromFaucetV0 as Nt,getFaucetHost as jt}from"@mysten/sui/faucet";import{SuiClient as Ft,getFullnodeUrl as Rt}from"@mysten/sui/client";var ce=60,At=1e3,Se=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ut={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=k(e).getAddress():o=t,console.log(`
|
|
47
|
+
\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,a=Date.now(),i=!1,l=()=>{i=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
48
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",l);try{for(;n<ce&&!r&&!i;)try{await Nt({host:jt(e),recipient:o}),r=!0}catch{if(i)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()-a)/1e3),b=Se[s%Se.length];s++,process.stdout.write(`\r \u251C\u2500 ${b} Retrying... (${m}s)`),await new Promise(C=>setTimeout(C,At))}}finally{process.removeListener("SIGINT",l)}i&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let c=new Ft({url:Rt(e)}),d={owner:o},p=await c.getBalance(d);console.log(`
|
|
49
|
+
\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
50
|
\u2705 Faucet Operation Complete
|
|
68
|
-
`),process.exit(0)}}
|
|
51
|
+
`),process.exit(0)}},$e=Ut;import{schemaGen as Vt,loadConfig as qt}from"@0xobelisk/sui-common";import Kt from"chalk";var Lt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{let o=await qt(e);await Vt(o,void 0,t),process.exit(0)}catch(o){console.log(Kt.red("Schemagen failed!")),console.error(o.message)}}},Ee=Lt;import{loadConfig as zt}from"@0xobelisk/sui-common";var Bt={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 zt(t);await be(n,e,o)}catch(n){E(n),process.exit(1)}process.exit(0)}},Pe=Bt;import{Transaction as De,UpgradePolicy as Gt}from"@0xobelisk/sui-client";import{execSync as Ht}from"child_process";import F from"chalk";import*as q from"fs";import*as Te from"path";function Wt(e,t){let o=`${e}/sources/codegen/core/schema.move`,n=q.readFileSync(o,"utf-8"),r=new RegExp("public fun migrate\\(_schema: &mut Schema, _ctx: &mut TxContext\\) {[^}]*}"),s=`
|
|
69
52
|
public fun migrate(_schema: &mut Schema, _ctx: &mut TxContext) {
|
|
70
|
-
${t.map(
|
|
53
|
+
${t.map(i=>{let l="";return i.fields.includes("StorageValue")?l=`storage_value::new(b"${i.schemaName}", _ctx)`:i.fields.includes("StorageMap")?l=`storage_map::new(b"${i.schemaName}", _ctx)`:i.fields.includes("StorageDoubleMap")&&(l=`storage_double_map::new(b"${i.schemaName}", _ctx)`),`storage::add_field<${i.fields}>(&mut _schema.id, b"${i.schemaName}", ${l});`}).join("")}
|
|
71
54
|
}
|
|
72
|
-
`,
|
|
73
|
-
`),a
|
|
74
|
-
`);
|
|
75
|
-
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",
|
|
76
|
-
\u{1F680} Starting Migration Process...`),
|
|
77
|
-
`)));let o=process.cwd(),n,r="";try{r=G.readFileSync(`${o}/.env`,"utf8");let s=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(s=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),s){let
|
|
78
|
-
`),l=!1;for(let
|
|
79
|
-
`),G.writeFileSync(`${o}/.env`,r);break}}let
|
|
80
|
-
`+l:r=l,G.writeFileSync(`${o}/.env`,r),console.log(
|
|
55
|
+
`,a=n.replace(r,s);q.writeFileSync(o,a,"utf-8")}function ee(e,t,o,n){let r=Te.resolve(e),a=q.readFileSync(r,"utf-8").split(`
|
|
56
|
+
`),i=a.findIndex(d=>d.trim()===`[env.${t}]`);if(i===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let l=-1,c="";for(let d=i+1;d<a.length;d++){let p=a[d].trim();if(p.startsWith("["))break;if(p.startsWith(o)){l=d,c=p.split("=")[1].trim().replace(/"/g,"");break}}if(l!==-1){a[l]=`${o} = "${n}"`;let d=a.join(`
|
|
57
|
+
`);q.writeFileSync(r,d,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return c}async function Me(e,t,o){await O(o);let n=process.cwd(),r=`${n}/src/${t}`,s=k({network:o}),a=Number(await pe(r,o)),i=await V(r,o),l=await ue(r,o),c=await X(r,o),d=ee(`${r}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),p=[],h=await de(r,o);Object.entries(e.schemas).forEach(([m,b])=>{h.hasOwnProperty(m)||p.push({schemaName:m,fields:b})}),Wt(r,p);try{let m,b,C;try{let{modules:g,dependencies:u,digest:oe}=JSON.parse(Ht(`sui move build --dump-bytecode-as-base64 --path ${n}/src/${t}`,{encoding:"utf-8"}));m=g,b=u,C=oe}catch(g){throw new W(g.stdout)}console.log(`
|
|
58
|
+
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",i),console.log("\u{1F4CB} UpgradeCap Object Id:",l),console.log("\u{1F4CB} OldVersion:",a);let w=new De,D=w.moveCall({target:"0x2::package::authorize_upgrade",arguments:[w.object(l),w.pure.u8(Gt.COMPATIBLE),w.pure.vector("u8",C)]}),R=w.upgrade({modules:m,dependencies:b,package:i,ticket:D});w.moveCall({target:"0x2::package::commit_upgrade",arguments:[w.object(l),R]});let A=await s.signAndSendTxn({tx:w,onSuccess:g=>{console.log(F.green(`Upgrade Transaction Digest: ${g.digest}`))},onError:g=>{console.log(F.red("Upgrade Transaction failed!")),console.error(g)}}),I="";A.objectChanges.map(g=>{g.type==="published"&&(console.log(F.blue(`${t} new PackageId: ${g.packageId}`)),console.log(F.blue(`${t} new Version: ${a+1}`)),I=g.packageId)}),ee(`${r}/Move.lock`,o,"original-published-id",d),ee(`${r}/Move.lock`,o,"latest-published-id",I),ee(`${r}/Move.lock`,o,"published-version",a+1+""),L(t,o,I,c,l,a+1,e.schemas),console.log(`
|
|
59
|
+
\u{1F680} Starting Migration Process...`),p.forEach(g=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(g,null,2))}),await new Promise(g=>setTimeout(g,5e3));let x=new De,y=a+1,S=[];if(t!=="dubhe"){let g=await U(o);S.push(x.object(g))}S.push(x.object(c)),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(F.green(`Migration Transaction Digest: ${g.digest}`))},onError:g=>{console.log(F.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(g)}})}catch(m){console.log(F.red("upgrade handler execution failed!")),console.error(m.message)}}import{loadConfig as Yt}from"@0xobelisk/sui-common";var Jt={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 Yt(t);await Me(o,o.name,e)}catch(o){E(o),process.exit(1)}process.exit(0)}},Oe=Jt;import{execSync as Xt}from"child_process";import{loadConfig as Zt}from"@0xobelisk/sui-common";var Qt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Zt(e),a=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Xt(a,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Ne=Qt;import{execSync as eo}from"child_process";import to from"chalk";import{loadConfig as oo}from"@0xobelisk/sui-common";var no={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 oo(e),s=`${process.cwd()}/src/${n.name}`;await O(t),await Z(s+"/Move.toml",t);let a=`sui move build --path ${s} ${o?" --dump-bytecode-as-base64":""}`,i=eo(a,{encoding:"utf-8"});console.log(i)}catch(n){console.error(to.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},je=no;var ro={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){H()}},Fe=ro;import{Dubhe as Re}from"@0xobelisk/sui-client";import*as G from"fs";import B from"chalk";async function Ae(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.
|
|
60
|
+
`)));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 a=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",i=r.split(`
|
|
61
|
+
`),l=!1;for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.endsWith(s)){let[m]=h.split("=");t?l=m==="PRIVATE_KEY":l=m==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(l){for(let p=i.length-1;p>=0;p--)if(i[p].endsWith(s)){let m=`${a}=${s}`;i[p]=m,r=i.join(`
|
|
62
|
+
`),G.writeFileSync(`${o}/.env`,r);break}}let d=new Re({secretKey:s}).getSigner();console.log(B.blue(`Using existing account: ${d.toSuiAddress()}`));return}}catch{}if(e||!n){let a=new Re().getSigner();n=a.getSecretKey();let l=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;r?r=r.trim()+`
|
|
63
|
+
`+l:r=l,G.writeFileSync(`${o}/.env`,r),console.log(B.green(`File created/updated at: ${o}/.env`)),console.log(B.blue(`New account generated: ${a.toSuiAddress()}`))}}var so={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 Ae(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ue=so;import ao from"chalk";import io from"dotenv";io.config();async function Ve(e){try{let o=await k({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(ao.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var co={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await Ve(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},qe=co;import{mkdirSync as lo,writeFileSync as po}from"fs";import{dirname as uo}from"path";async function mo(e,t,o,n){let r=await U(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
81
64
|
|
|
82
65
|
export const NETWORK: NetworkType = '${e}';
|
|
83
66
|
export const PACKAGE_ID = '${t}';
|
|
84
67
|
export const SCHEMA_ID = '${o}';
|
|
85
68
|
export const DUBHE_SCHEMA_ID = '${r}';
|
|
86
|
-
`;
|
|
87
|
-
Watch stopped.`),process.exit()})}},Ge=
|
|
69
|
+
`;go(s,n,"storeConfig")}async function go(e,t,o){lo(uo(t),{recursive:!0}),po(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Ke(e,t,o){let r=`${process.cwd()}/src/${e.name}`,s=await N(r,t);await mo(s.network,s.packageId,s.schemaId,o)}import{loadConfig as fo}from"@0xobelisk/sui-common";var ho={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 fo(e);await Ke(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Le=ho;import{loadConfig as yo}from"@0xobelisk/sui-common";var bo={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:a}){try{let i=await yo(t);await xe({dubheConfig:i,schema:o,objectId:n,network:e,packageId:r,metadataFilePath:s,params:a})}catch(i){E(i),process.exit(1)}process.exit(0)}},ze=bo;import{loadConfig as wo}from"@0xobelisk/sui-common";var vo={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:a}){try{let i=await wo(t);await _e({dubheConfig:i,moduleName:o,funcName:n,network:e,packageId:r,metadataFilePath:s,params:a})}catch(i){E(i),process.exit(1)}process.exit(0)}},Be=vo;import xo from"chokidar";import{exec as _o}from"child_process";var Co={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{_o("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=xo.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(`
|
|
70
|
+
Watch stopped.`),process.exit()})}},Ge=Co;import Io from"wait-on";import ko from"ora";import te from"chalk";var So={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=ko({text:`Waiting for service to start ${te.cyan(t.url)}...`,color:"cyan"});o.start();try{await Io({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(te.green("Service is ready!")),process.exit(0)}catch{o.fail(te.red("Timeout waiting for service")),console.error(te.yellow("Please make sure the service is running...")),process.exit(1)}}},He=So;var $o={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 O(e.network)}},We=$o;var Ye=[ke,Pe,Be,ze,$e,Ee,Oe,Ne,je,Fe,Ue,qe,Le,Ge,He,We];import*as Xe from"dotenv";import Je from"chalk";Xe.config();Eo(Po(process.argv)).scriptName("dubhe").command(Ye).strict().fail((e,t)=>{console.error(Je.red(e)),e.includes("Missing required argument")&&console.log(Je.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
71
|
//# sourceMappingURL=dubhe.js.map
|