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