@0xobelisk/sui-cli 1.2.0-pre.2 → 1.2.0-pre.21
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 +5 -1
- package/src/commands/info.ts +49 -0
- package/src/commands/localnode.ts +2 -8
- package/src/commands/switchEnv.ts +24 -0
- package/src/commands/test.ts +1 -1
- package/src/dubhe.ts +12 -4
- 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 Mo from"yargs";import{hideBin as Oo}from"yargs/helpers";import{execSync as Dt,spawn as Ie}from"child_process";import E from"chalk";import ot from"chalk";function W(){console.log(ot.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 ee}from"@0xobelisk/sui-client";import{execSync as yt}from"child_process";import f from"chalk";import*as ae from"fs/promises";import{mkdirSync as it,writeFileSync as ct}from"fs";import{dirname as lt}from"path";import{SUI_PRIVATE_KEY_PREFIX as dt}from"@mysten/sui/cryptography";import B from"chalk";import{ZodError as nt}from"zod";import{fromZodError as rt,ValidationError as st}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"},Y=class extends Error{name="UpgradeError"};function S(e){if(e instanceof st)console.log(B.redBright(e.message));else if(e instanceof nt){let t=rt(e,{prefixSeparator:`
|
|
36
14
|
- `,issueSeparator:`
|
|
37
|
-
- `});console.log(
|
|
38
|
-
\u274C Failed to
|
|
39
|
-
\u274C
|
|
40
|
-
\u274C Failed to
|
|
15
|
+
- `});console.log(B.redBright(t.message))}else e instanceof re?(console.log(B.red(e.message)),console.log(""),console.log(B.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof v?console.log(B.red(e)):console.log(e)}import*as X from"fs";import T from"chalk";import{spawn as de}from"child_process";import{Dubhe as pt}from"@0xobelisk/sui-client";var se={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.21",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 ie(e){if(e.startsWith(dt))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 ae.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 J(e,t){try{let o=await ae.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 J(o,"mainnet");case"testnet":return await J(o,"testnet");case"devnet":return await J(o,"devnet");case"localnet":return await J(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function pe(e,t){return(await N(e,t)).schemas}async function ue(e,t){return(await N(e,t)).version}async function V(e,t){return(await N(e,t)).packageId}async function Z(e,t){return(await N(e,t)).schemaId}async function me(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);ut(c,`${l}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function ut(e,t,o){it(lt(t),{recursive:!0}),ct(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function mt(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${se.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${se.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function Q(e,t){let o=X.readFileSync(e,"utf-8"),n=mt(t),r=o.replace(/Dubhe = \{.*\}/,n);X.writeFileSync(e,r,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function gt(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 ft(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 gt(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=de("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 ft(e),new Promise((t,o)=>{let n="",r="",s=de("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 F=e=>new Promise(t=>setTimeout(t,e));function ht(){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=ie(e);if(t===!1)throw new v("Please check your privateKey.");return t}function _({network:e,packageId:t,metadata:o}){let n=ht();return new pt({networkType:e,secretKey:n,packageId:t,metadata:o})}import*as M from"fs";import*as ge from"path";var C=60,z=1e3,P=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];async function fe(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 he(e,t,o,n,r){let s=ge.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,I]=m.split("=").map(w=>w.trim().replace(/"/g,""));switch(b){case"original-published-id":c.originalPublishedId=I;break;case"latest-published-id":c.latestPublishedId=I;break;case"published-version":c.publishedVersion=parseInt(I,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
|
|
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 ye(e){let t,o;try{let n=JSON.parse(yt(`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 be(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<C&&!r&&!s;){try{s=await e.suiInteractor.currentClient.getChainIdentifier()}catch{}if(r)break;if(!s){t++,t===C&&(console.log(f.red(` \u2514\u2500 Failed to connect to node after ${C} 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<C&&!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===C&&(console.log(f.red(` \u2514\u2500 Deployer account has no SUI balance after ${C} 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===C&&(console.log(f.red(` \u2514\u2500 Failed to check deployer balance after ${C} 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 bt(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 be(e);console.log(" \u251C\u2500 Validating Environment..."),await fe(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
|
|
33
|
+
\u{1F4E6} Building Contract...`);let[a,i]=ye(n);console.log(`
|
|
34
|
+
\u{1F504} Publishing Contract...`);let l=new ee;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,I=()=>{b=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
|
|
35
|
+
\u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",I);try{for(;p<C&&!d&&!b;)try{d=await e.signAndSendTxn({tx:l})}catch{if(b)break;p++,p===C&&(console.log(f.red(` \u2514\u2500 Publication failed after ${C} attempts`)),console.log(f.red(" \u2514\u2500 Please check your network connection and try again later.")),process.exit(1));let ne=Math.floor((Date.now()-m)/1e3),et=P[h%P.length];h++,process.stdout.write(`\r \u251C\u2500 ${et} Retrying... (${ne}s)`),await new Promise(tt=>setTimeout(tt,z))}}finally{process.removeListener("SIGINT",I)}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="",A="",R=t.schemas,k="",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}`),k=u.objectId||""),u.type==="created"&&x.push(u)}),console.log(` \u2514\u2500 Transaction: ${d.digest}`),he(`${n}/Move.lock`,o,"publish",s,D),console.log(`
|
|
36
|
+
\u26A1 Executing Deploy Hook...`),await F(5e3);let y=new ee,$=[];if(t.name!=="dubhe"){let u=await U(o);$.push(y.object(u))}$.push(y.object("0x6")),y.moveCall({target:`${D}::${t.name}_genesis::run`,arguments:$});let g;try{g=await e.signAndSendTxn({tx:y})}catch(u){console.error(f.red(" \u2514\u2500 Deploy hook execution failed")),console.error(u.message),process.exit(1)}g.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${g.digest}`),console.log(`
|
|
37
|
+
\u{1F4CB} Created Objects:`),g.objectChanges?.map(u=>{u.type==="created"&&u.objectType&&u.objectType.includes("schema::Schema")&&(A=u.objectId||""),u.type==="created"&&u.objectType&&u.objectType.includes("schema")&&!u.objectType.includes("dynamic_field")&&x.push(u)}),x.map(u=>{console.log(` \u251C\u2500 Type: ${u.objectType}`),console.log(` \u2514\u2500 ID: ${u.objectId}`)}),L(t.name,o,D,A,k,w,R),console.log(`
|
|
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 wt(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 vt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await wt(n))return;console.log(`
|
|
41
|
+
\u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let r=await be(e);await fe(`${n}/Move.lock`,t);let[s,a]=ye(n),i=new ee,[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&&!c&&!m;)try{c=await e.signAndSendTxn({tx:i})}catch{if(m)break;d++,d===C&&(console.log(f.red(` \u2514\u2500 Publication failed after ${C} attempts`)),console.log(f.red(" \u2514\u2500 Please check your network connection and try again later.")),process.exit(1));let $=Math.floor((Date.now()-h)/1e3),g=P[p%P.length];p++,process.stdout.write(`\r \u251C\u2500 ${g} Retrying... (${$}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 I=1,w="",D="",A={},R="";c.objectChanges.map(y=>{y.type==="published"&&(w=y.packageId||""),y.type==="created"&&y.objectType&&y.objectType==="0x2::package::UpgradeCap"&&(R=y.objectId||"")}),await F(3e3);let k=new ee;k.moveCall({target:`${w}::dubhe_genesis::run`,arguments:[k.object("0x6")]});let x;try{x=await e.signAndSendTxn({tx:k})}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,R,I,A),he(`${n}/Move.lock`,t,"publish",r,w),await F(1e3)}async function we(e,t,o){await O(t);let n=_({network:t});t==="localnet"&&await vt(n,t);let s=`${process.cwd()}/src/${e.name}`;await Q(`${s}/Move.toml`,t),await bt(n,e,t,s,o)}import{loadMetadata as xt}from"@0xobelisk/sui-client";import*as ve from"fs";import*as xe from"path";function _t(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 Ct(e){switch(e.split("<")[0].trim()){case"StorageValue":return 0;case"StorageMap":return 1;case"StorageDoubleMap":return 2;default:return 0}}async function _e({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 Z(l,n);let c;if(a?c=await ce(a):c=await xt(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(!_t(d,p))throw new Error(`Invalid params count for ${d}. Expected: ${Ct(d)}, Got: ${p.length}`);let m=await _({network:n,packageId:s,metadata:c}).parseState({schema:t,objectId:r,storageType:d,params:p});console.log(m)}async function ce(e){if(xe.extname(e)!==".json")throw new Error("Metadata file must be in JSON format");try{let t=ve.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 It,Transaction as kt}from"@0xobelisk/sui-client";var St=["u8","u16","u32","u64","u128","u256","bool","id","string","address","object"];function $t(e){try{e.forEach(t=>{let[o,n]=t.split(":");if(!St.includes(o))throw new Error(`Invalid param type: ${o}`)})}catch(t){throw new Error(`Invalid params: ${t}`)}}function Et(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 Pt(e,t){return t.map(o=>Et(e,o))}async function Ce({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 ce(a):c=await It(r,s),!c)throw new v("Metadata file not found. Please provide a metadata file path or set the packageId.");let d=n||[];$t(d);let p=_({network:r,packageId:s,metadata:c}),h=new kt,m=Pt(h,d),b=await p.tx[t][o]({tx:h,params:m});console.log(JSON.stringify(b,null,2))}import{Dubhe as Tt}from"@0xobelisk/sui-client";function Mt(){try{let e=process.platform==="win32"?'tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH':'pgrep -f "sui start"',t=Dt(e).toString().trim();return process.platform==="win32"?t.toLowerCase().includes("sui.exe"):t.length>0}catch{return!1}}async function Ot(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let r=new Tt({secretKey:t}).getSigner();Ie("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(E.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(E.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Nt(e){let t=()=>{console.log(E.yellow(`
|
|
43
|
+
\u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function ke(){if(Mt()){console.log(E.yellow(`
|
|
44
|
+
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(E.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(E.yellow(" \u2514\u2500 Please stop the existing process first"));return}W(),console.log("\u{1F680} Starting Local Node...");let e=null;try{if(e=Ie("sui",["start","--with-faucet","--force-regenesis"],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),e.on("error",o=>{console.error(E.red(`
|
|
45
|
+
\u274C Failed to Start Local Node`)),console.error(E.red(` \u2514\u2500 Error: ${o.message}`))}),await F(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 Ot(),await F(2e3),ie("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new v("Please check your privateKey.");console.log(E.green("\u{1F389} Local environment is ready!")),Nt(e),await new Promise(o=>{e?.on("exit",()=>o())})}catch(t){console.error(E.red(`
|
|
46
|
+
\u274C Failed to Start Local Node`)),console.error(E.red(` \u2514\u2500 Error: ${t.message}`)),e&&e.kill("SIGINT"),process.exit(1)}}var Ft={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)}}},Se=Ft;import{requestSuiFromFaucetV0 as jt,getFaucetHost as At}from"@mysten/sui/faucet";import{SuiClient as Rt,getFullnodeUrl as Ut}from"@mysten/sui/client";var le=60,Vt=1e3,$e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qt={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=_(e).getAddress():o=t,console.log(`
|
|
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<le&&!r&&!i;)try{await jt({host:At(e),recipient:o}),r=!0}catch{if(i)break;n++,n===le&&(console.log(` \u2514\u2500 Failed to request funds after ${le} 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=$e[s%$e.length];s++,process.stdout.write(`\r \u251C\u2500 ${b} Retrying... (${m}s)`),await new Promise(I=>setTimeout(I,Vt))}}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 Rt({url:Ut(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)}},Ee=qt;import{schemaGen as Kt,loadConfig as Bt}from"@0xobelisk/sui-common";import Lt from"chalk";var zt={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 Bt(e);await Kt(o,void 0,t),process.exit(0)}catch(o){console.log(Lt.red("Schemagen failed!")),console.error(o.message)}}},Pe=zt;import{loadConfig as Gt}from"@0xobelisk/sui-common";var Ht={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 Gt(t);await we(n,e,o)}catch(n){S(n),process.exit(1)}process.exit(0)}},De=Ht;import{Transaction as Te,UpgradePolicy as Wt}from"@0xobelisk/sui-client";import{execSync as Yt}from"child_process";import j from"chalk";import*as q from"fs";import*as Me from"path";function Jt(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=
|
|
78
|
-
`),l=!1;for(let
|
|
79
|
-
`),
|
|
80
|
-
`+l:r=l,
|
|
55
|
+
`,a=n.replace(r,s);q.writeFileSync(o,a,"utf-8")}function te(e,t,o,n){let r=Me.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 Oe(e,t,o){await O(o);let n=process.cwd(),r=`${n}/src/${t}`,s=_({network:o}),a=Number(await ue(r,o)),i=await V(r,o),l=await me(r,o),c=await Z(r,o),d=te(`${r}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),p=[],h=await pe(r,o);Object.entries(e.schemas).forEach(([m,b])=>{h.hasOwnProperty(m)||p.push({schemaName:m,fields:b})}),Jt(r,p);try{let m,b,I;try{let{modules:g,dependencies:u,digest:ne}=JSON.parse(Yt(`sui move build --dump-bytecode-as-base64 --path ${n}/src/${t}`,{encoding:"utf-8"}));m=g,b=u,I=ne}catch(g){throw new Y(g.stdout)}console.log(`
|
|
58
|
+
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",i),console.log("\u{1F4CB} UpgradeCap Object Id:",l),console.log("\u{1F4CB} OldVersion:",a);let w=new Te,D=w.moveCall({target:"0x2::package::authorize_upgrade",arguments:[w.object(l),w.pure.u8(Wt.COMPATIBLE),w.pure.vector("u8",I)]}),A=w.upgrade({modules:m,dependencies:b,package:i,ticket:D});w.moveCall({target:"0x2::package::commit_upgrade",arguments:[w.object(l),A]});let R=await s.signAndSendTxn({tx:w,onSuccess:g=>{console.log(j.green(`Upgrade Transaction Digest: ${g.digest}`))},onError:g=>{console.log(j.red("Upgrade Transaction failed!")),console.error(g)}}),k="";R.objectChanges.map(g=>{g.type==="published"&&(console.log(j.blue(`${t} new PackageId: ${g.packageId}`)),console.log(j.blue(`${t} new Version: ${a+1}`)),k=g.packageId)}),te(`${r}/Move.lock`,o,"original-published-id",d),te(`${r}/Move.lock`,o,"latest-published-id",k),te(`${r}/Move.lock`,o,"published-version",a+1+""),L(t,o,k,c,l,a+1,e.schemas),console.log(`
|
|
59
|
+
\u{1F680} Starting Migration Process...`),p.forEach(g=>{console.log("\u{1F4CB} Added Fields:",JSON.stringify(g,null,2))}),await new Promise(g=>setTimeout(g,5e3));let x=new Te,y=a+1,$=[];if(t!=="dubhe"){let g=await U(o);$.push(x.object(g))}$.push(x.object(c)),$.push(x.pure.address(k)),$.push(x.pure.u32(y)),x.moveCall({target:`${k}::${t}_migrate::migrate_to_v${y}`,arguments:$}),await s.signAndSendTxn({tx:x,onSuccess:g=>{console.log(j.green(`Migration Transaction Digest: ${g.digest}`))},onError:g=>{console.log(j.red("Migration Transaction failed!, Please execute the migration manually.")),console.error(g)}})}catch(m){console.log(j.red("upgrade handler execution failed!")),console.error(m.message)}}import{loadConfig as Xt}from"@0xobelisk/sui-common";var Zt={command:"upgrade",describe:"Upgrade your move contracts",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Network of the node (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",decs:"Path to the config file"}})},async handler({network:e,"config-path":t}){try{let o=await Xt(t);await Oe(o,o.name,e)}catch(o){S(o),process.exit(1)}process.exit(0)}},Ne=Zt;import{execSync as Qt}from"child_process";import{loadConfig as eo}from"@0xobelisk/sui-common";var to={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await eo(e),a=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Qt(a,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Fe=to;import{execSync as oo}from"child_process";import no from"chalk";import{loadConfig as ro}from"@0xobelisk/sui-common";var so={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await ro(e),s=`${process.cwd()}/src/${n.name}`;await O(t),await Q(s+"/Move.toml",t);let a=`sui move build --path ${s} ${o?" --dump-bytecode-as-base64":""}`,i=oo(a,{encoding:"utf-8"});console.log(i)}catch(n){console.error(no.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},je=so;var ao={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){W()}},Ae=ao;import{Dubhe as Re}from"@0xobelisk/sui-client";import*as H from"fs";import G from"chalk";async function Ue(e=!1,t=!1){t&&(console.log(G.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(G.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
|
|
60
|
+
`)));let o=process.cwd(),n,r="";try{r=H.readFileSync(`${o}/.env`,"utf8");let s=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(s=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),s){let a=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",i=r.split(`
|
|
61
|
+
`),l=!1;for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.endsWith(s)){let[m]=h.split("=");t?l=m==="PRIVATE_KEY":l=m==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(l){for(let p=i.length-1;p>=0;p--)if(i[p].endsWith(s)){let m=`${a}=${s}`;i[p]=m,r=i.join(`
|
|
62
|
+
`),H.writeFileSync(`${o}/.env`,r);break}}let d=new Re({secretKey:s}).getSigner();console.log(G.blue(`Using existing account: ${d.toSuiAddress()}`));return}}catch{}if(e||!n){let a=new Re().getSigner();n=a.getSecretKey();let l=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;r?r=r.trim()+`
|
|
63
|
+
`+l:r=l,H.writeFileSync(`${o}/.env`,r),console.log(G.green(`File created/updated at: ${o}/.env`)),console.log(G.blue(`New account generated: ${a.toSuiAddress()}`))}}var io={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await Ue(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ve=io;import co from"chalk";import lo from"dotenv";lo.config();async function qe(e){try{let o=await _({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new v("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(co.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new v("Failed to check balance: "+t)}}var po={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await qe(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ke=po;import{mkdirSync as uo,writeFileSync as mo}from"fs";import{dirname as go}from"path";async function fo(e,t,o,n){let r=await U(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
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()})}},
|
|
69
|
+
`;ho(s,n,"storeConfig")}async function ho(e,t,o){uo(go(t),{recursive:!0}),mo(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Be(e,t,o){let r=`${process.cwd()}/src/${e.name}`,s=await N(r,t);await fo(s.network,s.packageId,s.schemaId,o)}import{loadConfig as yo}from"@0xobelisk/sui-common";var bo={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 yo(e);await Be(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Le=bo;import{loadConfig as wo}from"@0xobelisk/sui-common";var vo={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 wo(t);await _e({dubheConfig:i,schema:o,objectId:n,network:e,packageId:r,metadataFilePath:s,params:a})}catch(i){S(i),process.exit(1)}process.exit(0)}},ze=vo;import{loadConfig as xo}from"@0xobelisk/sui-common";var _o={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 xo(t);await Ce({dubheConfig:i,moduleName:o,funcName:n,network:e,packageId:r,metadataFilePath:s,params:a})}catch(i){S(i),process.exit(1)}process.exit(0)}},Ge=_o;import Co from"chokidar";import{exec as Io}from"child_process";var ko={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{Io("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=Co.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()})}},He=ko;import So from"wait-on";import $o from"ora";import oe from"chalk";var Eo={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 ${oe.cyan(t.url)}...`,color:"cyan"});o.start();try{await So({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(oe.green("Service is ready!")),process.exit(0)}catch{o.fail(oe.red("Timeout waiting for service")),console.error(oe.yellow("Please make sure the service is running...")),process.exit(1)}}},We=Eo;var Po={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)}},Ye=Po;import Do from"dotenv";import K from"chalk";Do.config();var To={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=_({network:e}),o=t.getSigner();console.log(K.blue("Account Information:")),console.log(` Network: ${K.green(e)}`),console.log(` Address: ${K.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),r=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${K.green(r)} SUI`)}catch{console.log(` Balance: ${K.red("Failed to fetch balance")} ${K.gray("(Network error)")}`)}}catch(t){S(t),process.exit(1)}}},Je=To;var Xe=[Se,De,Ge,ze,Ee,Pe,Ne,Fe,je,Ae,Ve,Ke,Le,He,We,Ye,Je];import*as Qe from"dotenv";import Ze from"chalk";Qe.config();Mo(Oo(process.argv)).scriptName("dubhe").command(Xe).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t,o)=>{console.error(Ze.red(e)),e.includes("Missing required argument")&&console.log(Ze.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),t&&(console.log(""),S(t),console.log("")),o.showHelp(),process.exit(1)}).alias({h:"help"}).argv;
|
|
88
71
|
//# sourceMappingURL=dubhe.js.map
|