@0xobelisk/sui-cli 1.0.3 → 1.0.5
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 +57 -55
- package/dist/dubhe.js.map +1 -1
- package/package.json +3 -3
- package/src/commands/call.ts +90 -0
- package/src/commands/index.ts +2 -0
- package/src/commands/query.ts +10 -9
- package/src/commands/test.ts +8 -4
- package/src/utils/callHandler.ts +166 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/queryStorage.ts +7 -7
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 yo}from"yargs/helpers";import{execSync as ht,spawn as me}from"child_process";import k from"chalk";import Ne from"chalk";function N(){console.log(Ne.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,75 +10,77 @@ Welcome to Dubhe
|
|
|
10
10
|
\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
|
|
11
11
|
\\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
|
|
12
12
|
|
|
13
|
-
`))}import{Dubhe as
|
|
13
|
+
`))}import{Dubhe as We}from"@0xobelisk/sui-client";import{Transaction as J}from"@mysten/sui/transactions";import{getFullnodeUrl as Ze,SuiClient as Qe}from"@mysten/sui/client";import{execSync as Xe}from"child_process";import y from"chalk";import T from"chalk";import{ZodError as Ve}from"zod";import{fromZodError as Ue,ValidationError as Ye}from"zod-validation-error";var H=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},m=class extends Error{name="DubheCliError"},V=class extends Error{name="UpgradeError"},U=class extends Error{name="FsIibError"};function E(e){if(e instanceof Ye)console.log(T.redBright(e.message));else if(e instanceof Ve){let t=Ue(e,{prefixSeparator:`
|
|
14
14
|
- `,issueSeparator:`
|
|
15
|
-
- `});console.log(
|
|
16
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
17
|
-
\u274C Process exited with code: ${
|
|
18
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
19
|
-
`),
|
|
20
|
-
[env.${
|
|
21
|
-
chain-id = "${
|
|
22
|
-
original-published-id = "${
|
|
23
|
-
latest-published-id = "${
|
|
24
|
-
published-version = "${
|
|
25
|
-
`,
|
|
26
|
-
`)+u;
|
|
27
|
-
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${
|
|
28
|
-
\u{1F4E6} Building Contract...`);let[l
|
|
29
|
-
\u{1F504} Publishing Contract...`);let u=new J;s&&u.setGasBudget(s);let[
|
|
30
|
-
\u26A1 Executing Deploy Hook...`),await
|
|
31
|
-
\u{1F4CB} Created Schemas:`),
|
|
15
|
+
- `});console.log(T.redBright(t.message))}else e instanceof H?(console.log(T.red(e.message)),console.log(""),console.log(T.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof m?console.log(T.red(e)):console.log(e)}import*as X from"fs/promises";import{mkdirSync as qe,writeFileSync as Be}from"fs";import{dirname as Le}from"path";import{SUI_PRIVATE_KEY_PREFIX as ze}from"@mysten/sui/cryptography";import*as Y from"fs";import O from"chalk";import{spawn as He}from"child_process";function _(e){if(e.startsWith(ze))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 K(e,t){try{let o=await X.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch{throw new U("Fs read deployment file failed.")}}async function ee(e,t){return(await K(e,t)).schemas}async function te(e,t){return(await K(e,t)).version}async function F(e,t){return(await K(e,t)).packageId}async function oe(e,t,o){let r=(await K(e,t)).schemas.find(s=>s.name.toLowerCase().endsWith(`::${o.toLowerCase()}_schema::${o}`));if(!r?.objectId)throw new Error(`Schema '${o}' not found in deployment history`);return r.objectId}async function ne(e,t){return(await K(e,t)).upgradeCap}function R(e,t,o,n,r,s){let a={projectName:e,network:t,packageId:o,schemas:s,upgradeCap:n,version:r},i=process.cwd(),c=JSON.stringify(a,null,2);Je(c,`${i}/contracts/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function Je(e,t,o){qe(Le(t),{recursive:!0}),Be(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Ge(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.0.0" }';default:throw new Error(`Unsupported network: ${e}`)}}function q(e,t){let o=Y.readFileSync(e,"utf-8"),n=Ge(t),r=o.replace(/Dubhe = \{.*\}/,n);Y.writeFileSync(e,r,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function M(e){try{return new Promise((t,o)=>{let n=He("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});n.stdout.on("data",r=>{console.log(O.green(`${r.toString()}`))}),n.on("error",r=>{console.error(O.red(`
|
|
16
|
+
\u274C Failed to Switch Env`)),console.error(O.red(` Error: ${r.message}`)),o(r)}),n.on("exit",r=>{r!==0?(console.error(O.red(`
|
|
17
|
+
\u274C Process exited with code: ${r}`)),o(new Error(`Process exited with code: ${r}`))):t()})})}catch(t){console.error(O.red(`
|
|
18
|
+
\u274C Failed to Switch Env`)),console.error(O.red(` \u2514\u2500 Error: ${t}`))}}var j=e=>new Promise(t=>setTimeout(t,e));import*as I from"fs";import*as re from"path";async function se(e,t){if(!I.existsSync(e))return;let o=I.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),r=o.replace(n,"");I.writeFileSync(e,r,"utf-8")}function ae(e,t,o,n,r){let s=re.resolve(e),a=I.readFileSync(s,"utf-8"),i=a.split(`
|
|
19
|
+
`),c=i.findIndex(g=>g.trim()===`[env.${t}]`),l={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(c===-1)if(o==="publish")l.originalPublishedId=r,l.latestPublishedId=r,l.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let g=c+1;g<i.length;g++){let b=i[g].trim();if(b.startsWith("["))break;let[h,v]=b.split("=").map(d=>d.trim().replace(/"/g,""));switch(h){case"original-published-id":l.originalPublishedId=v;break;case"latest-published-id":l.latestPublishedId=v;break;case"published-version":l.publishedVersion=parseInt(v,10);break}}o==="publish"?(l.originalPublishedId=r,l.latestPublishedId=r,l.publishedVersion=1):o==="upgrade"&&(l.latestPublishedId=r,l.publishedVersion+=1)}let u=`
|
|
20
|
+
[env.${t}]
|
|
21
|
+
chain-id = "${l.chainId}"
|
|
22
|
+
original-published-id = "${l.originalPublishedId}"
|
|
23
|
+
latest-published-id = "${l.latestPublishedId}"
|
|
24
|
+
published-version = "${l.publishedVersion}"
|
|
25
|
+
`,f=c===-1?a+u:i.slice(0,c).join(`
|
|
26
|
+
`)+u;I.writeFileSync(s,f,"utf-8")}function et(e){return e.split("_").map((t,o)=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function tt(e){let t=e.split("::");return t.length>0?t[t.length-1]:""}function ie(e){let t,o;try{let n=JSON.parse(Xe(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies,console.log(" \u2514\u2500 Build successful")}catch(n){console.error(y.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function ot(e,t,o,n,r,s){let a=await e.getChainIdentifier();await se(`${r}/Move.lock`,n),console.log(`
|
|
27
|
+
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${r}`),console.log(` \u251C\u2500 Network: ${n}`),console.log(` \u251C\u2500 ChainId: ${a}`),console.log(" \u251C\u2500 Validating Environment...");let i=t.getKeypair();console.log(` \u2514\u2500 Account: ${i.toSuiAddress()}`),console.log(`
|
|
28
|
+
\u{1F4E6} Building Contract...`);let[c,l]=ie(r);console.log(`
|
|
29
|
+
\u{1F504} Publishing Contract...`);let u=new J;s&&u.setGasBudget(s);let[f]=u.publish({modules:c,dependencies:l});u.transferObjects([f],i.toSuiAddress());let g;try{g=await e.signAndExecuteTransaction({signer:i,transaction:u,options:{showObjectChanges:!0}})}catch(p){console.error(y.red(" \u2514\u2500 Publication failed")),console.error(p.message),process.exit(1)}g.effects?.status.status==="failure"&&(console.log(y.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let b=1,h="",v=[],d="";g.objectChanges.map(p=>{p.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${p.packageId}`),h=p.packageId),p.type==="created"&&p.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${p.objectId}`),d=p.objectId)}),console.log(` \u2514\u2500 Transaction: ${g.digest}`),ae(`${r}/Move.lock`,n,"publish",a,h),console.log(`
|
|
30
|
+
\u26A1 Executing Deploy Hook...`),await j(5e3);let x=new J;x.moveCall({target:`${h}::deploy_hook::run`,arguments:[x.object("0x6")]});let C;try{C=await e.signAndExecuteTransaction({signer:i,transaction:x,options:{showEffects:!0,showObjectChanges:!0}})}catch(p){console.error(y.red(" \u2514\u2500 Deploy hook execution failed")),console.error(p.message),process.exit(1)}C.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${C.digest}`),console.log(`
|
|
31
|
+
\u{1F4CB} Created Schemas:`),C.objectChanges?.map(p=>{if(p.type==="created"&&p.objectType.includes("_schema")&&!p.objectType.includes("dynamic_field")){console.log(` \u251C\u2500 ${p.objectType}`),console.log(` \u2514\u2500 ID: ${p.objectId}`);let P={};for(let $ in o.schemas)et($)===tt(p.objectType)&&(P=o.schemas[$].structure);v.push({name:p.objectType,objectId:p.objectId,structure:P})}}),R(o.name,n,h,d,b,v),console.log(`
|
|
32
32
|
\u2705 Contract Publication Complete
|
|
33
|
-
`)):(console.log(
|
|
34
|
-
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(
|
|
35
|
-
\u2757 Framework Deployment Skipped`));return}let s=await
|
|
36
|
-
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${
|
|
37
|
-
\u{1F4E6} Building Contract...`);let[i,
|
|
38
|
-
\u{1F504} Publishing Contract...`);let
|
|
39
|
-
\u2705 Dubhe Framework deployed successfully`))}async function
|
|
33
|
+
`)):(console.log(y.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(y.yellow(" Please republish or manually call deploy_hook::run")),console.log(y.yellow(" Please check the transaction digest:")),console.log(y.yellow(` ${C.digest}`)),process.exit(1))}async function nt(e){return I.existsSync(e)?!0:(console.log(y.yellow(`
|
|
34
|
+
\u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(y.yellow(" \u251C\u2500 Expected Path:"),e),console.log(y.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(y.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe-framework")),console.log(y.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe-framework contracts/dubhe-framework")),console.log(y.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe-framework")),console.log(y.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function rt(e,t,o){let r=`${process.cwd()}/contracts/dubhe-framework`;if(!await nt(r)){console.log(y.yellow(`
|
|
35
|
+
\u2757 Framework Deployment Skipped`));return}let s=await e.getChainIdentifier();await se(`${r}/Move.lock`,o),console.log(`
|
|
36
|
+
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${r}`),console.log(` \u251C\u2500 Network: ${o}`);let a=t.getKeypair();console.log(` \u2514\u2500 Account: ${a.toSuiAddress()}`),console.log(`
|
|
37
|
+
\u{1F4E6} Building Contract...`);let[i,c]=ie(r);console.log(`
|
|
38
|
+
\u{1F504} Publishing Contract...`);let l=new J,[u]=l.publish({modules:i,dependencies:c});l.transferObjects([u],a.toSuiAddress());let f;try{f=await e.signAndExecuteTransaction({signer:a,transaction:l,options:{showObjectChanges:!0}})}catch(d){console.error(y.red(" \u2514\u2500 Publication failed")),console.error(d.message),process.exit(1)}f.effects?.status.status==="failure"&&(console.log(y.red(" \u2514\u2500 Publication failed")),process.exit(1));let g=1,b="",h=[],v="";f.objectChanges.map(d=>{d.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${d.packageId}`),b=d.packageId),d.type==="created"&&d.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${d.objectId}`),v=d.objectId)}),console.log(` \u2514\u2500 Transaction: ${f.digest}`),ae(`${r}/Move.lock`,o,"publish",s,b),R("dubhe-framework",o,b,v,g,h),console.log(y.green(`
|
|
39
|
+
\u2705 Dubhe Framework deployed successfully`))}async function ce(e,t,o){await M(t);let n=process.env.PRIVATE_KEY;if(!n)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
40
40
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
41
|
-
in your contracts directory to use the default sui private key.`);let
|
|
41
|
+
in your contracts directory to use the default sui private key.`);let r=_(n);if(r===!1)throw new m("Please check your privateKey.");let s=new We({secretKey:r}),a=new Qe({url:Ze(t)});t==="localnet"&&await rt(a,s,t);let c=`${process.cwd()}/contracts/${e.name}`;q(`${c}/Move.toml`,t),await ot(a,s,e,t,c,o)}import{Dubhe as st,loadMetadata as at}from"@0xobelisk/sui-client";import*as le from"fs";import*as de from"path";function it(e,t){switch(e.split("<")[0].trim()){case"StorageValue":return t.length===0;case"StorageMap":return t.length===1;case"StorageDoubleMap":return t.length===2;default:return!1}}function ct(e){switch(e.split("<")[0].trim()){case"StorageValue":return 0;case"StorageMap":return 1;case"StorageDoubleMap":return 2;default:return 0}}async function pe({dubheConfig:e,schema:t,field:o,params:n,network:r,objectId:s,packageId:a,metadataFilePath:i}){let c=process.env.PRIVATE_KEY;if(!c)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
42
42
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
43
|
-
in your contracts directory to use the default sui private key.`);let
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
\
|
|
47
|
-
\u274C Failed to Start Local Node`)),console.error(k.red(` \u2514\u2500 Error: ${
|
|
43
|
+
in your contracts directory to use the default sui private key.`);let l=_(c);if(l===!1)throw new m("Please check your privateKey.");let f=`${process.cwd()}/contracts/${e.name}`;a=a||await F(f,r),s=s||await oe(f,r,t);let g;if(i?g=await G(i):g=await at(r,a),!g)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(", ")}`);if(!e.schemas[t][o])throw new m(`Field "${o}" not found in schema "${t}". Available fields: ${Object.keys(e.schemas[t]).join(", ")}`);let b=e.schemas[t][o],h=n||[];if(!it(b,h))throw new Error(`Invalid params count for ${b}. Expected: ${ct(b)}, Got: ${h.length}`);let d=await new st({secretKey:l,networkType:r,packageId:a,metadata:g}).state({schema:t,field:o,objectId:s,storageType:b,params:h});console.log(d)}async function G(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 lt,loadMetadata as dt,Transaction as pt}from"@0xobelisk/sui-client";var ut=["u8","u16","u32","u64","u128","u256","bool","id","string","address","object"];function mt(e){try{e.forEach(t=>{let[o,n]=t.split(":");if(!ut.includes(o))throw new Error(`Invalid param type: ${o}`)})}catch(t){throw new Error(`Invalid params: ${t}`)}}function gt(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 ft(e,t){return t.map(o=>gt(e,o))}async function ue({dubheConfig:e,moduleName:t,funcName:o,params:n,network:r,packageId:s,metadataFilePath:a}){let i=process.env.PRIVATE_KEY;if(!i)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
44
|
+
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
45
|
+
in your contracts directory to use the default sui private key.`);let c=_(i);if(c===!1)throw new m("Please check your privateKey.");let u=`${process.cwd()}/contracts/${e.name}`;s=s||await F(u,r);let f;if(a?f=await G(a):f=await dt(r,s),!f)throw new m("Metadata file not found. Please provide a metadata file path or set the packageId.");let g=n||[];mt(g);let b=new lt({secretKey:c,networkType:r,packageId:s,metadata:f}),h=new pt,v=ft(h,g),d=await b.tx[t][o]({tx:h,params:v});console.log(d)}import{Dubhe as yt}from"@0xobelisk/sui-client";function bt(){try{let e=process.platform==="win32"?'tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH':'pgrep -f "sui start"',t=ht(e).toString().trim();return process.platform==="win32"?t.toLowerCase().includes("sui.exe"):t.length>0}catch{return!1}}async function wt(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let r=new yt({secretKey:t}).getKeypair();me("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${r.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${r.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(k.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(k.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}async function ge(){if(bt()){console.log(k.yellow(`
|
|
46
|
+
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(k.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(k.yellow(" \u2514\u2500 Please stop the existing process first"));return}N(),console.log("\u{1F680} Starting Local Node...");try{let e=me("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(k.red(`
|
|
47
|
+
\u274C Failed to Start Local Node`)),console.error(k.red(` \u2514\u2500 Error: ${o.message}`))}),await j(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await wt(),await j(2e3),_("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new m("Please check your privateKey.");console.log(k.green("\u{1F389} Local environment is ready!")),process.on("SIGINT",()=>{console.log(k.yellow(`
|
|
48
|
+
\u{1F514} Stopping Local Node...`)),e&&(e.kill(),console.log(k.green("\u2705 Local Node Stopped"))),process.exit()})}catch(e){console.error(k.red(`
|
|
49
|
+
\u274C Failed to Start Local Node`)),console.error(k.red(` \u2514\u2500 Error: ${e.message}`)),process.exit(1)}}var vt={command:"node",describe:"Manage local Sui node",builder(e){return e},async handler(){try{await ge()}catch(e){console.error("Error executing command:",e),process.exit(1)}}},fe=vt;import{Dubhe as _t}from"@0xobelisk/sui-client";import{requestSuiFromFaucetV0 as Ct,getFaucetHost as kt}from"@mysten/sui/faucet";import{SuiClient as xt,getFullnodeUrl as $t}from"@mysten/sui/client";var Et={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 a=process.env.PRIVATE_KEY;if(!a)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
48
50
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
49
|
-
in your contracts directory to use the default sui private key.`);let i=
|
|
50
|
-
\u{1F30A} Starting Faucet Operation...`),console.log(` \u251C\u2500 Network: ${
|
|
51
|
+
in your contracts directory to use the default sui private key.`);let i=_(a);if(i===!1)throw new m("Please check your PRIVATE_KEY.");o=new _t({secretKey:i}).getKeypair().toSuiAddress()}else o=t;console.log(`
|
|
52
|
+
\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 Ct({host:kt(e),recipient:o}),console.log(" \u2514\u2500 Checking balance...");let n=new xt({url:$t(e)}),r={owner:o},s=await n.getBalance(r);console.log(`
|
|
51
53
|
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(s.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
|
|
52
54
|
\u2705 Faucet Operation Complete
|
|
53
|
-
`),process.exit(0)}},
|
|
54
|
-
public fun migrate(${o.schemaName}: &mut ${
|
|
55
|
-
${o.fields.map(
|
|
55
|
+
`),process.exit(0)}},he=Et;import{schemaGen as St,loadConfig as It}from"@0xobelisk/sui-common";import Pt from"chalk";var Dt={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 It(e);await St(o,void 0,t),process.exit(0)}catch(o){console.log(Pt.red("Schemagen failed!")),console.error(o.message)}}},ye=Dt;import{loadConfig as Ot}from"@0xobelisk/sui-common";var Ft={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","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 Ot(t);await ce(n,e,o)}catch(n){E(n),process.exit(1)}process.exit(0)}},be=Ft;import{Dubhe as Mt}from"@0xobelisk/sui-client";import{Transaction as At,UpgradePolicy as Tt}from"@mysten/sui/transactions";import{getFullnodeUrl as Kt,SuiClient as Rt}from"@mysten/sui/client";import{execSync as jt}from"child_process";import B from"chalk";import*as A from"fs";import*as we from"path";function Nt(e,t){t.forEach(o=>{let n=`${e}/sources/codegen/schemas/${o.schemaName}.move`,r=A.readFileSync(n,"utf-8"),s=new RegExp(`public fun migrate\\(_${o.schemaName}: &mut ${W(o.schemaName)}, _cap: &UpgradeCap\\) {[^}]*}`),a=`
|
|
56
|
+
public fun migrate(${o.schemaName}: &mut ${W(o.schemaName)}, _cap: &UpgradeCap) {
|
|
57
|
+
${o.fields.map(c=>{let l="";return c.type.includes("StorageValue")?l="storage_value::new()":c.type.includes("StorageMap")?l="storage_map::new()":c.type.includes("StorageDoubleMap")&&(l="storage_double_map::new()"),`storage_migration::add_field<${c.type}>(&mut ${o.schemaName}.id, b"${c.name}", ${l});`}).join("")}
|
|
56
58
|
}
|
|
57
|
-
`,i=
|
|
58
|
-
`),i=a.findIndex(u=>u.trim()===`[env.${
|
|
59
|
-
`);
|
|
59
|
+
`,i=r.replace(s,a);A.writeFileSync(n,i,"utf-8")})}function W(e){return e.split("_").map((t,o)=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function Vt(e){let t=e.split("::");return t.length>0?t[t.length-1]:""}function L(e,t,o,n){let r=we.resolve(e),a=A.readFileSync(r,"utf-8").split(`
|
|
60
|
+
`),i=a.findIndex(u=>u.trim()===`[env.${t}]`);if(i===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let c=-1,l="";for(let u=i+1;u<a.length;u++){let f=a[u].trim();if(f.startsWith("["))break;if(f.startsWith(o)){c=u,l=f.split("=")[1].trim().replace(/"/g,"");break}}if(c!==-1){a[c]=`${o} = "${n}"`;let u=a.join(`
|
|
61
|
+
`);A.writeFileSync(r,u,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return l}async function ve(e,t,o){await M(o);let n=process.cwd(),r=`${n}/contracts/${t}`,s=process.env.PRIVATE_KEY;if(!s)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
60
62
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
61
|
-
in your contracts directory to use the default sui private key.`);let a=
|
|
62
|
-
\u{1F680} Starting Migration for ${
|
|
63
|
-
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",
|
|
64
|
-
`)));let o=process.cwd(),
|
|
63
|
+
in your contracts directory to use the default sui private key.`);let a=_(s);if(a===!1)throw new m("Please check your privateKey.");let c=new Mt({secretKey:a}).getKeypair(),l=new Rt({url:Kt(o)}),u=Number(await te(r,o)),f=await F(r,o),g=await ne(r,o),b=L(`${r}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),h=[],v=await ee(r,o);for(let d in e.schemas)v.forEach(x=>{if(W(d)==Vt(x.name)){let C={schemaName:"",fields:[]},p=[],P=!1;for(let $ in e.schemas[d].structure)$ in x.structure||(P=!0,p.push({name:$,type:e.schemas[d].structure[$]}),x.structure[$]=e.schemas[d].structure[$]);P&&(C.schemaName=d,C.fields=p,h.push(C))}});h.forEach(d=>{console.log(`
|
|
64
|
+
\u{1F680} Starting Migration for ${d.schemaName}...`),console.log("\u{1F4CB} Migration Fields:",d.fields)}),Nt(r,h);try{let d,x,C;try{let{modules:D,dependencies:Re,digest:je}=JSON.parse(jt(`sui move build --dump-bytecode-as-base64 --path ${n}/contracts/${t}`,{encoding:"utf-8"}));d=D,x=Re,C=je}catch(D){throw new V(D.stdout)}console.log(`
|
|
65
|
+
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",f),console.log("\u{1F4CB} UpgradeCap Object Id:",g),console.log("\u{1F4CB} OldVersion:",u);let p=new At,P=p.moveCall({target:"0x2::package::authorize_upgrade",arguments:[p.object(g),p.pure.u8(Tt.COMPATIBLE),p.pure.vector("u8",C)]}),$=p.upgrade({modules:d,dependencies:x,package:f,ticket:P});p.moveCall({target:"0x2::package::commit_upgrade",arguments:[p.object(g),$]});let Q=await l.signAndExecuteTransaction({signer:c,transaction:p,options:{showObjectChanges:!0}}),z="";Q.objectChanges.map(D=>{D.type==="published"&&(console.log(B.blue(`${t} PackageId: ${D.packageId}`)),console.log(B.blue(`${t} Version: ${u+1}`)),z=D.packageId)}),L(`${r}/Move.lock`,o,"original-published-id",b),L(`${r}/Move.lock`,o,"latest-published-id",z),L(`${r}/Move.lock`,o,"published-version",u+1+""),console.log(B.green(`Upgrade Transaction Digest: ${Q.digest}`)),R(t,o,z,g,u+1,v)}catch(d){console.log(B.red("Upgrade failed!")),console.error(d.message)}}import{loadConfig as Ut}from"@0xobelisk/sui-common";var Yt={command:"upgrade",describe:"Upgrade your move contracts",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","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 Ut(t);await ve(o,o.name,e)}catch(o){E(o),process.exit(1)}process.exit(0)}},_e=Yt;import{execSync as qt}from"child_process";import Bt from"chalk";import{loadConfig as Lt}from"@0xobelisk/sui-common";var zt={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 Lt(e),a=`sui move test --path ${`${process.cwd()}/contracts/${n.name}`} ${t?` --test ${t}`:""} ${o?` --gas-limit ${o}`:""}`;qt(a,{stdio:"inherit",encoding:"utf-8"})}catch(n){console.error(Bt.red("Error executing sui move test:")),console.log(n.stdout),process.exit(0)}}},Ce=zt;import{execSync as Ht}from"child_process";import Jt from"chalk";import{loadConfig as Gt}from"@0xobelisk/sui-common";var Wt={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",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 Gt(e),s=`${process.cwd()}/contracts/${n.name}`;await M(t),q(s+"/Move.toml",t);let a=`sui move build --path ${s} ${o?" --dump-bytecode-as-base64":""}`,i=Ht(a,{encoding:"utf-8"});console.log(i)}catch(n){console.error(Jt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},ke=Wt;var Zt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){N()}},xe=Zt;import{Dubhe as Z}from"@0xobelisk/sui-client";import*as w from"fs";import S from"chalk";async function $e(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.
|
|
66
|
+
`)));let o=process.cwd(),n;if(e){let i=new Z().getKeypair();if(n=i.getSecretKey(),w.writeFileSync(`${o}/.env`,`PRIVATE_KEY=${n}`),console.log(S.green(`File created at: ${o}/.env`)),t){let c=t.substring(0,t.lastIndexOf("/"));w.existsSync(c)||w.mkdirSync(c,{recursive:!0}),w.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
65
67
|
export const ACCOUNT = '${i.toSuiAddress()}';
|
|
66
|
-
`),console.log(S.green(`File created at: ${
|
|
67
|
-
`))}console.log(S.blue(`Force generate new Account: ${i.toSuiAddress()}`));return}try{let i=
|
|
68
|
-
export const ACCOUNT = '${
|
|
69
|
-
`),console.log(S.green(`File created at: ${
|
|
70
|
-
`))}console.log(S.blue(`Using existing Account: ${
|
|
68
|
+
`),console.log(S.green(`File created at: ${t}
|
|
69
|
+
`))}console.log(S.blue(`Force generate new Account: ${i.toSuiAddress()}`));return}try{let i=w.readFileSync(`${o}/.env`,"utf8").match(/PRIVATE_KEY=(.+)/);if(i&&i[1]){n=i[1];let l=new Z({secretKey:n}).getKeypair();if(t){let u=t.substring(0,t.lastIndexOf("/"));w.existsSync(u)||w.mkdirSync(u,{recursive:!0}),w.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
70
|
+
export const ACCOUNT = '${l.toSuiAddress()}';
|
|
71
|
+
`),console.log(S.green(`File created at: ${t}
|
|
72
|
+
`))}console.log(S.blue(`Using existing Account: ${l.toSuiAddress()}`));return}}catch{}let s=new Z().getKeypair();if(n=s.getSecretKey(),w.writeFileSync(`${o}/.env`,`PRIVATE_KEY=${n}`),console.log(S.green(`File created at: ${o}/.env`)),t){let a=t.substring(0,t.lastIndexOf("/"));w.existsSync(a)||w.mkdirSync(a,{recursive:!0}),w.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
71
73
|
export const ACCOUNT = '${s.toSuiAddress()}';
|
|
72
|
-
`),console.log(S.green(`File created at: ${
|
|
73
|
-
`))}console.log(S.blue(`Generate new Account: ${s.toSuiAddress()}`))}var
|
|
74
|
+
`),console.log(S.green(`File created at: ${t}
|
|
75
|
+
`))}console.log(S.blue(`Generate new Account: ${s.toSuiAddress()}`))}var Qt={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 $e(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ee=Qt;import{Dubhe as Xt}from"@0xobelisk/sui-client";import eo from"chalk";import to from"dotenv";to.config();async function Se(e){try{let t=process.env.PRIVATE_KEY;if(!t)throw new m(`Missing PRIVATE_KEY environment variable.
|
|
74
76
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
75
|
-
in your contracts directory to use the default sui private key.`);if(
|
|
77
|
+
in your contracts directory to use the default sui private key.`);if(_(t)===!1)throw new m("Please check your privateKey.");let r=await new Xt({secretKey:process.env.PRIVATE_KEY,networkType:e}).getBalance(),s=Number(r.totalBalance)/1e9;if(s===0)throw new m("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(eo.green(`Current account balance: ${s.toFixed(4)} SUI`))}catch(t){throw new m("Failed to check balance: "+t)}}var oo={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"}},async handler({network:e}){try{await Se(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ie=oo;import*as Pe from"fs/promises";import{mkdirSync as no,writeFileSync as ro}from"fs";import{dirname as so}from"path";async function ao(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 io(e,t,o,n){let r=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
76
78
|
|
|
77
|
-
export const NETWORK: NetworkType = '${
|
|
79
|
+
export const NETWORK: NetworkType = '${e}';
|
|
78
80
|
|
|
79
|
-
export const PACKAGE_ID = '${
|
|
81
|
+
export const PACKAGE_ID = '${t}'
|
|
80
82
|
|
|
81
83
|
${o.map(s=>`export const ${s.name.split("::")[2]}_Object_Id = '${s.objectId}'`).join(`
|
|
82
84
|
`)}
|
|
83
|
-
`;
|
|
85
|
+
`;co(r,n,"storeConfig")}async function co(e,t,o){no(so(t),{recursive:!0}),ro(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function De(e,t,o){let r=`${process.cwd()}/contracts/${e.name}`,s=await ao(r,t);io(s.network,s.packageId,s.schemas,o)}import{loadConfig as lo}from"@0xobelisk/sui-common";var po={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 lo(e);await De(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Oe=po;import{loadConfig as uo}from"@0xobelisk/sui-common";var mo={command:"query",describe:"Query dubhe schema struct state",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)",demandOption:!0},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},schema:{type:"string",desc:"Schema name",demandOption:!0},field:{type:"string",desc:"Field 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,field:n,"object-id":r,"package-id":s,"metadata-path":a,params:i}){try{let c=await uo(t);await pe({dubheConfig:c,schema:o,field:n,objectId:r,network:e,packageId:s,metadataFilePath:a,params:i})}catch(c){E(c),process.exit(1)}process.exit(0)}},Fe=mo;import{loadConfig as go}from"@0xobelisk/sui-common";var fo={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)",demandOption:!0},module:{type:"string",desc:"Module name",demandOption:!0},function:{type:"string",desc:"Function name",demandOption:!0},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"package-id":{type:"string",desc:"Package ID (optional)"},"metadata-path":{type:"string",desc:"Path to metadata JSON file (optional)"},params:{type:"array",desc:"Params for the function",string:!0}},async handler({network:e,"config-path":t,module:o,function:n,"package-id":r,"metadata-path":s,params:a}){try{let i=await go(t);await ue({dubheConfig:i,moduleName:o,funcName:n,network:e,packageId:r,metadataFilePath:s,params:a})}catch(i){E(i),process.exit(1)}process.exit(0)}},Me=fo;var Ae=[fe,be,Me,Fe,he,ye,_e,Ce,ke,xe,Ee,Ie,Oe];import*as Ke from"dotenv";import Te from"chalk";Ke.config();ho(yo(process.argv)).scriptName("dubhe").command(Ae).strict().fail((e,t)=>{console.error(Te.red(e)),e.includes("Missing required argument")&&console.log(Te.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),E(t),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
|
|
84
86
|
//# sourceMappingURL=dubhe.js.map
|