@0xobelisk/sui-cli 1.1.2 → 1.1.4
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 +61 -50
- package/dist/dubhe.js.map +1 -1
- package/package.json +3 -3
- package/src/commands/build.ts +6 -2
- package/src/commands/index.ts +2 -0
- package/src/commands/install.ts +126 -0
- package/src/commands/localnode.ts +18 -3
- package/src/utils/publishHandler.ts +77 -106
- package/src/utils/startNode.ts +11 -5
- package/src/utils/utils.ts +0 -4
package/dist/dubhe.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Ho from"yargs";import{hideBin as Jo}from"yargs/helpers";import{execSync as qt,spawn as ke}from"child_process";import _ from"chalk";import Ze from"chalk";function U(){console.log(Ze.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,39 +10,50 @@ Welcome to Dubhe
|
|
|
10
10
|
\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
|
|
11
11
|
\\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
|
|
12
12
|
|
|
13
|
-
`))}import{Dubhe as
|
|
13
|
+
`))}import{Dubhe as mt,Transaction as B}from"@0xobelisk/sui-client";import{execSync as ut}from"child_process";import v from"chalk";import M from"chalk";import{ZodError as Qe}from"zod";import{fromZodError as et,ValidationError as tt}from"zod-validation-error";var G=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},m=class extends Error{name="DubheCliError"},q=class extends Error{name="UpgradeError"},Y=class extends Error{name="FsIibError"};function x(e){if(e instanceof tt)console.log(M.redBright(e.message));else if(e instanceof Qe){let t=et(e,{prefixSeparator:`
|
|
14
14
|
- `,issueSeparator:`
|
|
15
|
-
- `});console.log(
|
|
16
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
17
|
-
\u274C Process exited with code: ${a}`)),o(new Error(`Process exited with code: ${a}`))):t()})})}catch(t){console.error(
|
|
18
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
19
|
-
|
|
15
|
+
- `});console.log(M.redBright(t.message))}else e instanceof G?(console.log(M.red(e.message)),console.log(""),console.log(M.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof m?console.log(M.red(e)):console.log(e)}import*as oe from"fs/promises";import{mkdirSync as ot,writeFileSync as nt}from"fs";import{dirname as rt}from"path";import{SUI_PRIVATE_KEY_PREFIX as at}from"@mysten/sui/cryptography";import F from"chalk";import{spawn as st}from"child_process";function w(e){if(e.startsWith(at))return e.length===70?e:!1;if(e.startsWith("0x")){let t=e.slice(2);return t.length===64?t:!1}else return e.length===64?e:!1}async function N(e,t){try{let o=await oe.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch{throw new Y("Fs read deployment file failed.")}}async function ne(e,t){return(await N(e,t)).schemas}async function re(e,t){return(await N(e,t)).version}async function T(e,t){return(await N(e,t)).packageId}async function R(e,t){return(await N(e,t)).schemaId}async function ae(e,t){return(await N(e,t)).upgradeCap}function L(e,t,o,n,a,r,i){let s={projectName:e,network:t,packageId:o,schemaId:n,schemas:i,upgradeCap:a,version:r},l=process.cwd(),d=JSON.stringify(s,null,2);it(d,`${l}/contracts/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function it(e,t,o){ot(rt(t),{recursive:!0}),nt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function O(e){try{return new Promise((t,o)=>{let n=st("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});n.on("error",a=>{console.error(F.red(`
|
|
16
|
+
\u274C Failed to Switch Env`)),console.error(F.red(` Error: ${a.message}`)),o(a)}),n.on("exit",a=>{a!==0?(console.error(F.red(`
|
|
17
|
+
\u274C Process exited with code: ${a}`)),o(new Error(`Process exited with code: ${a}`))):t()})})}catch(t){console.error(F.red(`
|
|
18
|
+
\u274C Failed to Switch Env`)),console.error(F.red(` \u2514\u2500 Error: ${t}`))}}var D=e=>new Promise(t=>setTimeout(t,e));import*as $ from"fs";import*as de from"path";import{homedir as gt}from"node:os";import{execSync as ct}from"child_process";import{loadConfig as lt}from"@0xobelisk/sui-common";import{existsSync as se,writeFileSync as ie}from"fs";import{homedir as W}from"node:os";import{join as ce}from"path";import{readFileSync as dt}from"node:fs";function K(e){let t=e.split("/").filter(n=>n.length>0);return t[t.length-1].replace(/^\${(.*)}$/,"$1")}function j(e,t,o){let n=`[package]
|
|
19
|
+
name = "${t}"
|
|
20
|
+
version = "1.0.0"
|
|
21
|
+
edition = "2024"
|
|
22
|
+
|
|
23
|
+
[dependencies]
|
|
24
|
+
`;if(n+=`Sui = { git = "https://github.com/MystenLabs/sui.git", subdir = "crates/sui-framework/packages/sui-framework", rev = "mainnet-v1.38.3" }
|
|
25
|
+
`,o==="localnet"){let a=`${W()}/.dubhe/dependencies/dubhe-framework`;n+=`Dubhe = { local = "${a}" }
|
|
26
|
+
`,e.forEach(r=>{let i=K(r.git);if(r.name&&r.name.toLowerCase()==="dubhe")return;let s=`${W()}/.dubhe/dependencies/${i}`;r.subdir&&(s+=`/${r.subdir}`);let l=r.name||i;n+=`${l} = { local = "${s}" }
|
|
27
|
+
`;let d=ce(s,"Move.toml");if(se(d))try{let c=dt(d,"utf-8"),p=/Dubhe\s*=\s*{[^}]*}/g;c.match(p)&&(c=c.replace(p,`Dubhe = { local = "${a}" }`),ie(d,c,"utf-8"))}catch(c){console.error(`Failed to update Move.toml at ${d}: ${c}`)}})}else e.forEach(a=>{let r=K(a.git),i=a.name||r;n+=`${i} = { git = "${a.git}", rev = "${a.rev}"`,a.subdir&&(n+=`, subdir = "${a.subdir}"`),n+=` }
|
|
28
|
+
`});return n+=`
|
|
29
|
+
[addresses]
|
|
30
|
+
sui = "0x2"
|
|
31
|
+
${t} = "0x0"
|
|
32
|
+
`,n}var pt={command:"install",describe:"Install a repository in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Path to the configuration file"}}).options({network:{type:"string",default:"localnet",description:"Path to the configuration file"}})},async handler({"config-path":e,network:t}){try{let o=await lt(e);await X(o,t)}catch(o){console.error(`Error installing repository: ${o.message}`),process.exit(1)}}};async function X(e,t){e.dependencies.forEach(a=>{let r=K(a.git),i=ce(W(),".dubhe","dependencies",r);if(!se(i)){console.log(`\u{1F680} Installing repository: ${a.git}`);let s=`git clone --depth 1 --branch ${a.rev} ${a.git} ${i}`;ct(s,{stdio:"inherit",encoding:"utf-8"})}});let o=j(e.dependencies,e.name,t),n=`${process.cwd()}/contracts/${e.name}/Move.toml`;ie(n,o,{encoding:"utf-8"})}var le=pt;import{writeFileSync as ft}from"fs";async function pe(e,t){if(!$.existsSync(e))return;let o=$.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),a=o.replace(n,"");$.writeFileSync(e,a,"utf-8")}function me(e,t,o,n,a){let r=de.resolve(e),i=$.readFileSync(r,"utf-8"),s=i.split(`
|
|
33
|
+
`),l=s.findIndex(u=>u.trim()===`[env.${t}]`),d={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(l===-1)if(o==="publish")d.originalPublishedId=a,d.latestPublishedId=a,d.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let u=l+1;u<s.length;u++){let h=s[u].trim();if(h.startsWith("["))break;let[k,f]=h.split("=").map(C=>C.trim().replace(/"/g,""));switch(k){case"original-published-id":d.originalPublishedId=f;break;case"latest-published-id":d.latestPublishedId=f;break;case"published-version":d.publishedVersion=parseInt(f,10);break}}o==="publish"?(d.originalPublishedId=a,d.latestPublishedId=a,d.publishedVersion=1):o==="upgrade"&&(d.latestPublishedId=a,d.publishedVersion+=1)}let c=`
|
|
20
34
|
[env.${t}]
|
|
21
35
|
chain-id = "${d.chainId}"
|
|
22
36
|
original-published-id = "${d.originalPublishedId}"
|
|
23
37
|
latest-published-id = "${d.latestPublishedId}"
|
|
24
38
|
published-version = "${d.publishedVersion}"
|
|
25
|
-
`,
|
|
26
|
-
`)+c
|
|
39
|
+
`,p=l===-1?i+c:s.slice(0,l).join(`
|
|
40
|
+
`)+c;$.writeFileSync(r,p,"utf-8")}function ue(e){let t,o;try{let n=JSON.parse(ut(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(v.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function ht(e,t,o,n,a){let r=await e.suiInteractor.currentClient.getChainIdentifier();await pe(`${n}/Move.lock`,o),console.log(`
|
|
27
41
|
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(` \u251C\u2500 ChainId: ${r}`),console.log(" \u251C\u2500 Validating Environment..."),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
|
|
28
|
-
\u{1F4E6} Building Contract...`);let[i,s]=
|
|
29
|
-
\u{1F504} Publishing Contract...`);let l=new
|
|
30
|
-
\u26A1 Executing Deploy Hook...`),await D(5e3);let C=new
|
|
31
|
-
\u{1F4CB} Created Schemas:`),
|
|
42
|
+
\u{1F4E6} Building Contract...`);let[i,s]=ue(n);console.log(`
|
|
43
|
+
\u{1F504} Publishing Contract...`);let l=new B;a&&l.setGasBudget(a);let[d]=l.publish({modules:i,dependencies:s});l.transferObjects([d],e.getAddress());let c;try{c=await e.signAndSendTxn({tx:l})}catch(g){console.error(v.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}c.effects?.status.status==="failure"&&(console.log(v.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let p=1,u="",h="",k=t.schemas,f="";c.objectChanges.map(g=>{g.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${g.packageId}`),u=g.packageId),g.type==="created"&&g.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${g.objectId}`),f=g.objectId)}),console.log(` \u2514\u2500 Transaction: ${c.digest}`),me(`${n}/Move.lock`,o,"publish",r,u),console.log(`
|
|
44
|
+
\u26A1 Executing Deploy Hook...`),await D(5e3);let C=new B;C.moveCall({target:`${u}::${t.name}_genesis::run`,arguments:[C.object("0x6")]});let y;try{y=await e.signAndSendTxn({tx:C})}catch(g){console.error(v.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}y.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${y.digest}`),console.log(`
|
|
45
|
+
\u{1F4CB} Created Schemas:`),y.objectChanges?.map(g=>{g.type==="created"&&g.objectType.includes("schema::Schema")&&(h=g.objectId),g.type==="created"&&g.objectType.includes("schema")&&!g.objectType.includes("dynamic_field")&&(console.log(` \u251C\u2500 ${g.objectType}`),console.log(` \u2514\u2500 ID: ${g.objectId}`))}),L(t.name,o,u,h,f,p,k),console.log(`
|
|
32
46
|
\u2705 Contract Publication Complete
|
|
33
|
-
`)):(console.log(
|
|
34
|
-
\
|
|
35
|
-
\
|
|
36
|
-
\
|
|
37
|
-
\u{1F4E6} Building Contract...`);let[r,i]=ie(n);console.log(`
|
|
38
|
-
\u{1F504} Publishing Contract...`);let s=new G,[l]=s.publish({modules:r,dependencies:i});s.transferObjects([l],e.getAddress());let d;try{d=await e.signAndSendTxn({tx:s})}catch(f){console.error(h.red(" \u2514\u2500 Publication failed")),console.error(f.message),process.exit(1)}d.effects?.status.status==="failure"&&(console.log(h.red(" \u2514\u2500 Publication failed")),process.exit(1));let c=1,u="",m={},y="";d.objectChanges.map(f=>{f.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${f.packageId}`),u=f.packageId),f.type==="created"&&f.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${f.objectId}`),y=f.objectId)}),console.log(` \u2514\u2500 Transaction: ${d.digest}`),se(`${n}/Move.lock`,t,"publish",a,u),K("dubhe-framework",t,u,"",y,c,m),await D(1e3),console.log(h.green(`
|
|
39
|
-
\u2705 Dubhe Framework deployed successfully`))}async function ce(e,t,o){await O(t);let n=process.env.PRIVATE_KEY;if(!n)throw new p(`Missing PRIVATE_KEY environment variable.
|
|
47
|
+
`)):(console.log(v.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(v.yellow(" Please republish or manually call deploy_hook::run")),console.log(v.yellow(" Please check the transaction digest:")),console.log(v.yellow(` ${y.digest}`)),process.exit(1))}async function ge(e,t,o){let n=await t.suiInteractor.currentClient.getChainIdentifier();for(let a of e.dependencies){let r=K(a.git),i=`${gt()}/.dubhe/dependencies/${r}`;if(a.subdir&&(i+=`/${a.subdir}`),console.log(`
|
|
48
|
+
\u{1F680} Initialize dependencies...`),console.log(` \u251C\u2500 Project: ${i}`),!$.existsSync(i)){console.log(v.yellow(`
|
|
49
|
+
\u2139\uFE0F Please install Dubhe Framework`)),console.log(v.yellow(`
|
|
50
|
+
\u2139\uFE0F Execute the following command:`)),console.log(v.yellow("pnpm dubhe install"));continue}await pe(`${i}/Move.lock`,o);let[s,l]=ue(i),d=new B,[c]=d.publish({modules:s,dependencies:l});d.transferObjects([c],t.getAddress());let p;try{p=await t.signAndSendTxn({tx:d})}catch(u){console.error(v.red(" \u2514\u2500 Publication failed")),console.error(u.message),process.exit(1)}p.effects?.status.status==="failure"&&(console.log(v.red(" \u2514\u2500 Publication failed")),process.exit(1)),p.objectChanges.map(async u=>{if(u.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${u.packageId}`),me(`${i}/Move.lock`,o,"publish",n,u.packageId),a.name==="merak")){await D(2e3);let h=new B;h.moveCall({target:`${u.packageId}::genesis::run`,arguments:[h.object("0x6")]});let k;try{k=await t.signAndSendTxn({tx:h})}catch(f){console.error(v.red(" \u2514\u2500 Deploy hook execution failed")),console.error(f.message),process.exit(1)}k.effects?.status.status==="success"&&k.objectChanges?.map(f=>{f.type==="created"&&f.objectType.includes("schema::Schema")&&console.log(` \u251C\u2500 Schema ID: ${f.objectId}`)})}})}}async function fe(e,t,o){await O(t);let n=process.env.PRIVATE_KEY;if(!n)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
40
51
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
41
|
-
in your contracts directory to use the default sui private key.`);let a=
|
|
52
|
+
in your contracts directory to use the default sui private key.`);let a=w(n);if(a===!1)throw new m("Please check your privateKey.");let r=new mt({secretKey:a,networkType:t}),s=`${process.cwd()}/contracts/${e.name}`,l=j(e.dependencies,e.name,t);ft(`${s}/Move.toml`,l,{encoding:"utf-8"}),await ht(r,e,t,s,o)}import{Dubhe as yt,loadMetadata as bt}from"@0xobelisk/sui-client";import*as he from"fs";import*as ye from"path";function wt(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 vt(e){switch(e.split("<")[0].trim()){case"StorageValue":return 0;case"StorageMap":return 1;case"StorageDoubleMap":return 2;default:return 0}}async function be({dubheConfig:e,schema:t,params:o,network:n,objectId:a,packageId:r,metadataFilePath:i}){let s=process.env.PRIVATE_KEY;if(!s)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
42
53
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
43
|
-
in your contracts directory to use the default sui private key.`);let l=
|
|
54
|
+
in your contracts directory to use the default sui private key.`);let l=w(s);if(l===!1)throw new m("Please check your privateKey.");let c=`${process.cwd()}/contracts/${e.name}`;r=r||await T(c,n),a=a||await R(c,n);let p;if(i?p=await Z(i):p=await bt(n,r),!p)throw new m("Metadata file not found. Please provide a metadata file path or set the packageId.");if(!e.schemas[t])throw new m(`Schema "${t}" not found in dubhe config. Available schemas: ${Object.keys(e.schemas).join(", ")}`);let u=e.schemas[t],h=o||[];if(!wt(u,h))throw new Error(`Invalid params count for ${u}. Expected: ${vt(u)}, Got: ${h.length}`);let f=await new yt({secretKey:l,networkType:n,packageId:r,metadata:p}).parseState({schema:t,objectId:a,storageType:u,params:h});console.log(f)}async function Z(e){if(ye.extname(e)!==".json")throw new Error("Metadata file must be in JSON format");try{let t=he.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{Dubhe as kt,loadMetadata as xt,Transaction as _t}from"@0xobelisk/sui-client";var Et=["u8","u16","u32","u64","u128","u256","bool","id","string","address","object"];function St(e){try{e.forEach(t=>{let[o,n]=t.split(":");if(!Et.includes(o))throw new Error(`Invalid param type: ${o}`)})}catch(t){throw new Error(`Invalid params: ${t}`)}}function Ct(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=>Ct(e,o))}async function we({dubheConfig:e,moduleName:t,funcName:o,params:n,network:a,packageId:r,metadataFilePath:i}){let s=process.env.PRIVATE_KEY;if(!s)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
44
55
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
45
|
-
in your contracts directory to use the default sui private key.`);let l=
|
|
56
|
+
in your contracts directory to use the default sui private key.`);let l=w(s);if(l===!1)throw new m("Please check your privateKey.");let c=`${process.cwd()}/contracts/${e.name}`;r=r||await T(c,a);let p;if(i?p=await Z(i):p=await xt(a,r),!p)throw new m("Metadata file not found. Please provide a metadata file path or set the packageId.");let u=n||[];St(u);let h=new kt({secretKey:l,networkType:a,packageId:r,metadata:p}),k=new _t,f=$t(k,u),C=await h.tx[t][o]({tx:k,params:f});console.log(JSON.stringify(C,null,2))}import{getFullnodeUrl as It,SuiClient as Dt}from"@mysten/sui/client";import Pt from"sqlite3";import{open as Tt}from"sqlite";import Rt from"chalk";var E,Ot=async e=>(E=await Tt({filename:`./${e}.db`,driver:Pt.Database}),await At(E,e),await Mt(E),E),At=async(e,t)=>{let o=`
|
|
46
57
|
CREATE TABLE IF NOT EXISTS ${t} (
|
|
47
58
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
48
59
|
last_update_checkpoint TEXT,
|
|
@@ -52,67 +63,67 @@ in your contracts directory to use the default sui private key.`);let l=k(s);if(
|
|
|
52
63
|
key2 TEXT,
|
|
53
64
|
value TEXT,
|
|
54
65
|
is_removed BOOLEAN DEFAULT FALSE
|
|
55
|
-
)`;await e.exec(o)},
|
|
66
|
+
)`;await e.exec(o)},Mt=async e=>{let t=`
|
|
56
67
|
CREATE TABLE IF NOT EXISTS dapp_transaction (
|
|
57
68
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
58
69
|
checkpoint TEXT,
|
|
59
70
|
digest TEXT
|
|
60
71
|
)
|
|
61
|
-
`;await e.exec(t)},
|
|
72
|
+
`;await e.exec(t)},Ft=async(e,t,o,n,a)=>{let r=a;typeof r.key1=="object"&&r.key1!==null||Array.isArray(r.key1)?r.key1=V(r.key1):typeof r.key2=="object"&&r.key2!==null||Array.isArray(r.key2)?r.key2=V(r.key2):(typeof r.value=="object"||Array.isArray(r.value))&&(r.value=V(r.value)),await Kt(e,t,{checkpoint:o,digest:n,event:r})},Nt=async(e,t,o,n,a)=>{let r=a;typeof r.key1=="object"&&r.key1!==null||Array.isArray(r.key1)?r.key1=V(r.key1):(typeof r.key2=="object"&&r.key2!==null||Array.isArray(r.key2))&&(r.key2=V(r.key2)),await jt(e,t,{checkpoint:o,digest:n,event:r})},V=e=>e.hasOwnProperty("fields")?JSON.stringify(e.fields):JSON.stringify(e);async function Kt(e,t,o){let{checkpoint:n,digest:a,event:r}=o,i=`
|
|
62
73
|
INSERT OR REPLACE INTO ${t} (id, last_update_checkpoint, last_update_digest, name, key1, key2, value)
|
|
63
74
|
VALUES (
|
|
64
75
|
(SELECT id FROM ${t} WHERE name = ? AND (key1 = ? OR key1 IS NULL) AND (key2 = ? OR key2 IS NULL)),
|
|
65
76
|
?, ?, ?, ?, ?, ?
|
|
66
77
|
)
|
|
67
|
-
`,s=[r.name,r.key1,r.key2,n,a,r.name,r.key1,r.key2,r.value];await e.run(i,s),console.log("Insert or update data: ",n,a,t,o)}async function
|
|
78
|
+
`,s=[r.name,r.key1,r.key2,n,a,r.name,r.key1,r.key2,r.value];await e.run(i,s),console.log("Insert or update data: ",n,a,t,o)}async function jt(e,t,o){let{checkpoint:n,digest:a,event:r}=o,i=`
|
|
68
79
|
UPDATE ${t}
|
|
69
80
|
SET is_removed = TRUE
|
|
70
81
|
WHERE name = ? AND (key1 = ? OR key1 IS NULL) AND (key2 = ? OR key2 IS NULL)
|
|
71
|
-
`;await e.run(i,[r.name,r.key1,r.key2]),console.log("Remove data: ",n,a,t,o)}async function
|
|
82
|
+
`;await e.run(i,[r.name,r.key1,r.key2]),console.log("Remove data: ",n,a,t,o)}async function Vt(e,t,o){let n=`
|
|
72
83
|
INSERT INTO dapp_transaction (checkpoint, digest)
|
|
73
84
|
VALUES (?, ?)
|
|
74
|
-
`;await e.run(n,[t,o]),console.log("Insert transaction: ",t,o)}async function
|
|
85
|
+
`;await e.run(n,[t,o]),console.log("Insert transaction: ",t,o)}async function Ut(e){let t=await e.get(`
|
|
75
86
|
SELECT digest FROM dapp_transaction
|
|
76
87
|
ORDER BY id DESC
|
|
77
88
|
LIMIT 1
|
|
78
|
-
`);return t?t.digest:null}async function
|
|
79
|
-
\u{1F680} Sqlite Started`),console.log(` \u251C\u2500 Project: ${r}`),console.log(` \u251C\u2500 Network: ${t}`),console.log(` \u251C\u2500 Database: ${o}`),console.log(` \u251C\u2500 Schema ID: ${n}`),!n)throw new
|
|
80
|
-
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(
|
|
81
|
-
\u274C Failed to Start Local Node`)),console.error(
|
|
82
|
-
\u{1F514} Stopping Local Node...`)),
|
|
83
|
-
\u274C Failed to Start Local Node`)),console.error(
|
|
89
|
+
`);return t?t.digest:null}async function ve(e,t,o,n){let r=`${process.cwd()}/contracts/${e.name}`;if(n=n||await R(r,t),console.log(`
|
|
90
|
+
\u{1F680} Sqlite Started`),console.log(` \u251C\u2500 Project: ${r}`),console.log(` \u251C\u2500 Network: ${t}`),console.log(` \u251C\u2500 Database: ${o}`),console.log(` \u251C\u2500 Schema ID: ${n}`),!n)throw new m("Schema ID not found. Please provide a schema ID with the --schemaId flag.");let i=new Dt({url:It(t)});if(o==="sqlite")for(E=await Ot(e.name);;){await D(2e3);let s=await Ut(E),d=(await i.queryTransactionBlocks({filter:{ChangedObject:n},order:"ascending",cursor:s,options:{showEvents:!0}})).data;for(let c of d)if(await Vt(E,c.checkpoint?.toString(),c.digest),c.events)for(let p of c.events)p.parsedJson.hasOwnProperty("value")?await Ft(E,e.name,c.checkpoint?.toString(),c.digest,p.parsedJson):await Nt(E,e.name,c.checkpoint?.toString(),c.digest,p.parsedJson)}else throw new m(`Database "${o}" not supported. Supported databases: sqlite`)}process.on("SIGINT",async()=>{await E.close(),console.log(Rt.green("\u2705 Sqlite Stopped")),process.exit()});import{Dubhe as xe}from"@0xobelisk/sui-client";function Yt(){try{let e=process.platform==="win32"?'tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH':'pgrep -f "sui start"',t=qt(e).toString().trim();return process.platform==="win32"?t.toLowerCase().includes("sui.exe"):t.length>0}catch{return!1}}async function Lt(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let a=new xe({secretKey:t}).getSigner();ke("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${a.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${a.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."))}async function _e(e){if(Yt()){console.log(_.yellow(`
|
|
91
|
+
\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}U(),console.log("\u{1F680} Starting Local Node...");try{let t=ke("sui",["start","--with-faucet","--force-regenesis"],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore",detached:!0});t.on("error",a=>{console.error(_.red(`
|
|
92
|
+
\u274C Failed to Start Local Node`)),console.error(_.red(` \u2514\u2500 Error: ${a.message}`))}),await D(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 Lt(),await D(2e3);let o=w("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c");if(o===!1)throw new m("Please check your privateKey.");console.log(_.green("\u{1F389} Local environment is ready!"));let n=new xe({secretKey:o,networkType:"localnet"});await ge(e,n,"localnet"),process.on("SIGINT",()=>{console.log(_.yellow(`
|
|
93
|
+
\u{1F514} Stopping Local Node...`)),t&&(t.kill(),console.log(_.green("\u2705 Local Node Stopped"))),process.exit()})}catch(t){console.error(_.red(`
|
|
94
|
+
\u274C Failed to Start Local Node`)),console.error(_.red(` \u2514\u2500 Error: ${t.message}`)),process.exit(1)}}import{loadConfig as Bt}from"@0xobelisk/sui-common";var Ht={command:"node",describe:"Manage local Sui node",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Path to the configuration file"}})},async handler({"config-path":e}){try{let t=await Bt(e);await X(t,"localnet"),await _e(t)}catch(t){console.error("Error executing command:",t),process.exit(1)}}},Ee=Ht;import{Dubhe as Jt}from"@0xobelisk/sui-client";import{requestSuiFromFaucetV0 as zt,getFaucetHost as Gt}from"@mysten/sui/faucet";import{SuiClient as Wt,getFullnodeUrl as Xt}from"@mysten/sui/client";var Zt={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="";if(t===void 0){let i=process.env.PRIVATE_KEY;if(!i)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
84
95
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
85
|
-
in your contracts directory to use the default sui private key.`);let s=
|
|
86
|
-
\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..."),await
|
|
96
|
+
in your contracts directory to use the default sui private key.`);let s=w(i);if(s===!1)throw new m("Please check your PRIVATE_KEY.");o=new Jt({secretKey:s}).getAddress()}else o=t;console.log(`
|
|
97
|
+
\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..."),await zt({host:Gt(e),recipient:o}),console.log(" \u2514\u2500 Checking balance...");let n=new Wt({url:Xt(e)}),a={owner:o},r=await n.getBalance(a);console.log(`
|
|
87
98
|
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(r.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
|
|
88
99
|
\u2705 Faucet Operation Complete
|
|
89
|
-
`),process.exit(0)}},
|
|
100
|
+
`),process.exit(0)}},Se=Zt;import{schemaGen as Qt,loadConfig as eo}from"@0xobelisk/sui-common";import to from"chalk";var oo={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 eo(e);await Qt(o,void 0,t),process.exit(0)}catch(o){console.log(to.red("Schemagen failed!")),console.error(o.message)}}},Ce=oo;import{loadConfig as no}from"@0xobelisk/sui-common";var ro={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 no(t);await fe(n,e,o)}catch(n){x(n),process.exit(1)}process.exit(0)}},$e=ro;import{Dubhe as ao}from"@0xobelisk/sui-client";import{Transaction as so,UpgradePolicy as io}from"@mysten/sui/transactions";import{getFullnodeUrl as co,SuiClient as lo}from"@mysten/sui/client";import{execSync as po}from"child_process";import H from"chalk";import*as A from"fs";import*as Ie from"path";function mo(e,t){let o=`${e}/sources/codegen/schema.move`,n=A.readFileSync(o,"utf-8"),a=new RegExp("public fun migrate\\(_schema: &mut Schema, _cap: &UpgradeCap, _ctx: &mut TxContext\\) {[^}]*}"),r=`
|
|
90
101
|
public fun migrate(_schema: &mut Schema, _cap: &UpgradeCap, _ctx: &mut TxContext) {
|
|
91
102
|
${t.map(s=>{let l="";return s.fields.includes("StorageValue")?l=`storage_value::new(b"${s.schemaName}", _ctx)`:s.fields.includes("StorageMap")?l=`storage_map::new(b"${s.schemaName}", _ctx)`:s.fields.includes("StorageDoubleMap")&&(l=`storage_double_map::new(b"${s.schemaName}", _ctx)`),`storage::add_field<${s.fields}>(&mut _schema.id, b"${s.schemaName}", ${l});`}).join("")}
|
|
92
103
|
}
|
|
93
|
-
`,i=n.replace(a,r);
|
|
94
|
-
`),s=i.findIndex(c=>c.trim()===`[env.${t}]`);if(s===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let l=-1,d="";for(let c=s+1;c<i.length;c++){let
|
|
95
|
-
`);
|
|
104
|
+
`,i=n.replace(a,r);A.writeFileSync(o,i,"utf-8")}function J(e,t,o,n){let a=Ie.resolve(e),i=A.readFileSync(a,"utf-8").split(`
|
|
105
|
+
`),s=i.findIndex(c=>c.trim()===`[env.${t}]`);if(s===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let l=-1,d="";for(let c=s+1;c<i.length;c++){let p=i[c].trim();if(p.startsWith("["))break;if(p.startsWith(o)){l=c,d=p.split("=")[1].trim().replace(/"/g,"");break}}if(l!==-1){i[l]=`${o} = "${n}"`;let c=i.join(`
|
|
106
|
+
`);A.writeFileSync(a,c,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return d}async function De(e,t,o){await O(o);let n=process.cwd(),a=`${n}/contracts/${t}`,r=process.env.PRIVATE_KEY;if(!r)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
96
107
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
97
|
-
in your contracts directory to use the default sui private key.`);let i=
|
|
98
|
-
\u{1F680} Starting Migration for ${
|
|
99
|
-
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",
|
|
100
|
-
`)));let o=process.cwd(),n;if(e){let s=new
|
|
108
|
+
in your contracts directory to use the default sui private key.`);let i=w(r);if(i===!1)throw new m("Please check your privateKey.");let l=new ao({secretKey:i}).getSigner(),d=new lo({url:co(o)}),c=Number(await re(a,o)),p=await T(a,o),u=await ae(a,o),h=await R(a,o),k=J(`${a}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),f=[],C=await ne(a,o);Object.entries(e.schemas).forEach(([y,g])=>{C.hasOwnProperty(y)||f.push({schemaName:y,fields:g})}),f.forEach(y=>{console.log(`
|
|
109
|
+
\u{1F680} Starting Migration for ${y.schemaName}...`),console.log("\u{1F4CB} Migration Fields:",y.fields)}),mo(a,f);try{let y,g,ee;try{let{modules:P,dependencies:We,digest:Xe}=JSON.parse(po(`sui move build --dump-bytecode-as-base64 --path ${n}/contracts/${t}`,{encoding:"utf-8"}));y=P,g=We,ee=Xe}catch(P){throw new q(P.stdout)}console.log(`
|
|
110
|
+
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",p),console.log("\u{1F4CB} UpgradeCap Object Id:",u),console.log("\u{1F4CB} OldVersion:",c);let I=new so,ze=I.moveCall({target:"0x2::package::authorize_upgrade",arguments:[I.object(u),I.pure.u8(io.COMPATIBLE),I.pure.vector("u8",ee)]}),Ge=I.upgrade({modules:y,dependencies:g,package:p,ticket:ze});I.moveCall({target:"0x2::package::commit_upgrade",arguments:[I.object(u),Ge]});let te=await d.signAndExecuteTransaction({signer:l,transaction:I,options:{showObjectChanges:!0}}),z="";te.objectChanges.map(P=>{P.type==="published"&&(console.log(H.blue(`${t} PackageId: ${P.packageId}`)),console.log(H.blue(`${t} Version: ${c+1}`)),z=P.packageId)}),J(`${a}/Move.lock`,o,"original-published-id",k),J(`${a}/Move.lock`,o,"latest-published-id",z),J(`${a}/Move.lock`,o,"published-version",c+1+""),console.log(H.green(`Upgrade Transaction Digest: ${te.digest}`)),L(t,o,z,h,u,c+1,e.schemas)}catch(y){console.log(H.red("Upgrade failed!")),console.error(y.message)}}import{loadConfig as uo}from"@0xobelisk/sui-common";var go={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 uo(t);await De(o,o.name,e)}catch(o){x(o),process.exit(1)}process.exit(0)}},Pe=go;import{execSync as fo}from"child_process";import{loadConfig as ho}from"@0xobelisk/sui-common";var yo={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"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await ho(e),i=`sui move test --path ${`${process.cwd()}/contracts/${n.name}`} ${t?` --test ${t}`:""} ${o?` --gas-limit ${o}`:""}`;fo(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Te=yo;import{execSync as bo}from"child_process";import wo from"chalk";import{loadConfig as vo}from"@0xobelisk/sui-common";import{writeFileSync as ko}from"fs";var xo={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 vo(e),r=`${process.cwd()}/contracts/${n.name}`;await O(t);let i=j(n.dependencies,n.name,t);ko(`${r}/Move.toml`,i,{encoding:"utf-8"});let s=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,l=bo(s,{encoding:"utf-8"});console.log(l)}catch(n){console.error(wo.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Re=xo;var _o={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){U()}},Oe=_o;import{Dubhe as Q}from"@0xobelisk/sui-client";import*as b from"fs";import S from"chalk";async function Ae(e=!1,t){t&&(console.log(S.blue("Note: The generated account will be stored in the .env file and the TypeScript file specified by the --output-ts-path option.")),console.log(S.yellow(`Warning: Do not expose the key file. It is intended for local testing only.
|
|
111
|
+
`)));let o=process.cwd(),n;if(e){let s=new Q().getSigner();if(n=s.getSecretKey(),b.writeFileSync(`${o}/.env`,`PRIVATE_KEY=${n}`),console.log(S.green(`File created at: ${o}/.env`)),t){let l=t.substring(0,t.lastIndexOf("/"));b.existsSync(l)||b.mkdirSync(l,{recursive:!0}),b.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
101
112
|
export const ACCOUNT = '${s.toSuiAddress()}';
|
|
102
113
|
`),console.log(S.green(`File created at: ${t}
|
|
103
|
-
`))}console.log(S.blue(`Force generate new Account: ${s.toSuiAddress()}`));return}try{let s=
|
|
114
|
+
`))}console.log(S.blue(`Force generate new Account: ${s.toSuiAddress()}`));return}try{let s=b.readFileSync(`${o}/.env`,"utf8").match(/PRIVATE_KEY=(.+)/);if(s&&s[1]){n=s[1];let d=new Q({secretKey:n}).getSigner();if(t){let c=t.substring(0,t.lastIndexOf("/"));b.existsSync(c)||b.mkdirSync(c,{recursive:!0}),b.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
104
115
|
export const ACCOUNT = '${d.toSuiAddress()}';
|
|
105
116
|
`),console.log(S.green(`File created at: ${t}
|
|
106
|
-
`))}console.log(S.blue(`Using existing Account: ${d.toSuiAddress()}`));return}}catch{}let r=new
|
|
117
|
+
`))}console.log(S.blue(`Using existing Account: ${d.toSuiAddress()}`));return}}catch{}let r=new Q().getSigner();if(n=r.getSecretKey(),b.writeFileSync(`${o}/.env`,`PRIVATE_KEY=${n}`),console.log(S.green(`File created at: ${o}/.env`)),t){let i=t.substring(0,t.lastIndexOf("/"));b.existsSync(i)||b.mkdirSync(i,{recursive:!0}),b.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
107
118
|
export const ACCOUNT = '${r.toSuiAddress()}';
|
|
108
119
|
`),console.log(S.green(`File created at: ${t}
|
|
109
|
-
`))}console.log(S.blue(`Generate new Account: ${r.toSuiAddress()}`))}var
|
|
120
|
+
`))}console.log(S.blue(`Generate new Account: ${r.toSuiAddress()}`))}var Eo={command:"generate-key",describe:"Generate a new account key pair and save it to a .env file, with an option to output to a TypeScript file.",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new key pair"},"output-ts-path":{type:"string",desc:"Specify the path to output the TypeScript file containing the key pair (e.g., ./src/config/key.ts)"}},async handler({force:e,"output-ts-path":t}){try{await Ae(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Me=Eo;import{Dubhe as So}from"@0xobelisk/sui-client";import Co from"chalk";import $o from"dotenv";$o.config();async function Fe(e){try{let t=process.env.PRIVATE_KEY;if(!t)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
110
121
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
111
|
-
in your contracts directory to use the default sui private key.`);if(
|
|
122
|
+
in your contracts directory to use the default sui private key.`);if(w(t)===!1)throw new m("Please check your privateKey.");let a=await new So({secretKey:process.env.PRIVATE_KEY,networkType:e}).getBalance(),r=Number(a.totalBalance)/1e9;if(r===0)throw new m("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(Co.green(`Current account balance: ${r.toFixed(4)} SUI`))}catch(t){throw new m("Failed to check balance: "+t)}}var Io={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 Fe(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ne=Io;import*as Ke from"fs/promises";import{mkdirSync as Do,writeFileSync as Po}from"fs";import{dirname as To}from"path";async function Ro(e,t){try{let o=await Ke.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}`)}}function Oo(e,t,o,n){let a=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
112
123
|
|
|
113
124
|
export const NETWORK: NetworkType = '${e}';
|
|
114
125
|
export const PACKAGE_ID = '${t}'
|
|
115
126
|
export const SCHEMA_ID = '${o}'
|
|
116
|
-
`;
|
|
117
|
-
Watch stopped.`),process.exit()})}},
|
|
127
|
+
`;Ao(a,n,"storeConfig")}async function Ao(e,t,o){Do(To(t),{recursive:!0}),Po(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function je(e,t,o){let a=`${process.cwd()}/contracts/${e.name}`,r=await Ro(a,t);Oo(r.network,r.packageId,r.schemaId,o)}import{loadConfig as Mo}from"@0xobelisk/sui-common";var Fo={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 Mo(e);await je(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Ve=Fo;import{loadConfig as No}from"@0xobelisk/sui-common";var Ko={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":a,"metadata-path":r,params:i}){try{let s=await No(t);await be({dubheConfig:s,schema:o,objectId:n,network:e,packageId:a,metadataFilePath:r,params:i})}catch(s){x(s),process.exit(1)}process.exit(0)}},Ue=Ko;import{loadConfig as jo}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":a,"metadata-path":r,params:i}){try{let s=await jo(t);await we({dubheConfig:s,moduleName:o,funcName:n,network:e,packageId:a,metadataFilePath:r,params:i})}catch(s){x(s),process.exit(1)}process.exit(0)}},qe=Vo;import{loadConfig as Uo}from"@0xobelisk/sui-common";var qo={command:"indexer",describe:"Dubhe indexer",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)",default:"localnet"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},schemaId:{type:"string",desc:"Schema ID"},db:{type:"string",choices:["sqlite","postgres"],desc:"Optional gas budget for the transaction",default:"sqlite"}})},async handler({network:e,"config-path":t,db:o,schemaId:n}){try{let a=await Uo(t);await ve(a,e,o,n)}catch(a){x(a),process.exit(1)}process.exit(0)}},Ye=qo;import Yo from"chokidar";import{exec as Lo}from"child_process";var Bo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{Lo("pnpm dubhe schemagen",(n,a,r)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(r){console.error(`schemagen stderr: ${r}`);return}console.log(`schemagen stdout: ${a}`)})},o=Yo.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(`
|
|
128
|
+
Watch stopped.`),process.exit()})}},Le=Bo;var Be=[Ee,$e,qe,Ue,Se,Ce,Pe,Te,Re,Oe,Me,Ne,Ve,Ye,Le,le];import*as Je from"dotenv";import He from"chalk";Je.config();Ho(Jo(process.argv)).scriptName("dubhe").command(Be).strict().fail((e,t)=>{console.error(He.red(e)),e.includes("Missing required argument")&&console.log(He.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),x(t),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
|
|
118
129
|
//# sourceMappingURL=dubhe.js.map
|