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