@0xobelisk/sui-cli 0.5.30 → 0.5.32
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 +60 -40
- package/dist/dubhe.js.map +1 -1
- package/package.json +1 -1
- package/src/commands/checkBalance.ts +35 -0
- package/src/commands/generateKey.ts +35 -0
- package/src/commands/index.ts +7 -1
- package/src/commands/storeConfig.ts +48 -0
- package/src/utils/checkBalance.ts +55 -0
- package/src/utils/errors.ts +31 -31
- package/src/utils/generateAccount.ts +112 -0
- package/src/utils/publishHandler.ts +71 -32
- package/src/utils/storeConfig.ts +79 -0
package/dist/dubhe.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Wt from"yargs";import{hideBin as Zt}from"yargs/helpers";import{execSync as tt,spawn as de}from"child_process";import x from"chalk";import Re from"chalk";function U(){console.log(Re.yellow(`
|
|
3
3
|
Welcome to Dubhe
|
|
4
4
|
--from team@obelisk
|
|
5
5
|
________ ___ ___ ________ ___ ___ _______
|
|
@@ -10,51 +10,71 @@ Welcome to Dubhe
|
|
|
10
10
|
\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
|
|
11
11
|
\\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
|
|
12
12
|
|
|
13
|
-
`))}import{Dubhe as
|
|
13
|
+
`))}import{Dubhe as ze}from"@0xobelisk/sui-client";import{Transaction as W}from"@mysten/sui/transactions";import{getFullnodeUrl as Je,SuiClient as Ge}from"@mysten/sui/client";import{execSync as We}from"child_process";import D from"chalk";import R from"chalk";import{ZodError as Te}from"zod";import{fromZodError as je,ValidationError as Ne}from"zod-validation-error";var G=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},g=class extends Error{name="DubheCliError"},V=class extends Error{name="UpgradeError"},Y=class extends Error{name="FsIibError"};function F(e){if(e instanceof Ne)console.log(R.redBright(e.message));else if(e instanceof Te){let t=je(e,{prefixSeparator:`
|
|
14
14
|
- `,issueSeparator:`
|
|
15
|
-
- `});console.log(
|
|
16
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
17
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
18
|
-
\u274C Process exited with code: ${
|
|
19
|
-
\u274C Failed to Switch Env`)),console.error(
|
|
20
|
-
`),d=
|
|
15
|
+
- `});console.log(R.redBright(t.message))}else e instanceof G?(console.log(R.red(e.message)),console.log(""),console.log(R.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof g?console.log(R.red(e)):console.log(e)}import*as ee from"fs/promises";import{mkdirSync as Ue,writeFileSync as Ve}from"fs";import{dirname as Ye}from"path";import{SUI_PRIVATE_KEY_PREFIX as qe}from"@mysten/sui/cryptography";import*as q from"fs";import E from"chalk";import{spawn as He}from"child_process";function $(e){if(e.startsWith(qe))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 T(e,t){try{let o=await ee.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch{throw new Y("Fs read deployment file failed.")}}async function te(e,t){return(await T(e,t)).schemas}async function oe(e,t){return(await T(e,t)).version}async function ne(e,t){return(await T(e,t)).packageId}async function re(e,t){return(await T(e,t)).upgradeCap}async function H(e,t){return(await T(e,t)).schemaHub}function j(e,t,o,n,r,s,a){let c={projectName:e,network:t,packageId:o,schemas:a,upgradeCap:n,schemaHub:r,version:s},d=process.cwd(),i=JSON.stringify(c,null,2);Be(i,`${d}/contracts/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function Be(e,t,o){Ue(Ye(t),{recursive:!0}),Ve(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function Le(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.0.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 B(e,t){let o=q.readFileSync(e,"utf-8"),n=Le(t),r=o.replace(/Dubhe = \{.*\}/,n);q.writeFileSync(e,r,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function O(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(E.green(`${r.toString()}`))}),n.stderr.on("data",r=>{console.error(E.red(`
|
|
16
|
+
\u274C Failed to Switch Env`)),console.error(E.red(` Error: ${r.toString()}`))}),n.on("error",r=>{console.error(E.red(`
|
|
17
|
+
\u274C Failed to Switch Env`)),console.error(E.red(` Error: ${r.message}`)),o(r)}),n.on("exit",r=>{r!==0?(console.error(E.red(`
|
|
18
|
+
\u274C Process exited with code: ${r}`)),o(new Error(`Process exited with code: ${r}`))):t()})})}catch(t){console.error(E.red(`
|
|
19
|
+
\u274C Failed to Switch Env`)),console.error(E.red(` \u2514\u2500 Error: ${t}`))}}var N=e=>new Promise(t=>setTimeout(t,e));import*as P from"fs";import*as se from"path";async function Ze(e){switch(e){case"localnet":{let t=process.cwd();return await H(`${t}/contracts/dubhe-framework`,e)}case"testnet":return"0x8dbf8d28ac027ba214c9e0951b09f6842843be6cb87242b7d9a326a2677cd47a";default:return"0x8dbf8d28ac027ba214c9e0951b09f6842843be6cb87242b7d9a326a2677cd47a"}}function ae(e,t){if(!P.existsSync(e))return;let o=P.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),r=o.replace(n,"");P.writeFileSync(e,r,"utf-8")}function ie(e,t,o,n,r){let s=se.resolve(e),a=P.readFileSync(s,"utf-8"),c=a.split(`
|
|
20
|
+
`),d=c.findIndex(b=>b.trim()===`[env.${t}]`),i={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(d===-1)if(o==="publish")i.originalPublishedId=r,i.latestPublishedId=r,i.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let b=d+1;b<c.length;b++){let v=c[b].trim();if(v.startsWith("["))break;let[C,w]=v.split("=").map(_=>_.trim().replace(/"/g,""));switch(C){case"original-published-id":i.originalPublishedId=w;break;case"latest-published-id":i.latestPublishedId=w;break;case"published-version":i.publishedVersion=parseInt(w,10);break}}o==="publish"?(i.originalPublishedId=r,i.latestPublishedId=r,i.publishedVersion=1):o==="upgrade"&&(i.latestPublishedId=r,i.publishedVersion+=1)}let u=`
|
|
21
21
|
[env.${t}]
|
|
22
|
-
chain-id = "${
|
|
23
|
-
original-published-id = "${
|
|
24
|
-
latest-published-id = "${
|
|
25
|
-
published-version = "${
|
|
26
|
-
`,
|
|
27
|
-
`)+u;
|
|
28
|
-
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${
|
|
29
|
-
\u{1F4E6} Building Contract...`);let[d,
|
|
30
|
-
\u{1F504} Publishing Contract...`);let u=new
|
|
31
|
-
\u26A1 Executing Deploy Hook...`),await
|
|
32
|
-
\u{1F4CB} Created Schemas:`),
|
|
22
|
+
chain-id = "${i.chainId}"
|
|
23
|
+
original-published-id = "${i.originalPublishedId}"
|
|
24
|
+
latest-published-id = "${i.latestPublishedId}"
|
|
25
|
+
published-version = "${i.publishedVersion}"
|
|
26
|
+
`,y=d===-1?a+u:c.slice(0,d).join(`
|
|
27
|
+
`)+u;P.writeFileSync(s,y,"utf-8")}function Xe(e){return e.split("_").map((t,o)=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function Qe(e){let t=e.split("::");return t.length>0?t[t.length-1]:""}function ce(e){let t,o;try{let n=JSON.parse(We(`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(D.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function et(e,t,o,n,r){let s=await Ze(n);console.log("dappsObjectId",s);let a=await e.getChainIdentifier();ae(`${r}/Move.lock`,n),console.log(`
|
|
28
|
+
\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 c=t.getKeypair();console.log(` \u2514\u2500 Account: ${c.toSuiAddress()}`),console.log(`
|
|
29
|
+
\u{1F4E6} Building Contract...`);let[d,i]=ce(r);console.log(`
|
|
30
|
+
\u{1F504} Publishing Contract...`);let u=new W,[y]=u.publish({modules:d,dependencies:i});u.transferObjects([y],c.toSuiAddress());let b;try{b=await e.signAndExecuteTransaction({signer:c,transaction:u,options:{showObjectChanges:!0}})}catch(p){console.error(D.red(" \u2514\u2500 Publication failed")),console.error(p.message),process.exit(1)}b.effects?.status.status==="failure"&&(console.log(D.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let v=1,C="",w=[],_="",l="";b.objectChanges.map(p=>{p.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${p.packageId}`),C=p.packageId),p.type==="created"&&p.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${p.objectId}`),_=p.objectId),p.type==="created"&&p.objectType.includes("schema_hub")&&(console.log(` \u251C\u2500 Schema Hub: ${p.objectId}`),l=p.objectId)}),console.log(` \u2514\u2500 Transaction: ${b.digest}`),ie(`${r}/Move.lock`,n,"publish",a,C),console.log(`
|
|
31
|
+
\u26A1 Executing Deploy Hook...`),await N(5e3);let m=new W;m.setGasBudget(2e9);let[I]=m.splitCoins(m.gas,["1000000000"]);m.moveCall({target:`${C}::deploy_hook::run`,arguments:[m.object(l),m.object(s),m.object(_),m.object("0x6"),I]});let f;try{f=await e.signAndExecuteTransaction({signer:c,transaction:m,options:{showEffects:!0,showObjectChanges:!0}})}catch(p){console.error(D.red(" \u2514\u2500 Deploy hook execution failed")),console.error(p.message),process.exit(1)}f.effects?.status.status==="success"?(console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${f.digest}`),console.log(`
|
|
32
|
+
\u{1F4CB} Created Schemas:`),f.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 k={};for(let K in o.schemas)Xe(K)===Qe(p.objectType)&&(k=o.schemas[K].structure);w.push({name:p.objectType,objectId:p.objectId,structure:k})}}),j(o.name,n,C,_,l,v,w),console.log(`
|
|
33
33
|
\u2705 Contract Publication Complete
|
|
34
|
-
`)):(console.log(
|
|
35
|
-
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${
|
|
36
|
-
\u{1F4E6} Building Contract...`);let[
|
|
37
|
-
\u{1F504} Publishing Contract...`);let
|
|
34
|
+
`)):(console.log(D.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(D.yellow(" Please republish or manually call deploy_hook::run")))}async function Z(e,t,o){let r=`${process.cwd()}/contracts/dubhe-framework`,s=await e.getChainIdentifier();console.log(` \u2514\u2500 Chain ID: ${s}`),ae(`${r}/Move.lock`,o),console.log(`
|
|
35
|
+
\u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${r}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(` \u251C\u2500 ChainId: ${s}`),console.log(" \u251C\u2500 Validating Environment...");let a=t.getKeypair();console.log(` \u2514\u2500 Account: ${a.toSuiAddress()}`),console.log(`
|
|
36
|
+
\u{1F4E6} Building Contract...`);let[c,d]=ce(r);console.log(`
|
|
37
|
+
\u{1F504} Publishing Contract...`);let i=new W,[u]=i.publish({modules:c,dependencies:d});i.transferObjects([u],a.toSuiAddress());let y;try{y=await e.signAndExecuteTransaction({signer:a,transaction:i,options:{showObjectChanges:!0}})}catch(l){console.error(D.red(" \u2514\u2500 Publication failed")),console.error(l.message),process.exit(1)}y.effects?.status.status==="failure"&&(console.log(D.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let b=1,v="",C=[],w="",_="";y.objectChanges.map(l=>{l.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${l.packageId}`),v=l.packageId),l.type==="created"&&l.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${l.objectId}`),w=l.objectId),l.type==="created"&&l.objectType.includes("dapps")&&(console.log(` \u251C\u2500 Dapps: ${l.objectId}`),_=l.objectId)}),console.log(` \u2514\u2500 Transaction: ${y.digest}`),ie(`${r}/Move.lock`,o,"publish",s,v),j("dubhe-framework",o,v,w,_,b,C)}async function le(e,t,o){await O(t);let n=process.env.PRIVATE_KEY;if(!n)throw new g(`Missing PRIVATE_KEY environment variable.
|
|
38
38
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
39
|
-
in your contracts directory to use the default sui private key.`);let n
|
|
40
|
-
\u26A0\uFE0F Warning: Local Node Already Running`)),console.log(
|
|
41
|
-
\u274C Failed to Start Local Node`)),console.error(
|
|
42
|
-
\u{1F514} Stopping Local Node...`)),e&&(e.kill(),console.log(
|
|
43
|
-
\u274C Failed to Start Local Node`)),console.error(
|
|
39
|
+
in your contracts directory to use the default sui private key.`);let r=$(n);if(r===!1)throw new g("Please check your privateKey.");let s=new ze({secretKey:r}),a=new Ge({url:Je(t)});if(o=="dubhe-framework")await Z(a,s,t);else{let d=`${process.cwd()}/contracts/${e.name}`;B(`${d}/Move.toml`,t),await et(a,s,e,t,d)}}import{Dubhe as pe}from"@0xobelisk/sui-client";import{getFullnodeUrl as ot,SuiClient as nt}from"@mysten/sui/client";function rt(){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 st(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let r=new pe({secretKey:t}).getKeypair();de("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(x.yellow("\u26A0\uFE0FWARNING: 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 ue(){if(rt()){console.log(x.yellow(`
|
|
40
|
+
\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}U(),console.log("\u{1F680} Starting Local Node...");try{let e=de("sui",["start","--with-faucet","--force-regenesis"],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore",detached:!0});e.on("error",s=>{console.error(x.red(`
|
|
41
|
+
\u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${s.message}`))}),await N(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 st(),await N(2e3);let t=$("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c");if(t===!1)throw new g("Please check your privateKey.");let o=new pe({secretKey:t}),n=new nt({url:ot("localnet")}),r=console.log;console.log=()=>{},await Z(n,o,"localnet"),console.log=r,process.on("SIGINT",()=>{console.log(x.yellow(`
|
|
42
|
+
\u{1F514} Stopping Local Node...`)),e&&(e.kill(),console.log(x.green("\u2705 Local Node Stopped"))),process.exit()})}catch(e){console.error(x.red(`
|
|
43
|
+
\u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${e.message}`))}}var at={command:"node",describe:"Manage local Sui node",builder(e){return e},async handler(){try{await ue()}catch(e){console.error("Error executing command:",e),process.exit(1)}}},ge=at;import{Dubhe as it}from"@0xobelisk/sui-client";import{requestSuiFromFaucetV0 as ct,getFaucetHost as lt}from"@mysten/sui/faucet";import{SuiClient as dt,getFullnodeUrl as pt}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 a=process.env.PRIVATE_KEY;if(!a)throw new g(`Missing PRIVATE_KEY environment variable.
|
|
44
44
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
45
|
-
in your contracts directory to use the default sui private key.`);let
|
|
46
|
-
\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
|
|
47
|
-
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(
|
|
45
|
+
in your contracts directory to use the default sui private key.`);let c=$(a);if(c===!1)throw new g("Please check your PRIVATE_KEY.");o=new it({secretKey:c}).getKeypair().toSuiAddress()}else o=t;console.log(`
|
|
46
|
+
\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:lt(e),recipient:o}),console.log(" \u2514\u2500 Checking balance...");let n=new dt({url:pt(e)}),r={owner:o},s=await n.getBalance(r);console.log(`
|
|
47
|
+
\u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(s.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
|
|
48
48
|
\u2705 Faucet Operation Complete
|
|
49
|
-
`),process.exit(0)}},
|
|
50
|
-
public fun migrate(${o.schemaName}: &mut ${
|
|
51
|
-
${o.fields.map(d=>{let
|
|
49
|
+
`),process.exit(0)}},me=ut;import{schemaGen as gt,loadConfig as mt}from"@0xobelisk/sui-common";import ft from"chalk";var ht={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)"},"framework-id":{type:"string",desc:"Framework Package ID"}},async handler({"config-path":e,network:t,"framework-id":o}){try{let n=await mt(e);await gt(n,void 0,t,o),process.exit(0)}catch(n){console.log(ft.red("Schemagen failed!")),console.error(n.message)}}},fe=ht;import{loadConfig as yt}from"@0xobelisk/sui-common";var bt={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"},"contract-name":{type:"string",desc:"Optional contract name in contracts/ directory"}})},async handler({network:e,"config-path":t,"contract-name":o}){try{let n=await yt(t);await le(n,e,o)}catch(n){F(n),process.exit(1)}process.exit(0)}},he=bt;import{Dubhe as vt}from"@0xobelisk/sui-client";import{Transaction as wt,UpgradePolicy as _t}from"@mysten/sui/transactions";import{getFullnodeUrl as xt,SuiClient as Ct}from"@mysten/sui/client";import{execSync as kt}from"child_process";import L from"chalk";import*as M from"fs";import*as ye from"path";function $t(e,t){t.forEach(o=>{let n=`${e}/sources/codegen/schemas/${o.schemaName}.move`,r=M.readFileSync(n,"utf-8"),s=new RegExp(`public fun migrate\\(_${o.schemaName}: &mut ${X(o.schemaName)}, _cap: &UpgradeCap\\) {[^}]*}`),a=`
|
|
50
|
+
public fun migrate(${o.schemaName}: &mut ${X(o.schemaName)}, _cap: &UpgradeCap) {
|
|
51
|
+
${o.fields.map(d=>{let i="";return d.type.includes("StorageValue")?i="storage_value::new()":d.type.includes("StorageMap")?i="storage_map::new()":d.type.includes("StorageDoubleMap")&&(i="storage_double_map::new()"),`storage_migrate::add_field<${d.type}>(&mut ${o.schemaName}.id, b"${d.name}", ${i});`}).join("")}
|
|
52
52
|
}
|
|
53
|
-
`,
|
|
54
|
-
`),
|
|
55
|
-
`);
|
|
53
|
+
`,c=r.replace(s,a);M.writeFileSync(n,c,"utf-8")})}function X(e){return e.split("_").map((t,o)=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function St(e){let t=e.split("::");return t.length>0?t[t.length-1]:""}function z(e,t,o,n){let r=ye.resolve(e),a=M.readFileSync(r,"utf-8").split(`
|
|
54
|
+
`),c=a.findIndex(u=>u.trim()===`[env.${t}]`);if(c===-1)return console.log(`Network type [env.${t}] not found in the file.`),"";let d=-1,i="";for(let u=c+1;u<a.length;u++){let y=a[u].trim();if(y.startsWith("["))break;if(y.startsWith(o)){d=u,i=y.split("=")[1].trim().replace(/"/g,"");break}}if(d!==-1){a[d]=`${o} = "${n}"`;let u=a.join(`
|
|
55
|
+
`);M.writeFileSync(r,u,"utf-8")}else console.log(`${o} not found for [env.${t}].`);return i}async function be(e,t,o){await O(o);let n=process.cwd(),r=`${n}/contracts/${t}`,s=process.env.PRIVATE_KEY;if(!s)throw new g(`Missing PRIVATE_KEY environment variable.
|
|
56
56
|
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
57
|
-
in your contracts directory to use the default sui private key.`);let a
|
|
58
|
-
\u{1F680} Starting Migration for ${
|
|
59
|
-
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",
|
|
57
|
+
in your contracts directory to use the default sui private key.`);let a=$(s);if(a===!1)throw new g("Please check your privateKey.");let d=new vt({secretKey:a}).getKeypair(),i=new Ct({url:xt(o)}),u=Number(await oe(r,o)),y=await ne(r,o),b=await H(r,o),v=await re(r,o),C=z(`${r}/Move.lock`,o,"original-published-id","0x0000000000000000000000000000000000000000000000000000000000000000"),w=[],_=await te(r,o);for(let l in e.schemas)_.forEach(m=>{if(X(l)==St(m.name)){let I={schemaName:"",fields:[]},f=[],p=!1;for(let k in e.schemas[l].structure)k in m.structure||(p=!0,f.push({name:k,type:e.schemas[l].structure[k]}),m.structure[k]=e.schemas[l].structure[k]);p&&(I.schemaName=l,I.fields=f,w.push(I))}});w.forEach(l=>{console.log(`
|
|
58
|
+
\u{1F680} Starting Migration for ${l.schemaName}...`),console.log("\u{1F4CB} Migration Fields:",l.fields)}),$t(r,w);try{let l,m,I;try{let{modules:A,dependencies:Me,digest:Ke}=JSON.parse(kt(`sui move build --dump-bytecode-as-base64 --path ${n}/contracts/${t}`,{encoding:"utf-8"}));l=A,m=Me,I=Ke}catch(A){throw new V(A.stdout)}console.log(`
|
|
59
|
+
\u{1F680} Starting Upgrade Process...`),console.log("\u{1F4CB} OldPackageId:",y),console.log("\u{1F4CB} UpgradeCap Object Id:",v),console.log("\u{1F4CB} OldVersion:",u);let f=new wt,p=f.moveCall({target:"0x2::package::authorize_upgrade",arguments:[f.object(v),f.pure.u8(_t.COMPATIBLE),f.pure.vector("u8",I)]}),k=f.upgrade({modules:l,dependencies:m,package:y,ticket:p});f.moveCall({target:"0x2::package::commit_upgrade",arguments:[f.object(v),k]});let K=await i.signAndExecuteTransaction({signer:d,transaction:f,options:{showObjectChanges:!0}}),J="";K.objectChanges.map(A=>{A.type==="published"&&(console.log(L.blue(`${t} PackageId: ${A.packageId}`)),console.log(L.blue(`${t} Version: ${u+1}`)),J=A.packageId)}),z(`${r}/Move.lock`,o,"original-published-id",C),z(`${r}/Move.lock`,o,"latest-published-id",J),z(`${r}/Move.lock`,o,"published-version",u+1+""),console.log(L.green(`Upgrade Transaction Digest: ${K.digest}`)),j(t,o,J,v,b,u+1,_)}catch(l){console.log(L.red("Upgrade failed!")),console.error(l.message)}}import{loadConfig as It}from"@0xobelisk/sui-common";var Et={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 It(t);await be(o,o.name,e)}catch(o){F(o),process.exit(1)}process.exit(0)}},ve=Et;import{execSync as Dt}from"child_process";import Pt from"chalk";import{loadConfig as At}from"@0xobelisk/sui-common";var Ft={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"}})},async handler({"config-path":e,test:t}){try{console.log("\u{1F680} Running move test");let o=await At(e),s=`sui move test --path ${`${process.cwd()}/contracts/${o.name}`} ${t?` --test ${t}`:""}`,a=Dt(s,{encoding:"utf-8"});console.log(a)}catch(o){console.error(Pt.red("Error executing sui move test:")),console.log(o.stdout),process.exit(0)}}},we=Ft;import{execSync as Ot}from"child_process";import Mt from"chalk";import{loadConfig as Kt}from"@0xobelisk/sui-common";var Rt={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 Kt(e),s=`${process.cwd()}/contracts/${n.name}`;await O(t),B(s+"/Move.toml",t);let a=`sui move build --path ${s} ${o?" --dump-bytecode-as-base64":""}`,c=Ot(a,{encoding:"utf-8"});console.log(c)}catch(n){console.error(Mt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},_e=Rt;var Tt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){U()}},xe=Tt;import{Dubhe as Q}from"@0xobelisk/sui-client";import*as h 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.
|
|
60
|
+
`)));let o=process.cwd(),n;if(e){let c=new Q().getKeypair();if(n=c.getSecretKey(),h.writeFileSync(`${o}/.env`,`PRIVATE_KEY=${n}`),console.log(S.green(`File created at: ${o}/.env`)),t){let d=t.substring(0,t.lastIndexOf("/"));h.existsSync(d)||h.mkdirSync(d,{recursive:!0}),h.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
61
|
+
export const ACCOUNT = '${c.toSuiAddress()}';
|
|
62
|
+
`),console.log(S.green(`File created at: ${t}
|
|
63
|
+
`))}console.log(S.blue(`Force generate new Account: ${c.toSuiAddress()}`));return}try{let c=h.readFileSync(`${o}/.env`,"utf8").match(/PRIVATE_KEY=(.+)/);if(c&&c[1]){n=c[1];let i=new Q({secretKey:n}).getKeypair();if(t){let u=t.substring(0,t.lastIndexOf("/"));h.existsSync(u)||h.mkdirSync(u,{recursive:!0}),h.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
64
|
+
export const ACCOUNT = '${i.toSuiAddress()}';
|
|
65
|
+
`),console.log(S.green(`File created at: ${t}
|
|
66
|
+
`))}console.log(S.blue(`Using existing Account: ${i.toSuiAddress()}`));return}}catch{}let s=new Q().getKeypair();if(n=s.getSecretKey(),h.writeFileSync(`${o}/.env`,`PRIVATE_KEY=${n}`),console.log(S.green(`File created at: ${o}/.env`)),t){let a=t.substring(0,t.lastIndexOf("/"));h.existsSync(a)||h.mkdirSync(a,{recursive:!0}),h.writeFileSync(t,`export const PRIVATEKEY = '${n}';
|
|
67
|
+
export const ACCOUNT = '${s.toSuiAddress()}';
|
|
68
|
+
`),console.log(S.green(`File created at: ${t}
|
|
69
|
+
`))}console.log(S.blue(`Generate new Account: ${s.toSuiAddress()}`))}var jt={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)}},ke=jt;import{Dubhe as Nt}from"@0xobelisk/sui-client";import $e from"chalk";import Ut from"dotenv";Ut.config();async function Se(e,t=2){try{console.log($e.blue("Note: You need at least 2 SUI for transaction fees and staking, and registering a Dapp will reserve 1 SUI for Dubhe Dapp Staking, which can be retrieved upon unregistering."));let o=process.env.PRIVATE_KEY;if(!o)throw new g(`Missing PRIVATE_KEY environment variable.
|
|
70
|
+
Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
|
|
71
|
+
in your contracts directory to use the default sui private key.`);if($(o)===!1)throw new g("Please check your privateKey.");let s=await new Nt({secretKey:process.env.PRIVATE_KEY,networkType:e}).getBalance(),a=Number(s.totalBalance)/1e9;if(a<t)throw new g(`Account balance is less than ${t} SUI. Please get more SUI.`);console.log($e.green(`Current account balance: ${a.toFixed(4)} SUI`))}catch(o){throw new g("Failed to check balance: "+o)}}var Vt={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"},amount:{type:"number",default:2,desc:"Amount of SUI to check balance for"}},async handler({network:e,amount:t}){try{await Se(e,t)}catch(o){console.error("Error checking balance:",o),process.exit(1)}process.exit(0)}},Ie=Vt;import*as Ee from"fs/promises";import{mkdirSync as Yt,writeFileSync as qt}from"fs";import{dirname as Ht}from"path";async function Bt(e,t){try{let o=await Ee.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 Lt(e,t,o,n){let r=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
|
|
72
|
+
|
|
73
|
+
export const NETWORK: NetworkType = '${e}';
|
|
74
|
+
|
|
75
|
+
export const PACKAGE_ID = '${t}'
|
|
76
|
+
|
|
77
|
+
${o.map(s=>`export const ${s.name.split("::")[2]}_Object_Id = '${s.objectId}'`).join(`
|
|
78
|
+
`)}
|
|
79
|
+
`;zt(r,n,"storeConfig")}async function zt(e,t,o){Yt(Ht(t),{recursive:!0}),qt(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function De(e,t,o){let r=`${process.cwd()}/contracts/${e.name}`,s=await Bt(r,t);Lt(s.network,s.packageId,s.schemas,o)}import{loadConfig as Jt}from"@0xobelisk/sui-common";var Gt={command:"store-config",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 Jt(e);await De(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Pe=Gt;var Ae=[he,ge,me,fe,ve,we,_e,xe,ke,Ie,Pe];import*as Oe from"dotenv";import Fe from"chalk";Oe.config();Wt(Zt(process.argv)).scriptName("dubhe").command(Ae).strict().fail((e,t)=>{console.error(Fe.red(e)),e.includes("Missing required argument")&&console.log(Fe.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),F(t),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
|
|
60
80
|
//# sourceMappingURL=dubhe.js.map
|