midnight-wallet-cli 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/mcp-server.js +329 -333
- package/dist/wallet.js +402 -400
- package/package.json +6 -6
package/dist/wallet.js
CHANGED
|
@@ -1,42 +1,44 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as np}from"node:module";var ep=Object.defineProperty;var tp=(e)=>e;function rp(e,t){this[e]=tp.bind(null,t)}var fe=(e,t)=>{for(var r in t)ep(e,r,{get:t[r],enumerable:!0,configurable:!0,set:rp.bind(t,r)})};var E=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var xs=np(import.meta.url);function _i(e){let t=e??process.argv.slice(2),r=[],n={},s=0;while(s<t.length){let o=t[s];if(o.startsWith("--")){let i=o.slice(2),a=t[s+1];if(a!==void 0&&!a.startsWith("-"))n[i]=a,s+=2;else n[i]=!0,s+=1}else if(o.startsWith("-")&&o.length===2){let i=o.slice(1),a=t[s+1];if(a!==void 0&&!a.startsWith("-"))n[i]=a,s+=2;else n[i]=!0,s+=1}else r.push(o),s+=1}return{command:r[0],subcommand:r[1],positionals:r.slice(2),flags:n}}function A(e,t){let r=e.flags[t];if(r===void 0||r===!0)return;return r}function N(e,t){return t in e.flags}function Re(e){return N(e,"verbose")}function dt(e){return N(e,Qr)&&!N(e,mr)}function lt(e){if(N(e,"no-cache"))throw Error(`--no-cache is not supported on write commands (transfer, airdrop, dust register, serve).
|
|
3
3
|
`+`Writes always use the cache — the SDK's fresh-sync is too slow on hosted networks.
|
|
4
|
-
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function
|
|
5
|
-
`);for(let g of f)o.push(...
|
|
6
|
-
`)}function
|
|
7
|
-
`).map((o
|
|
8
|
-
`)
|
|
9
|
-
`)
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
4
|
+
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function en(e,t,r){let n=A(e,t);if(n===void 0)throw Error(`Missing required flag: --${t} <${r}>`);return n}var Qr="_minimal",mr="_full";function At(e){if(!e||e!==e.trim())return!1;if(/[\/\\]/.test(e))return!1;if(e.endsWith(".json"))return!1;if(e==="."||e==="..")return!1;if(/[\x00-\x1f]/.test(e))return!1;return!0}var rt="0000000000000000000000000000000000000000000000000000000000000001",fr="0000000000000000000000000000000000000000000000000000000000000000",kt="/api/v4/graphql",Ct="/api/v4/graphql/ws",Es=6,Ts=1e6,Di=300000000000000n,Pi=5,gr=800000000000000n,Oi=5000000000n,Mi=8267n,Fi=10800n,Li=300000,Ns=30000,Ui=1e4,Rs=120000,tn=300000,$s=60000,ji=16384,Wi=0.7,Bi=512,hr=10,Hi=3,Gi=600000,Is=15000,Ki=115,ae=".midnight",rn="wallet.json",Ji="config.json",Se=448,be=384,Vi="localnet",_s=1,$e="cache",Lt="wallets",wr="default",yr=10,Ds=3000,zi=120000,xt=9932,nn="https://midnight-comp-tracker.vercel.app";function ut(){return!("NO_COLOR"in process.env)}function Ut(e,t){if(!ut())return e;return`\x1B[38;5;${t}m${e}\x1B[0m`}function k(e){if(!ut())return e;return`\x1B[1m${e}\x1B[0m`}function l(e){if(!ut())return e;return`\x1B[2m${e}\x1B[0m`}function L(e){return Ut(e,38)}function J(e){return Ut(e,196)}function H(e){return Ut(e,40)}function M(e){return Ut(e,226)}function We(e){return Ut(e,15)}function nt(e){return Ut(e,245)}function W(e,t=Xi){let r=` ${e} `,n=t-r.length;if(n<=0)return k(r);let s=Math.floor(n/2),o=n-s;return k("═".repeat(s)+r+"═".repeat(o))}function V(e=Xi){return l("─".repeat(e))}function C(e,t,r=16){let n=(e+":").padEnd(r);return` ${nt(n)}${t}`}function Et(e){let t=e<0n,r=t?-e:e,n=BigInt(10**Es),s=r/n,i=(r%n).toString().padStart(Es,"0");return`${t?"-":""}${s}.${i}`}function sn(e){return`${Et(e)} NIGHT`}function Wt(e){let t=e<0n,r=t?-e:e,n=10n**BigInt(qi),s=r/n,a=(r%n).toString().padStart(qi,"0").replace(/0+$/,"").padEnd(6,"0");return`${t?"-":""}${s}.${a}`}function Sr(e){return`${Wt(e)} DUST`}function re(e,t=!1){let r=t&&e.length>20?e.slice(0,10)+"…"+e.slice(-8):e;return L(r)}function sp(e,t){let r=[],n="",s=0,o=!1,i=0;while(i<e.length){let a=/^\x1b\[[0-9;]*m/.exec(e.slice(i));if(a){n+=a[0],o=!0,i+=a[0].length;continue}if(s===t)r.push(o?n+"\x1B[0m":n),n="",s=0,o=!1;n+=e[i],s+=1,i+=1}if(n.length>0)r.push(o?n+"\x1B[0m":n);return r}function op(e,t){if(jt(e).length<=t)return[e];let n=e.split(/(\s+)/).flatMap((a)=>jt(a).length>t?sp(a,t):[a]),s=[],o="",i=0;for(let a of n){let c=jt(a).length;if(i+c>t&&i>0)s.push(o),o=a.trimStart(),i=jt(o).length;else o+=a,i+=c}if(o.length>0)s.push(o);return s}function Yi(e,t="light",r=70){let n=t==="heavy"?{tl:"╔",tr:"╗",bl:"╚",br:"╝",h:"═",v:"║"}:{tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"},s=r-4,o=[];for(let p of e){let f=p.split(`
|
|
5
|
+
`);for(let g of f)o.push(...op(g,s))}let i=Math.max(...o.map((p)=>jt(p).length)),a=Math.max(i+2,20),c=n.tl+n.h.repeat(a)+n.tr,d=n.bl+n.h.repeat(a)+n.br,u=o.map((p)=>{let f=jt(p).length,g=a-f-2;return`${n.v} ${p}${" ".repeat(Math.max(0,g))} ${n.v}`});return[c,...u,d].join(`
|
|
6
|
+
`)}function Zi(e,t){let n=e.split(`
|
|
7
|
+
`).map((s,o)=>o===0?J(k("Error: "))+J(s):J(s));if(t)n.push(""),n.push(l("Suggestion: ")+t);return n.join(`
|
|
8
|
+
`)}function Qi(e,t){let s=e.replace(/^Usage:\s*/i,"").split(`
|
|
9
|
+
`).map((o,i)=>i===0?M(k("Usage: "))+M(o):M(o));if(t)s.push(""),s.push(l("Hint: ")+t);return s.join(`
|
|
10
|
+
`)}function pt(e,t){let n=[`${H("✓")} ${e}`];if(t)n.push(C("Transaction",L(t)));return n.join(`
|
|
11
|
+
`)}var Xi=60,qi=15,jt=(e)=>e.replace(/\x1b\[[0-9;]*m/g,"");var ue=()=>{};function br(e){let t=(e.message??"").toLowerCase();if(t.includes("operation cancelled")||t.includes("operation aborted")||t==="cancelled"||t==="aborted")return{exitCode:7,errorCode:Ae.CANCELLED};if(t.includes("wallet file not found")||t.includes("wallet")&&t.includes("not found"))return{exitCode:3,errorCode:Ae.WALLET_NOT_FOUND};if(t.includes("missing required flag")||t.includes("missing amount")||t.includes("missing recipient")||t.includes("missing config key")||t.includes("missing or invalid subcommand")||t.includes("unknown command")||t.includes("cannot specify both")||t.includes("invalid bip-39")||t.includes("seed must be")||t.includes("key index must be")||t.includes("shielded balances are private")||t.includes("shielded is unavailable")||t.includes("belongs to")&&t.includes("--network is")||t.includes("usage:"))return{exitCode:2,errorCode:Ae.INVALID_ARGS};if(t.includes("proof")&&t.includes("timeout"))return{exitCode:6,errorCode:Ae.PROOF_TIMEOUT};if(t.includes("stale utxo")||t.includes("error code 115")||t.includes("errorcode: 115"))return{exitCode:6,errorCode:Ae.STALE_UTXO};if(t.includes("error 170")||t.includes("errorcode: 170")||t.includes("invaliddustspendproof"))return{exitCode:6,errorCode:Ae.INVALID_DUST_PROOF};if(t.includes("stale cache")||t.includes("chain reset")||t.includes("chainid mismatch")||t.includes("applied > highest"))return{exitCode:6,errorCode:Ae.STALE_CACHE};if(t.includes("failed to prove"))return{exitCode:6,errorCode:Ae.PROOF_FAILURE};if(t.includes("wallet sync timed out")||t.includes("sync timed out")||t.includes("timed out waiting for dust")||t.includes("did not respond within")||t.includes("did not produce a block")||t.includes("did not report funds"))return{exitCode:4,errorCode:Ae.SYNC_TIMEOUT};if(t.includes("no dust")||t.includes("dust")&&(t.includes("required")||t.includes("available")||t.includes("insufficient")))return{exitCode:5,errorCode:Ae.DUST_REQUIRED};if(t.includes("insufficient")||t.includes("not enough"))return{exitCode:5,errorCode:Ae.INSUFFICIENT_BALANCE};if(t.includes("rejected")||t.includes("transaction failed"))return{exitCode:6,errorCode:Ae.TX_REJECTED};if(t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("websocket")||t.includes("connection refused")||t.includes("request to ")&&t.includes(" failed, reason:")||t.includes("network")&&t.includes("error"))return{exitCode:4,errorCode:Ae.NETWORK_ERROR};return{exitCode:1,errorCode:Ae.UNKNOWN}}function ea(e){let t=e.match(/^request to (\S+) failed, reason:\s*$/i);if(t){let r=t[1];return`request to ${r} failed: unable to reach ${r} (connection refused, DNS, or TLS error). Is the indexer running?`}return e}var Ps=2,Ae;var Os=E(()=>{Ae={INVALID_ARGS:"INVALID_ARGS",WALLET_NOT_FOUND:"WALLET_NOT_FOUND",NETWORK_ERROR:"NETWORK_ERROR",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",TX_REJECTED:"TX_REJECTED",STALE_UTXO:"STALE_UTXO",STALE_CACHE:"STALE_CACHE",PROOF_TIMEOUT:"PROOF_TIMEOUT",PROOF_FAILURE:"PROOF_FAILURE",INVALID_DUST_PROOF:"INVALID_DUST_PROOF",DUST_REQUIRED:"DUST_REQUIRED",SYNC_TIMEOUT:"SYNC_TIMEOUT",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN"}});function ta(e){return e instanceof Z}var Z;var Be=E(()=>{Z=class Z extends Error{constructor(e){super(e);this.name="UsageError",Object.setPrototypeOf(this,Z.prototype)}}});function Ms(e){vr=e}function D(e){let t=JSON.stringify(e)+`
|
|
12
|
+
`;if(vr)vr(t);else process.stdout.write(t)}function Fs(e,t,r){let n=JSON.stringify({error:!0,code:t,message:e.message,exitCode:r})+`
|
|
13
|
+
`;if(vr)vr(n);else process.stdout.write(n)}var vr=null;var on;var ra=E(()=>{on={name:"midnight-wallet-cli",version:"0.5.4",type:"module",description:"Git-style CLI wallet for the Midnight blockchain",license:"Apache-2.0",author:"Norman Lopez (https://github.com/nel349)",homepage:"https://github.com/nel349/midnight-wallet-cli#readme",repository:{type:"git",url:"git+https://github.com/nel349/midnight-wallet-cli.git"},bugs:{url:"https://github.com/nel349/midnight-wallet-cli/issues"},keywords:["midnight","blockchain","wallet","cli","zk","zero-knowledge","compact","mcp","ai-agent"],workspaces:["packages/connector"],bin:{midnight:"dist/wallet.js",mn:"dist/wallet.js","midnight-wallet-cli":"dist/wallet.js","midnight-wallet-mcp":"dist/mcp-server.js"},files:["dist","docs/SKILL.md","NOTICE"],engines:{node:">=20",bun:">=1.3.0"},scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",link:"bun link",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/compact-runtime":"^0.16.0","@midnight-ntwrk/dapp-connector-api":"^4.0.1","@midnight-ntwrk/ledger-v8":"^8.1.0","@midnight-ntwrk/midnight-js-contracts":"^4.1.1","@midnight-ntwrk/midnight-js-http-client-proof-provider":"^4.1.1","@midnight-ntwrk/midnight-js-indexer-public-data-provider":"^4.1.1","@midnight-ntwrk/midnight-js-level-private-state-provider":"^4.1.1","@midnight-ntwrk/midnight-js-network-id":"^4.1.1","@midnight-ntwrk/midnight-js-node-zk-config-provider":"^4.1.1","@midnight-ntwrk/midnight-js-types":"^4.1.1","@midnight-ntwrk/midnight-js-utils":"^4.1.1","@midnight-ntwrk/wallet-sdk-abstractions":"^2.0.0","@midnight-ntwrk/wallet-sdk-address-format":"^3.1.0","@midnight-ntwrk/wallet-sdk-capabilities":"^3.2.0","@midnight-ntwrk/wallet-sdk-dust-wallet":"^4.0.0","@midnight-ntwrk/wallet-sdk-facade":"^4.0.0","@midnight-ntwrk/wallet-sdk-hd":"^3.0.1","@midnight-ntwrk/wallet-sdk-shielded":"^3.0.0","@midnight-ntwrk/wallet-sdk-unshielded-wallet":"^3.0.0","@modelcontextprotocol/sdk":"^1.27.1","@scure/bip39":"^2.0.1",rxjs:"^7.8.1",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"},optionalDependencies:{"@nel349/dust-sync-darwin-arm64":"0.5.4","@nel349/dust-sync-darwin-x64":"0.5.4","@nel349/dust-sync-linux-x64":"0.5.4","@nel349/dust-sync-linux-arm64":"0.5.4","@nel349/dust-sync-win32-x64":"0.5.4"}}});var kr,He,na;var Cr=E(()=>{ra();kr=on.name,He=on.version,na=on.description});import{execSync as ap}from"child_process";function xe(e){return sa.includes(e)}function Ar(e){return{...cp[e]}}function xr(){return sa}function dp(){try{let e=ap('docker ps --format "{{.Image}}|{{.Ports}}"',{encoding:"utf-8",timeout:5000}),t={};for(let r of e.trim().split(`
|
|
14
|
+
`)){if(!r)continue;let[n,s]=r.split("|"),o=(i)=>{let a=new RegExp(`0\\.0\\.0\\.0:(\\d+)->${i}/tcp`),c=s?.match(a);return c?parseInt(c[1],10):void 0};if(n.includes("indexer-standalone")||n.includes("indexer")){let i=o(8088);if(i)t.indexerPort=i}if(n.includes("midnight-node")){let i=o(9944);if(i)t.nodePort=i}if(n.includes("proof-server")){let i=o(6300);if(i)t.proofServerPort=i}}return t}catch{return{}}}function oa(e){let t=Ar(e);if(e==="undeployed"){let r=dp();if(r.indexerPort)t.indexer=`http://localhost:${r.indexerPort}${kt}`,t.indexerWS=`ws://localhost:${r.indexerPort}${Ct}`;if(r.nodePort)t.node=`ws://localhost:${r.nodePort}`;if(r.proofServerPort)t.proofServer=`http://localhost:${r.proofServerPort}`}return t}function Le(e,t,r,n){let s=Ee(n),o=Ls(s,r);if(e.proofServer=t.proofServer??o["proof-server"]??e.proofServer,e.node=t.node??o.node??e.node,e.indexerWS=t.indexerWS??o["indexer-ws"]??e.indexerWS,t.indexerWS??o["indexer-ws"]){let i=e.indexerWS;e.indexer=i.replace(/^wss:/,"https:").replace(/^ws:/,"http:").replace(/\/ws$/,"")}return e}var cp,sa;var Ie=E(()=>{Bt();cp={preprod:{indexer:`https://indexer.preprod.midnight.network${kt}`,indexerWS:`wss://indexer.preprod.midnight.network${Ct}`,node:"wss://rpc.preprod.midnight.network",proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:`https://indexer.preview.midnight.network${kt}`,indexerWS:`wss://indexer.preview.midnight.network${Ct}`,node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:`http://localhost:8088${kt}`,indexerWS:`ws://localhost:8088${Ct}`,node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},sa=["preprod","preview","undeployed"]});import*as st from"fs";import*as Us from"path";import{homedir as lp}from"os";function js(e){return up[e]??e}function pp(e){return/^(https?|wss?):\/\/\S+/.test(e)}function ia(e){return e??Us.join(lp(),ae)}function aa(e){return Us.join(ia(e),Ji)}function mp(e){let t=ia(e);if(!st.existsSync(t))st.mkdirSync(t,{recursive:!0,mode:Se})}function Ee(e){let t=aa(e);if(!st.existsSync(t))return{...Er};let r;try{r=st.readFileSync(t,"utf-8")}catch{return{...Er}}let n;try{n=JSON.parse(r)}catch{return{...Er}}let s={network:n.network&&xe(n.network)?n.network:Er.network};if(n["proof-server"]&&typeof n["proof-server"]==="string")s["proof-server"]=n["proof-server"];if(n.node&&typeof n.node==="string")s.node=n.node;if(n["indexer-ws"]&&typeof n["indexer-ws"]==="string")s["indexer-ws"]=n["indexer-ws"];if(n.wallet&&typeof n.wallet==="string")s.wallet=n.wallet;if(n.networks&&typeof n.networks==="object"){let o={};for(let[i,a]of Object.entries(n.networks)){if(!xe(i)||!a||typeof a!=="object")continue;let c={};for(let d of Tr){let u=a[d];if(u&&typeof u==="string")c[d]=u}if(Object.keys(c).length>0)o[i]=c}if(Object.keys(o).length>0)s.networks=o}return s}function Ls(e,t){let r=e.networks?.[t]??{},n=t===e.network;return{"proof-server":r["proof-server"]??(n?e["proof-server"]:void 0),node:r.node??(n?e.node:void 0),"indexer-ws":r["indexer-ws"]??(n?e["indexer-ws"]:void 0)}}function Nr(e,t){mp(t);let r=aa(t);st.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
15
|
+
`,{mode:be})}function ca(e,t){let r=js(e),n=Ee(t);if(r==="network")return n.network;if(r==="wallet")return n.wallet??"(not set)";if(Tr.has(r)){let o=Ls(n,n.network)[r];return typeof o==="string"?o:"(not set)"}throw Error(`Unknown config key: "${e}"
|
|
16
|
+
Valid keys: ${an.join(", ")}`)}function fp(e,t){let r={...e.networks?.[t]??{}},n=!1;for(let s of Tr){let o=s,i=e[o];if(i&&typeof i==="string"){if(!r[o])r[o]=i;delete e[o],n=!0}}if(n)e.networks={...e.networks??{},[t]:r}}function da(e,t,r){let n=js(e),s=Ee(r);if(n==="network"){if(!xe(t))throw Error(`Invalid network: "${t}"
|
|
17
|
+
Valid networks: preprod, preview, undeployed`);fp(s,s.network),s.network=t}else if(n==="wallet"){if(!At(t))throw Error(`Invalid wallet name: "${t}"
|
|
18
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(Tr.has(n)){if(!pp(t))throw Error(`Invalid URL for "${e}": "${t}"
|
|
17
19
|
Must start with http://, https://, ws://, or wss://`);let o=n,i={...s.networks?.[s.network]??{}};i[o]=t,s.networks={...s.networks??{},[s.network]:i},delete s[o]}else throw Error(`Unknown config key: "${e}"
|
|
18
|
-
Valid keys: ${
|
|
19
|
-
Valid keys: ${
|
|
20
|
-
`,{mode:
|
|
21
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=
|
|
22
|
-
Run "midnight wallet list" to see available wallets.`);let r=
|
|
23
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=$t(),r=
|
|
24
|
-
Run "midnight wallet list" to see available wallets.`);let n=
|
|
25
|
-
Switch to another wallet first: midnight wallet use <other-wallet>`);if(
|
|
26
|
-
`+"Create another wallet first: midnight wallet generate <name>");
|
|
27
|
-
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=
|
|
28
|
-
${c.message}`)}let n;try{n=JSON.parse(r)}catch{throw Error(`Invalid JSON in wallet file: ${t}`)}if(!n.seed||!n.createdAt){let c=["seed","createdAt"];if(!n.addresses)c.push("address");let d=c.filter((u)=>!n[u]);if(d.length>0)throw Error(`Wallet file is missing required fields (${d.join(", ")}): ${t}`)}if(!/^[0-9a-fA-F]+$/.test(n.seed))throw Error(`Invalid seed format in wallet file (expected hex string): ${t}`);if(!n.addresses){if(!n.address)throw Error(`Wallet file is missing required fields (address): ${t}`);let c=Buffer.from(n.seed,"hex"),d=
|
|
29
|
-
`,{mode:
|
|
30
|
-
`,{mode:
|
|
31
|
-
`,{mode:
|
|
20
|
+
Valid keys: ${an.join(", ")}`);Nr(s,r)}function la(e,t){let r=js(e),n=Ee(t);if(r==="network")n.network=Er.network;else if(r==="wallet")delete n.wallet;else if(Tr.has(r)){let s=r;delete n[s];let o=n.networks?.[n.network];if(o){if(delete o[s],Object.keys(o).length===0){if(delete n.networks[n.network],Object.keys(n.networks).length===0)delete n.networks}}}else throw Error(`Unknown config key: "${e}"
|
|
21
|
+
Valid keys: ${an.join(", ")}`);Nr(n,t)}function Ws(){return an}var Er,an,up,Tr;var Bt=E(()=>{Ie();Er={network:"undeployed"},an=["network","proof-server","node","indexer-ws","wallet"],up={"network-id":"network"};Tr=new Set(["proof-server","node","indexer-ws"])});import{HDWallet as gp,Roles as Bs}from"@midnight-ntwrk/wallet-sdk-hd";function Hs(e,t){let r=gp.fromSeed(e);if(r.type!=="seedOk")throw Error("Invalid seed for HD wallet");let n=r.hdWallet.selectAccount(0).selectRole(t).deriveKeyAt(0);if(n.type==="keyOutOfBounds")throw Error("Key derivation out of bounds");return n.key}function Tt(e){return Hs(e,Bs.Zswap)}function ua(e){return Hs(e,Bs.NightExternal)}function mt(e){return Hs(e,Bs.Dust)}var Nt=()=>{};import{HDWallet as hp,Roles as wp}from"@midnight-ntwrk/wallet-sdk-hd";import{createKeystore as yp,PublicKey as Sp}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{MidnightBech32m as bp,ShieldedAddress as vp,ShieldedCoinPublicKey as kp,ShieldedEncryptionPublicKey as Cp}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as Gs}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as pa from"@midnight-ntwrk/ledger-v8";function ve(e,t,r=0){let n=ma[t],s=hp.fromSeed(e);if(s.type!=="seedOk")throw Error("Invalid seed for HD wallet");let o=s.hdWallet.selectAccount(0).selectRole(wp.NightExternal).deriveKeyAt(r);if(o.type==="keyOutOfBounds")throw Error(`Key index ${r} out of bounds`);let i=yp(o.key,n);return Sp.fromKeyStore(i).address}function Rt(e,t=0){let r={};for(let n of xr())r[n]=ve(e,n,t);return r}function Rr(e){let t=$r(e),r={};for(let n of xr()){let s=ma[n];r[n]=bp.encode(s,t).asString()}return r}function $r(e){let t=Tt(e),r=pa.ZswapSecretKeys.fromSeed(t);return new vp(new kp(Buffer.from(r.coinPublicKey,"hex")),new Cp(Buffer.from(r.encryptionPublicKey,"hex")))}var ma;var Ge=E(()=>{Ie();Nt();ma={preprod:Gs.NetworkId.PreProd,preview:Gs.NetworkId.Preview,undeployed:Gs.NetworkId.Undeployed}});import*as Y from"fs";import*as ge from"path";import{homedir as Ap}from"os";function Ht(e,t,r){let n=ge.resolve(e);if(!Y.existsSync(n))return;try{let s=JSON.parse(Y.readFileSync(n,"utf-8")),o=s.shieldedAddresses&&typeof s.shieldedAddresses==="object"?s.shieldedAddresses:{};if(o[t]=r,s.shieldedAddresses=o,s.shieldedAddress&&s.shieldedAddress===r)delete s.shieldedAddress;Y.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
22
|
+
`,{mode:be})}catch{}}function Ks(){return ge.join(Ap(),ae)}function $t(){return ge.join(Ks(),Lt)}function Js(){return ge.join(Ks(),rn)}function ga(){let e=Ks();if(!Y.existsSync(e))Y.mkdirSync(e,{recursive:!0,mode:Se})}function xp(){ga();let e=$t();if(!Y.existsSync(e))Y.mkdirSync(e,{recursive:!0,mode:Se})}function Ep(e){return e.includes("/")||e.includes("\\")||e.endsWith(".json")}function ie(e){if(e!==void 0){if(Ep(e))return ge.resolve(e);return ge.join($t(),`${e}.json`)}let r=Ee().wallet??wr;return ge.join($t(),`${r}.json`)}function ft(){return Ee().wallet??wr}function Ir(e){if(!At(e))throw Error(`Invalid wallet name: "${e}"
|
|
23
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=ge.join($t(),`${e}.json`);if(!Y.existsSync(t))throw Error(`Wallet "${e}" not found.
|
|
24
|
+
Run "midnight wallet list" to see available wallets.`);let r=Ee();r.wallet=e,Nr(r)}function Vs(){let e=$t();if(!Y.existsSync(e))return[];let t=ft();return Y.readdirSync(e).filter((n)=>n.endsWith(".json")).sort().map((n)=>{let s=n.replace(/\.json$/,""),o=ge.join(e,n);try{let i=JSON.parse(Y.readFileSync(o,"utf-8")),a;if(i.addresses)a=i.addresses;else if(i.address&&i.seed)try{let d=Buffer.from(i.seed,"hex");a=Rt(d)}catch{a={undeployed:i.address,preprod:"(unknown)",preview:"(unknown)"}}else a={undeployed:"(unknown)",preprod:"(unknown)",preview:"(unknown)"};let c;if(i.shieldedAddresses&&typeof i.shieldedAddresses==="object")c=i.shieldedAddresses;else if(i.seed)try{c=Rr(Buffer.from(i.seed,"hex"))}catch{}return{name:s,addresses:a,shieldedAddresses:c,isActive:s===t,createdAt:typeof i.createdAt==="string"?i.createdAt:void 0,file:o}}catch{return{name:s,addresses:{undeployed:"(invalid)",preprod:"(invalid)",preview:"(invalid)"},isActive:s===t,file:o}}})}function Tp(e,t){for(let r of e){for(let[n,s]of Object.entries(r.addresses))if(s===t)return{wallet:r,network:n};if(r.shieldedAddresses){for(let[n,s]of Object.entries(r.shieldedAddresses))if(s===t)return{wallet:r,network:n}}}return}function ha(e){return Tp(Vs(),e)}function wa(e){if(!At(e))throw Error(`Invalid wallet name: "${e}"
|
|
25
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=$t(),r=ge.join(t,`${e}.json`);if(!Y.existsSync(r))throw Error(`Wallet "${e}" not found.
|
|
26
|
+
Run "midnight wallet list" to see available wallets.`);let n=ft();if(e===n)throw Error(`Cannot remove the active wallet "${e}".
|
|
27
|
+
Switch to another wallet first: midnight wallet use <other-wallet>`);if(Y.readdirSync(t).filter((o)=>o.endsWith(".json")).length<=1)throw Error(`Cannot remove "${e}" — it is the only wallet.
|
|
28
|
+
`+"Create another wallet first: midnight wallet generate <name>");Y.unlinkSync(r)}function ya(){let e=Js();if(!Y.existsSync(e))return;let t=$t();if(Y.existsSync(t)){if(Y.readdirSync(t).filter((o)=>o.endsWith(".json")).length>0)return}xp();let r=ge.join(t,`${wr}.json`);Y.copyFileSync(e,r),Y.chmodSync(r,be),Y.unlinkSync(e);let n=Ee();n.wallet=wr,Nr(n)}function ce(e){let t=e?ge.resolve(e):Js();if(!Y.existsSync(t))throw Error(`Wallet file not found: ${t}
|
|
29
|
+
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=Y.readFileSync(t,"utf-8")}catch(c){throw Error(`Failed to read wallet file: ${t}
|
|
30
|
+
${c.message}`)}let n;try{n=JSON.parse(r)}catch{throw Error(`Invalid JSON in wallet file: ${t}`)}if(!n.seed||!n.createdAt){let c=["seed","createdAt"];if(!n.addresses)c.push("address");let d=c.filter((u)=>!n[u]);if(d.length>0)throw Error(`Wallet file is missing required fields (${d.join(", ")}): ${t}`)}if(!/^[0-9a-fA-F]+$/.test(n.seed))throw Error(`Invalid seed format in wallet file (expected hex string): ${t}`);if(!n.addresses){if(!n.address)throw Error(`Wallet file is missing required fields (address): ${t}`);let c=Buffer.from(n.seed,"hex"),d=Rt(c),u={seed:n.seed,addresses:d,createdAt:n.createdAt};if(n.mnemonic)u.mnemonic=n.mnemonic;let p=fa(n,c);if(p)u.shieldedAddresses=p;let f={...n,addresses:d};if(p)f.shieldedAddresses=p,delete f.shieldedAddress;return Y.writeFileSync(t,JSON.stringify(f,null,2)+`
|
|
31
|
+
`,{mode:be}),u}if(typeof n.addresses!=="object")throw Error(`Wallet file has invalid addresses field: ${t}`);let s={seed:n.seed,addresses:n.addresses,createdAt:n.createdAt};if(n.mnemonic)s.mnemonic=n.mnemonic;let o=Buffer.from(n.seed,"hex"),i=fa(n,o);if(i)s.shieldedAddresses=i;if(i&&(!n.shieldedAddresses||typeof n.shieldedAddresses!=="object"||Object.keys(n.shieldedAddresses).length<Object.keys(i).length))try{let c={...n,shieldedAddresses:i};delete c.shieldedAddress,Y.writeFileSync(t,JSON.stringify(c,null,2)+`
|
|
32
|
+
`,{mode:be})}catch{}return s}function fa(e,t){let r;try{r=Rr(t)}catch{}let n=e.shieldedAddresses,s=n&&typeof n==="object"?n:null,o=s?Object.fromEntries(Object.entries(s).filter(([,i])=>typeof i==="string"&&i.length>0)):{};if(!r)return Object.keys(o).length>0?o:void 0;return{...r,...o}}function cn(e,t){let r=t?ge.resolve(t):Js();if(!t)ga();else{let n=ge.dirname(r);if(!Y.existsSync(n))Y.mkdirSync(n,{recursive:!0,mode:Se})}return Y.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
33
|
+
`,{mode:be}),r}var ke=E(()=>{Bt();Ge()});import Np from"node:v8";import Rp from"node:os";import{spawn as $p}from"node:child_process";function _p(e){let t=e.desiredMb??ji,r=e.ramFraction??Wi,n=e.minGainMb??Bi;if(!Number.isFinite(t)||t<=0)return null;if(!Number.isFinite(e.totalMb)||e.totalMb<=0)return null;let s=Math.floor(e.totalMb*r),o=Math.min(Math.floor(t),s);if(o<=e.currentLimitMb+n)return null;return o}async function _r(){if(process.env[zs]){Pp();return}let e=process.env[Ip],t=e!==void 0?Number(e):void 0,r=_p({totalMb:Math.floor(Rp.totalmem()/Sa),currentLimitMb:Math.floor(Np.getHeapStatistics().heap_size_limit/Sa),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=$p(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[zs]:"1"}});Dp(s),s.on("error",()=>{process.env[zs]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function Dp(e,t=(r,n)=>{process.on(r,n)}){let r=["SIGINT","SIGTERM","SIGHUP"];for(let n of r)t(n,()=>{try{e.kill(n)}catch{}});t("exit",()=>{try{e.kill("SIGKILL")}catch{}})}function Pp(){let e=process.ppid;if(!e||e<=1)return;setInterval(()=>{if(process.ppid!==e)try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},2000).unref()}var zs="MN_HEAP_BUMPED",Ip="MN_MAX_OLD_SPACE_MB",Sa=1048576;var qs=()=>{};async function z(e,t,r){let n=[];Ms((s)=>n.push(s));try{if(t.flags.json=!0,!(Qr in t.flags))t.flags[Qr]=!0;await e(t,r);let s=n.join("").trim();if(!s)return{};return JSON.parse(s)}finally{Ms(null)}}var dn=()=>{};function ba(e){let t=e.split(`
|
|
32
34
|
|
|
33
35
|
`)[0].trim(),r=t.split(`
|
|
34
36
|
`),n=[];for(let s of r){if(/(?:^|\s)(midnight|mn)\s+[a-z]/i.test(s))break;if(/^(Try|Run|See|Open):\s/i.test(s.trim()))break;n.push(s)}return n.join(`
|
|
35
|
-
`).trim()||t}import{randomUUID as
|
|
36
|
-
Valid networks: ${
|
|
37
|
-
Use --force to overwrite, or --output <file> to save to a different path.`);let c,d;if(o!==void 0){let h=o.replace(/^0x/,"");if(h.length!==64||!/^[0-9a-fA-F]+$/.test(h))throw Error("Seed must be a 64-character hex string (32 bytes)");c=Buffer.from(h,"hex")}else if(i!==void 0){if(!
|
|
37
|
+
`).trim()||t}import{randomUUID as Op}from"node:crypto";function va(e={}){let t=e.ttlMs??Mp,r=e.now??(()=>Date.now()),n=new Map,s=(o)=>{let i=0;for(let[a,c]of n)if(c.expiresAt<=o)n.delete(a),i+=1;return i};return{create(o){let i=r();s(i);let a=Op(),c={token:a,tool:o.tool,args:o.args,description:o.description,createdAt:i,expiresAt:i+t};return n.set(a,c),c},redeem(o){let i=n.get(o);if(!i)return null;if(i.expiresAt<=r())return n.delete(o),null;return n.delete(o),i},sweep(o=r()){return s(o)},size(){return n.size}}}var Mp=300000;var ka=()=>{};function _e(e){let t=A(e.args,"network");if(t!==void 0){if(!xe(t))throw Error(`Invalid network: "${t}"
|
|
38
|
+
Valid networks: ${xr().join(", ")}`);return t}let r=Ee(e.configDir);if(r.network&&xe(r.network))return r.network;return"undeployed"}function te(e){let t=_e(e),r=oa(t);return{name:t,config:r}}var pe=E(()=>{Ie();Bt()});var Ea={};fe(Ea,{default:()=>un});import*as xa from"fs";import*as ln from"path";import{homedir as Fp}from"os";import{generateMnemonic as Lp,mnemonicToSeedSync as Ca,validateMnemonic as Up}from"@scure/bip39";import{wordlist as Aa}from"@scure/bip39/wordlists/english.js";async function un(e){let t=_e({args:e}),r=A(e,"output"),n=A(e,"seed"),s=process.env.MN_SEED?.trim(),o=n??(s?s:void 0),i=A(e,"mnemonic");if(o!==void 0&&i!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let a=r?ln.resolve(r):ln.join(Fp(),ae,rn);if(xa.existsSync(a)&&!N(e,"force"))throw Error(`Wallet file already exists: ${a}
|
|
39
|
+
Use --force to overwrite, or --output <file> to save to a different path.`);let c,d;if(o!==void 0){let h=o.replace(/^0x/,"");if(h.length!==64||!/^[0-9a-fA-F]+$/.test(h))throw Error("Seed must be a 64-character hex string (32 bytes)");c=Buffer.from(h,"hex")}else if(i!==void 0){if(!Up(i,Aa))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");d=i,c=Buffer.from(Ca(d))}else d=Lp(Aa,256),c=Buffer.from(Ca(d));let u=Rt(c),p=u[t],f={seed:c.toString("hex"),addresses:u,createdAt:new Date().toISOString()};if(d)f.mnemonic=d;let g=cn(f,r);if(N(e,"json")){let h={addresses:u,activeAddress:p,activeNetwork:t,seed:c.toString("hex"),file:g,createdAt:f.createdAt};if(d)h.mnemonic=d;D(h);return}if(process.stdout.write(p+`
|
|
38
40
|
`),process.stderr.write(`
|
|
39
|
-
`+
|
|
41
|
+
`+W("Wallet Generated")+`
|
|
40
42
|
|
|
41
43
|
`),process.stderr.write(C("Network",t)+`
|
|
42
44
|
`),process.stderr.write(C("Address",re(p))+`
|
|
@@ -48,13 +50,13 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
48
50
|
`);process.stderr.write(M(k(" SEED (hex):"))+`
|
|
49
51
|
`),process.stderr.write(` ${c.toString("hex")}
|
|
50
52
|
|
|
51
|
-
`),process.stderr.write(
|
|
53
|
+
`),process.stderr.write(V()+`
|
|
52
54
|
`),process.stderr.write(l(" Next: midnight info | midnight balance")+`
|
|
53
55
|
|
|
54
|
-
`),process.stderr.write(
|
|
55
|
-
`)}var
|
|
56
|
+
`),process.stderr.write(H("✓")+` Wallet saved
|
|
57
|
+
`)}var Xs=E(()=>{Ge();pe();ke();ue()});var Ta={};fe(Ta,{default:()=>pn});async function pn(e){let t=ie(A(e,"wallet")),r=ce(t),n=_e({args:e}),s=r.addresses[n];if(N(e,"json")){let i={addresses:r.addresses,activeNetwork:n,activeAddress:s,createdAt:r.createdAt,file:t};if(r.shieldedAddresses)i.shieldedAddresses=r.shieldedAddresses;D(i);return}process.stdout.write(s+`
|
|
56
58
|
`),process.stderr.write(`
|
|
57
|
-
`+
|
|
59
|
+
`+W("Wallet Info")+`
|
|
58
60
|
|
|
59
61
|
`);let o=Object.keys(r.addresses);for(let i=0;i<o.length;i++){let a=o[i],c=a===n,d=r.addresses[a],u=r.shieldedAddresses?.[a],p=c?k(L(a))+l(" (active)"):a;if(process.stderr.write(` ${p}
|
|
60
62
|
`),process.stderr.write(` ${l("unshielded")} ${re(d)}
|
|
@@ -62,16 +64,16 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
62
64
|
`);else process.stderr.write(` ${l("shielded ")} ${l("(unavailable)")}
|
|
63
65
|
`);if(i<o.length-1)process.stderr.write(`
|
|
64
66
|
`)}process.stderr.write(`
|
|
65
|
-
`+
|
|
67
|
+
`+V()+`
|
|
66
68
|
|
|
67
69
|
`),process.stderr.write(` ${l("created")} ${r.createdAt}
|
|
68
70
|
`),process.stderr.write(` ${l("file ")} ${t}
|
|
69
71
|
|
|
70
|
-
`)}var
|
|
71
|
-
`)}var
|
|
72
|
+
`)}var Ys=E(()=>{ke();pe();ue();ue()});function De(){Na=!0}function B(e,t){if(!Na)return;let r=new Date().toISOString().slice(11,23);process.stderr.write(l(` [${r}] ${e}: ${t}`)+`
|
|
73
|
+
`)}var Na=!1;var ot=()=>{};function Zs(e,t={}){let r=A(e,"seed"),n=r??process.env.MN_SEED;if(n){let a=n.trim().replace(/^0x/,"");if(a.length!==64||!/^[0-9a-fA-F]+$/.test(a))throw new Z(`${r?"--seed":"MN_SEED"} must be a 64-character hex string (32 bytes)`);return{seed:Buffer.from(a,"hex"),walletPath:null,config:null}}let s=A(e,"wallet");if(s===void 0&&t.requireExplicit)throw new Z(`${t.label??"This command"} needs a seed source. Provide one of:
|
|
72
74
|
--seed <hex> 32-byte seed as 64 hex characters
|
|
73
75
|
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
74
|
-
--wallet <name> derive from a saved wallet`);let o=
|
|
76
|
+
--wallet <name> derive from a saved wallet`);let o=ie(s),i=ce(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function mn(e,t){return Zs(e,t).seed}var fn=E(()=>{Be();ke()});function Wp(e){return!jp.includes(e)}function Gt(e,t=!1){return Wp(e)||t}function gn(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var jp;var hn=E(()=>{jp=["preview","preprod"]});import{NetworkId as Qs}from"@midnight-ntwrk/wallet-sdk-abstractions";function It(e){let t=Bp[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}var Bp;var wn=E(()=>{Bp={PreProd:Qs.NetworkId.PreProd,Preview:Qs.NetworkId.Preview,Undeployed:Qs.NetworkId.Undeployed}});import Hp from"ws";function Kt(e,t,r){return new Promise((n,s)=>{let o=new Hp(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,u=!1,p=!1,f,g=()=>{let w=new Map,y=0,S=0,b=0;for(let v of i.values())if(!v.spent){y++;let R=w.get(v.tokenType)??0n;if(w.set(v.tokenType,R+v.value),v.tokenType===fr)if(v.registeredForDustGeneration)S++;else b++}return{balances:w,utxoCount:y,txCount:a,highestTxId:c,registeredUtxos:S,unregisteredUtxos:b}},h=()=>{clearTimeout(f)},m=()=>{if(!p&&u&&(c===0||d>=c))p=!0,h(),o.send(JSON.stringify({id:"1",type:"complete"})),o.close(),n(g())};o.on("open",()=>{o.send(JSON.stringify({type:"connection_init"}))}),o.on("message",(w)=>{let y=JSON.parse(w.toString());switch(y.type){case"connection_ack":o.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:Gp,variables:{address:e}}}));break;case"next":{if(y.payload?.errors){let b=y.payload.errors[0]?.message||"Unknown GraphQL error";if(!p)p=!0,h(),o.close(),s(Error(`GraphQL error: ${b}`));return}let S=y.payload?.data?.unshieldedTransactions;if(!S)return;if(S.__typename==="UnshieldedTransaction"){a++;let b=S;d=Math.max(d,b.transaction.id);for(let v of b.createdUtxos){let R=`${v.intentHash}:${v.outputIndex}`;i.set(R,{value:BigInt(v.value),tokenType:v.tokenType,spent:!1,registeredForDustGeneration:v.registeredForDustGeneration===!0})}for(let v of b.spentUtxos){let R=`${v.intentHash}:${v.outputIndex}`,P=i.get(R);if(P)P.spent=!0}if(r)r(d,c);m()}else if(S.__typename==="UnshieldedTransactionsProgress")c=S.highestTransactionId,u=!0,m();break}case"error":if(!p)p=!0,h(),o.close(),s(Error(`GraphQL subscription error: ${JSON.stringify(y.payload)}`));break;case"complete":break}}),o.on("error",(w)=>{if(!p){p=!0,h();let y=w.message?.trim()?w.message:`unable to reach ${t} (connection refused, DNS, or TLS error). Is the indexer running?`;s(Error(`WebSocket connection failed: ${y}`))}}),o.on("close",()=>{if(!p)p=!0,h(),s(Error(`Indexer closed the connection before balance sync completed. Indexer: ${t}`))}),f=setTimeout(()=>{if(!p)p=!0,o.close(),s(Error(`Balance check timed out after ${$s/1000}s. Indexer: ${t}`))},$s)})}function Dr(e){return e===fr}var Gp=`
|
|
75
77
|
subscription UnshieldedTransactions($address: UnshieldedAddress!) {
|
|
76
78
|
unshieldedTransactions(address: $address) {
|
|
77
79
|
__typename
|
|
@@ -85,10 +87,10 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
85
87
|
}
|
|
86
88
|
}
|
|
87
89
|
}
|
|
88
|
-
`;var
|
|
89
|
-
`),h=await p()}}else
|
|
90
|
+
`;var Pr=()=>{};import{existsSync as Or,mkdirSync as Kp,writeFileSync as Jp,readFileSync as Ra,unlinkSync as yn,readdirSync as eo,renameSync as Vp}from"node:fs";import{join as _t,dirname as zp}from"node:path";import{homedir as $a}from"node:os";import{randomBytes as qp}from"node:crypto";import*as Sn from"@midnight-ntwrk/ledger-v8";function to(e){return e.toString(16).padStart(64,"0")}function Ze(e){let t=mt(e),r=Sn.DustSecretKey.fromSeed(t);return to(r.publicKey)}function ro(e,t){let r=t??_t($a(),ae,$e);return _t(r,e)}function no(e,t,r){let n=t.slice(0,20);return _t(ro(e,r),`dust-${n}.json`)}function Mr(e,t,r){let n=no(e,t,r);if(!Or(n))return null;try{let s=JSON.parse(Ra(n,"utf-8"));if(s.version!==Ia)return null;if(s.network!==e)return null;if(s.dustPublicKeyHex!==t)return null;if(typeof s.lastAppliedEventId!=="number")return null;if(typeof s.dustState!=="string")return null;if(!Array.isArray(s.ownedGenerationIndices))return null;if(typeof s.generationFrontier!=="number")return null;let o=Buffer.from(s.dustState,"hex");return{state:Sn.DustLocalState.deserialize(o),lastAppliedEventId:s.lastAppliedEventId,retention:{ownedGenerationIndices:s.ownedGenerationIndices,generationFrontier:s.generationFrontier}}}catch{return null}}function so(e,t,r,n,s,o,i=Xp){let a={version:Ia,network:e,dustPublicKeyHex:t,lastAppliedEventId:n,timestamp:new Date().toISOString(),dustState:Buffer.from(r.serialize()).toString("hex"),ownedGenerationIndices:i.ownedGenerationIndices,generationFrontier:i.generationFrontier,...o?{chainId:o}:{}},c=no(e,t,s),d=zp(c);if(!Or(d))Kp(d,{recursive:!0,mode:Se});let u=c+`.tmp.${qp(4).toString("hex")}`;try{Jp(u,JSON.stringify(a),{mode:be}),Vp(u,c)}catch(p){try{yn(u)}catch{}throw p}}function _a(e,t,r){if(!t)return[];let n=ro(e,r);if(!Or(n))return[];let s=[],o;try{o=eo(n)}catch{return[]}for(let i of o){if(!i.startsWith("dust-")||!i.endsWith(".json"))continue;let a=_t(n,i);try{let c=JSON.parse(Ra(a,"utf-8"));if(!c.chainId)continue;if(c.chainId!==t)yn(a),s.push(a)}catch{}}return s}function gt(e,t,r){let n=r??_t($a(),ae,$e);if(e&&t){let o=no(e,t,r);try{yn(o)}catch{}return}let s=(o)=>{if(!Or(o))return;try{for(let i of eo(o))if(i.startsWith("dust-")&&i.endsWith(".json"))try{yn(_t(o,i))}catch{}}catch{}};if(e){s(ro(e,r));return}if(!Or(n))return;try{for(let o of eo(n))s(_t(n,o))}catch{}}var Ia=2,Xp;var Dt=E(()=>{Nt();Xp={ownedGenerationIndices:[],generationFrontier:0}});import{ShieldedWallet as Da}from"@midnight-ntwrk/wallet-sdk-shielded";import{UnshieldedWallet as Pa,createKeystore as Yp,PublicKey as Zp}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{DustWallet as Oa}from"@midnight-ntwrk/wallet-sdk-dust-wallet";import{WalletFacade as Ma}from"@midnight-ntwrk/wallet-sdk-facade";import*as Jt from"@midnight-ntwrk/ledger-v8";import{NetworkId as oo,InMemoryTransactionHistoryStorage as Qp,TransactionHistoryStorage as em}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as Te from"rxjs";async function Qe(e,t,r){let n=tm[t.networkId];if(n===void 0)throw Error(`Unknown networkId: ${t.networkId}`);B("facade",`Building facade for network ${t.networkId}`),B("facade",`Node: ${t.node}`),B("facade",`Indexer: ${t.indexerWS}`),B("facade",`Proof server: ${t.proofServer}`);let s=Tt(e),o=ua(e),i=mt(e),a=Jt.ZswapSecretKeys.fromSeed(s),c=Jt.DustSecretKey.fromSeed(i),d=Yp(o,n),u={networkId:n,indexerClientConnection:{indexerHttpUrl:t.indexer,indexerWsUrl:t.indexerWS},costParameters:{additionalFeeOverhead:Di,feeBlocksMargin:Pi},txHistoryStorage:new Qp(em.TransactionHistoryCommonSchema),provingServerUrl:new URL(t.proofServer),relayURL:new URL(t.node)},p=()=>Ma.init({configuration:u,shielded:(m)=>Da(m).startWithSecretKeys(a),unshielded:(m)=>Pa(m).startWithPublicKey(Zp.fromKeyStore(d)),dust:(m)=>Oa(m).startWithSecretKey(c,Jt.LedgerParameters.initialParameters().dust)}),f=r?rm(r,t,c.publicKey):null,g=!1,h;if(f){B("facade","Restoring from cache...");try{h=await Ma.init({configuration:u,shielded:(m)=>Da(m).restore(f.shielded),unshielded:(m)=>Pa(m).restore(f.unshielded),dust:(m)=>Oa(m).restore(f.dust)}),g=!0,B("facade","Cache restore successful")}catch(m){B("facade",`Cache restore failed: ${m.message}`),process.stderr.write(` Cache restore failed, building from scratch: ${m.message}
|
|
91
|
+
`),h=await p()}}else B("facade","No cache, building fresh"),h=await p();return{facade:h,keystore:d,zswapSecretKeys:a,dustSecretKey:c,restoredFromCache:g}}function ao(e,t){let r=JSON.parse(e);return r.state=Buffer.from(t.state.serialize()).toString("hex"),r.offset=t.lastAppliedEventId.toString(),JSON.stringify(r)}function rm(e,t,r){try{let n=t.networkId.toLowerCase(),s=to(r),o=Mr(n,s);if(!o)return e;let i=JSON.parse(e.dust),a=i.offset!==void 0?Number(i.offset):-1;if(a>=o.lastAppliedEventId)return B("facade",`Facade dust offset=${a} >= dust-direct offset=${o.lastAppliedEventId}; skipping bridge`),e;return B("facade",`Bridged dust-direct cache (facade offset ${a} → dust-direct offset ${o.lastAppliedEventId})`),{...e,dust:ao(e.dust,o)}}catch(n){return B("facade",`Dust-direct bridge skipped: ${n.message}`),e}}function io(e,t="full"){let r=e.unshielded?.progress?.isStrictlyComplete()??!1,n=t!=="no-dust",s=!n;if(n){if(s=e.dust?.state?.progress?.isStrictlyComplete()??!1,!s)try{let i=e.dust?.state?.progress;if(i&&i.highestRelevantWalletIndex>0&&i.appliedIndex>=i.highestRelevantWalletIndex)s=!0;if(i&&i.highestRelevantWalletIndex===0&&i.appliedIndex===0&&r)s=!0}catch{}}if(t==="lite")return r&&s;let o=e.shielded?.state?.progress?.isStrictlyComplete()??!1;if(!o&&r)try{let i=e.shielded?.state?.progress;if(i&&i.highestRelevantWalletIndex===0&&i.appliedIndex===0)o=!0}catch{}return o&&r&&s}function nm(e){if(e.dust?.state?.progress?.isStrictlyComplete())return!1;try{let t=e.dust?.state?.progress;if(t&&t.highestRelevantWalletIndex>0&&t.appliedIndex>=t.highestRelevantWalletIndex)return!1;if(t&&t.highestRelevantWalletIndex===0&&t.appliedIndex===0&&e.unshielded?.progress?.isStrictlyComplete())return!1}catch{}return!0}async function ht(e,t={}){let{onProgress:r,onSyncDetail:n,timeoutMs:s,syncMode:o="full",requireStrictSync:i=!1}=t,{facade:a,zswapSecretKeys:c,dustSecretKey:d}=e;B("sync","Starting facade (connecting to node and indexer)..."),await a.start(c,d),B("sync","Facade started, subscribing to state...");let u=s??Li;B("sync",`Sync timeout: ${u/1000}s, mode: ${o}`);let p=!i&&e.restoredFromCache,f=Date.now();return new Promise((g,h)=>{let m=!1,w=0,y="",S=null,b=setTimeout(()=>{if(!m){if(B("sync",`Sync timed out after ${u/1000}s (${w} emissions)`),S)try{let v=S.unshielded?.progress;B("sync",` unshielded: applied=${v?.appliedId} highest=${v?.highestTransactionId} complete=${v?.isStrictlyComplete()}`);let R=S.dust?.state?.progress;if(B("sync",` dust: applied=${R?.appliedIndex} highest=${R?.highestRelevantWalletIndex} complete=${R?.isStrictlyComplete?.()} connected=${R?.isConnected}`),o==="full"){let P=S.shielded?.state?.progress;B("sync",` shielded: complete=${P?.isStrictlyComplete()}`)}}catch{}h(Error("Wallet sync timed out"))}},u);e.keepAlive=a.state().subscribe({next:(v)=>{if(m)return;if(w++,S=v,e.restoredFromCache){let P=om(v);if(P){m=!0,clearTimeout(b),B("sync",`Stale cache detected: ${P}`),h(new bn(P));return}}if(r){let P=v.unshielded.progress;if(P){let q=Number(P.appliedId),U=Number(P.highestTransactionId);r(Math.min(q,U),U)}}let R=[];try{if((o==="full"||o==="no-dust")&&!v.shielded?.state?.progress?.isStrictlyComplete())R.push("shielded");if(o!=="no-dust"&&nm(v))R.push("dust");if(!v.unshielded?.progress?.isStrictlyComplete())R.push("unshielded")}catch{}if(R.length>0){n?.(R.join(", "));let P=R.join(",");if(w===1||P!==y||w%100===0)B("sync",`Waiting on: ${R.join(", ")} (emission #${w})`),y=P}if(io(v,o)){m=!0,clearTimeout(b),B("sync",`Sync complete after ${w} emissions`),g(v);return}if(p){let P=Date.now()-f;if(P>=sm&&io(v,"no-dust"))m=!0,clearTimeout(b),B("sync",`Sync resolved via cached-restore grace (${P}ms, ${w} emissions)`),g(v)}},error:(v)=>{if(!m)B("sync",`Sync error: ${v.message}`),clearTimeout(b),h(v)}})})}function om(e){try{let t=e.unshielded?.progress;if(!t)return;let r=Number(t.appliedId??0),n=Number(t.highestTransactionId??0);if(n>0&&r>n)return`unshielded cache applied=${r} but chain highest=${n}.`}catch{}return}async function Fa(e){let t=(r)=>{let n=r.unshielded?.progress?.isStrictlyComplete()??!1,s=r.dust?.state?.progress?.isStrictlyComplete()??!1;return n&&s};try{return await Te.firstValueFrom(e.facade.state().pipe(Te.filter(t),Te.timeout(15000)))}catch{return await Te.firstValueFrom(e.facade.state())}}async function Vt(e,t=60000){let r=(n)=>{try{let s=n.dust;return s?.availableCoins?.length>0||s?.balance(new Date)>0n}catch{return!1}};try{return await Te.firstValueFrom(e.facade.state().pipe(Te.filter(r),Te.timeout(t)))}catch{return await Te.firstValueFrom(e.facade.state())}}async function co(e,t="full"){return Te.firstValueFrom(e.facade.state().pipe(Te.filter((r)=>io(r,t)),Te.timeout(Ui)))}async function Ue(e){e.keepAlive?.unsubscribe(),await Promise.race([e.facade.stop(),new Promise((t)=>setTimeout(t,5000))])}function he(e){let t=(n)=>{let s=n?._tag;if(typeof s==="string"&&s.startsWith("Wallet.")){let o=n?.message??"transient error";e?.(s,o);return}r("Unhandled rejection:",n),process.exit(1)},r=console.error;return console.error=(...n)=>{let s=n[0];if(typeof s==="object"&&s?._tag?.startsWith("Wallet.")){e?.(s._tag,s?.message??"transient error");return}if(typeof s==="string"&&s.startsWith("Wallet.")){e?.("Wallet.Sync","transient error");return}r(...n)},process.on("unhandledRejection",t),()=>{process.removeListener("unhandledRejection",t),console.error=r}}var tm,sm=1e4,bn;var Ke=E(()=>{Nt();Dt();ot();tm={PreProd:oo.NetworkId.PreProd,Preview:oo.NetworkId.Preview,Undeployed:oo.NetworkId.Undeployed};bn=class bn extends Error{code="STALE_CACHE";constructor(e){super(`Cached wallet state is stale (from a previous chain). ${e}
|
|
90
92
|
Run: midnight cache clear --wallet <name> --network <name>
|
|
91
|
-
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function
|
|
93
|
+
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function im(e){let t=e;while(t){let r=String(t?.message??"").toLowerCase();if(r.includes("submission error"))return!0;if(r.includes("transaction")&&r.includes("invalid"))return!0;if(r.includes("138"))return!0;let n=t?._tag;if(n==="TransactionInvalidError"||n==="SubmissionError")return!0;t=t.cause}return!1}function vn(e){let t=e?.message?.toLowerCase()??"";return t.includes("not enough dust")||t.includes("dust generated")||t.includes("insufficient funds")||t.includes("no dust tokens")||im(e)}function Fr(e){let t=e?.message?.toLowerCase()??"";if(e?._tag==="Wallet.InsufficientFunds")return!0;return t==="insufficient funds"||t.startsWith("insufficient funds")}import{existsSync as Ur,mkdirSync as am,writeFileSync as cm,readFileSync as La,unlinkSync as Lr,readdirSync as kn,renameSync as dm}from"node:fs";import{join as et,dirname as lm}from"node:path";import{homedir as lo}from"node:os";import{randomBytes as um}from"node:crypto";function uo(e,t,r){let n=r??et(lo(),ae,$e),s=e.slice(0,20);return et(n,t,`${s}.json`)}function wt(e,t,r){let n=uo(e,t,r);if(!Ur(n))return null;try{let s=La(n,"utf-8"),o=JSON.parse(s);if(o.version!==_s)return null;if(o.network!==t)return null;if(o.address!==e)return null;if(!o.wallets||typeof o.wallets.shielded!=="string"||typeof o.wallets.unshielded!=="string"||typeof o.wallets.dust!=="string")return null;return o.wallets}catch{return null}}async function je(e,t,r,n,s){let[o,i,a]=await Promise.all([r.shielded.serializeState(),r.unshielded.serializeState(),r.dust.serializeState()]),c={version:_s,network:t,address:e,timestamp:new Date().toISOString(),wallets:{shielded:o,unshielded:i,dust:a},...s?{chainId:s}:{}},d=uo(e,t,n),u=lm(d);if(!Ur(u))am(u,{recursive:!0,mode:Se});let p=d+`.tmp.${um(4).toString("hex")}`;try{cm(p,JSON.stringify(c),{mode:be}),dm(p,d)}catch(f){try{Lr(p)}catch{}throw f}}function Ua(e,t,r){if(!t)return[];let n=r??et(lo(),ae,$e),s=et(n,e);if(!Ur(s))return[];let o=[],i;try{i=kn(s)}catch{return[]}for(let a of i){if(!a.endsWith(".json"))continue;let c=et(s,a);try{let d=JSON.parse(La(c,"utf-8"));if(!d.chainId)continue;if(d.chainId!==t)Lr(c),o.push(c)}catch{}}return o}function Je(e,t,r){let n=r??et(lo(),ae,$e);if(e&&t){let s=uo(e,t,r);try{Lr(s)}catch{}return}if(t){let s=et(n,t);if(!Ur(s))return;try{for(let o of kn(s))if(o.endsWith(".json"))Lr(et(s,o))}catch{}return}if(!Ur(n))return;try{for(let s of kn(n)){let o=et(n,s);try{for(let i of kn(o))if(i.endsWith(".json"))Lr(et(o,i))}catch{}}}catch{}}var yt=()=>{};import pm from"ws";async function zt(e,t,r=[]){let n=e.timeoutMs??mm;return new Promise((s,o)=>{let i=new pm(e.url),a=!1,c=(u)=>{if(!a)a=!0,u()},d=setTimeout(()=>{c(()=>{try{i.close()}catch{}o(Error(`RPC ${t} timed out after ${n}ms`))})},n);i.on("open",()=>{try{i.send(JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:r}))}catch(u){clearTimeout(d),c(()=>o(u instanceof Error?u:Error(String(u))))}}),i.on("message",(u)=>{clearTimeout(d),c(()=>{try{let p=JSON.parse(u.toString());try{i.close()}catch{}if(p.error)o(Error(`RPC ${t}: ${p.error.message}`));else s(p.result)}catch(p){o(p instanceof Error?p:Error(String(p)))}})}),i.on("error",(u)=>{clearTimeout(d),c(()=>o(u instanceof Error?u:Error(String(u))))})})}var mm=5000;var Cn=()=>{};async function An(e){let t=ja.get(e);if(t&&Date.now()-t.fetchedAt<fm)return t.hash;try{let r=await zt({url:e,timeoutMs:5000},"chain_getBlockHash",[0]);if(typeof r!=="string"||!r.startsWith("0x"))return null;return ja.set(e,{hash:r,fetchedAt:Date.now()}),r}catch{return null}}var ja,fm=60000;var po=E(()=>{Cn();ja=new Map});function gm(e,t){if(t<=0n)return[];let r=[...new Set(e)].filter((o)=>o>=0n&&o<t).sort((o,i)=>o<i?-1:o>i?1:0),n=[],s=-1n;for(let o of r){if(o>s+1n)n.push([s+1n,o-1n]);s=o}if(t-1n>s)n.push([s+1n,t-1n]);return n}function xn(e,t,r){let n=gm(t,r);if(n.length===0)return{state:e,collapsed:!1,rangesCollapsed:0,reason:"nothing-foreign"};let s=e.syncTime instanceof Date?e.syncTime:new Date(String(e.syncTime)),o,i;try{o=e.walletBalance(s),i=e.generatingTreeRoot()}catch(c){return{state:e,collapsed:!1,rangesCollapsed:0,reason:`no-reference: ${c.message}`}}let a=e;try{for(let[c,d]of n)a=a.collapseGenerationTree(c,d)}catch(c){return{state:e,collapsed:!1,rangesCollapsed:0,reason:`collapse-threw: ${c.message}`}}try{if(a.walletBalance(s)!==o||a.generatingTreeRoot()!==i)return{state:e,collapsed:!1,rangesCollapsed:0,reason:"guard-mismatch"};for(let c of a.utxos)if(a.generationInfo(c)===void 0)return{state:e,collapsed:!1,rangesCollapsed:0,reason:"guard-utxo-generation-missing"}}catch(c){return{state:e,collapsed:!1,rangesCollapsed:0,reason:`guard-threw: ${c.message}`}}return{state:a,collapsed:!0,rangesCollapsed:n.length}}import hm from"ws";function En(e,t){let{query:r,variables:n,onNext:s,buildResult:o,timeoutMs:i,idleMs:a,idleBeforeFirstEvent:c,initialSilenceMs:d,signal:u}=t;return new Promise((p,f)=>{let g=new hm(e,["graphql-transport-ws"]),h=!1,m=!1,w,y,S,b=()=>{if(clearTimeout(w),y)clearTimeout(y);if(S)clearTimeout(S);try{g.close()}catch{}u?.removeEventListener("abort",P)},v=(U,X)=>{if(m)return;m=!0,b();try{p(o(X))}catch(O){f(O instanceof Error?O:Error(String(O)))}},R=(U)=>{if(m)return;m=!0,b(),f(U)},P=()=>R(Error("Operation cancelled"));u?.addEventListener("abort",P,{once:!0});let q=()=>{if(y)clearTimeout(y);y=setTimeout(()=>{if(!m&&(h||c))v("idle",!1)},a)};g.on("open",()=>{g.send(JSON.stringify({type:"connection_init"}))}),g.on("message",(U)=>{let X;try{X=JSON.parse(U.toString())}catch{return}if(X.type==="connection_ack"){if(g.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:r,variables:n}})),c)q();if(d&&d>0)S=setTimeout(()=>{if(!h&&!m)v("initial-silence",!1)},d);return}if(X.type==="error"){R(Error(`GraphQL subscription error: ${JSON.stringify(X.payload)?.slice(0,300)}`));return}if(X.type!=="next")return;if(X.payload?.errors){R(Error(`GraphQL error: ${X.payload.errors[0]?.message||"unknown"}`));return}if(h=!0,S)clearTimeout(S),S=void 0;let O;try{O=s(X.payload?.data)}catch(F){R(F instanceof Error?F:Error(String(F)));return}if(q(),O)v("caught-up",!1)}),g.on("error",(U)=>R(Error(`WebSocket error: ${U.message}`))),g.on("close",()=>{if(m)return;v(h?"closed-early":"graceful-close",h)}),w=setTimeout(()=>v("timeout",!0),i)})}var mo=()=>{};import*as qt from"@midnight-ntwrk/ledger-v8";function ym(){let e=new qt.DustParameters(Oi,Mi,Fi);return new qt.DustLocalState(e)}function Wa(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:u=0,initialRetention:p,collapse:f}=r,g=f!==!1&&process.env[fo]!=="1",h=500,m=d??ym(),w=[],y=e.publicKey,S=new Set((p?.ownedGenerationIndices??[]).map(BigInt)),b=BigInt(p?.generationFrontier??0),v=(O)=>{let F=O.content;if(F?.tag!=="dustInitialUtxo"||F.generationIndex===void 0)return;let Q=F.generationIndex;if(Q+1n>b)b=Q+1n;if(F.generation?.owner===y)S.add(Q)},R=()=>({ownedGenerationIndices:[...S].map(Number),generationFrontier:Number(b)}),P=0,q=u-1,U=-1,X=()=>{if(w.length===0)return;if(m=m.replayEvents(e,w),P+=w.length,w.length=0,g)m=xn(m,S,b).state;if(s&&q>=0)try{s(m,q,R())}catch{}};return En(t,{query:wm,variables:{id:u},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(O)=>{let F=O?.dustLedgerEvents;if(!F)return!1;let Q;try{Q=qt.Event.deserialize(Buffer.from(F.raw,"hex"))}catch(de){throw Error(`Failed to deserialize dust event ${F.id}: ${de.message}`)}if(v(Q),w.push(Q),q=F.id,F.maxId>U)U=F.maxId;if(w.length>=500)try{X()}catch(de){throw Error(`Failed applying dust events: ${de.message}`)}return n?.(P+w.length,U),q>=U},buildResult:(O)=>{try{X();let F=new Date;return m=m.processTtls(F),{balance:m.walletBalance(F),availableCoins:m.utxos.length,eventCount:P,ownedUtxoCount:m.utxos.length,syncTime:m.syncTime,state:m,retention:R(),lastAppliedEventId:q,partial:O}}catch(F){throw Error(`Failed to build dust state: ${F.message}`)}}})}var fo="MN_DISABLE_DUST_COLLAPSE",wm=`
|
|
92
94
|
subscription DustLedgerEvents($id: Int) {
|
|
93
95
|
dustLedgerEvents(id: $id) {
|
|
94
96
|
type: __typename
|
|
@@ -97,9 +99,9 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
97
99
|
maxId
|
|
98
100
|
}
|
|
99
101
|
}
|
|
100
|
-
`;var
|
|
101
|
-
`),p.stdin.end();let h="",m="";p.stdout.on("data",(w)=>{h+=w.toString()}),p.stderr.on("data",(w)=>{let y=w.toString();m=(m+y).slice(-2000);for(let S of y.matchAll(/applied (\d+) \/ (\d+)/g))r.onProgress?.(Number(S[1]),Number(S[2]))}),p.on("error",(w)=>{r.signal?.removeEventListener("abort",f),s(w)}),p.on("close",(w)=>{if(r.signal?.removeEventListener("abort",f),w!==0&&!
|
|
102
|
-
`).filter(Boolean).pop(),S=y?JSON.parse(y):JSON.parse(
|
|
102
|
+
`;var go=E(()=>{mo()});import{spawn as Sm}from"node:child_process";import{existsSync as St,mkdirSync as bm,readFileSync as Ka,readdirSync as Ba,unlinkSync as Ha,writeFileSync as vm}from"node:fs";import{homedir as Ja}from"node:os";import{dirname as Ga,join as it}from"node:path";import{fileURLToPath as km}from"node:url";import*as Va from"@midnight-ntwrk/ledger-v8";function za(){let e=process.env.MN_DUST_SYNC_BIN;if(e&&St(e))return e;let t=process.platform==="win32"?"dust-sync.exe":"dust-sync",r=Ga(km(import.meta.url));for(let n of[["..",".."],[".."]]){let s=it(r,...n,"sidecar","dust-sync","target","release",t);if(St(s))return s}try{let n=`@nel349/dust-sync-${process.platform}-${process.arch}`,s=Cm(import.meta.url),o=it(Ga(s.resolve(`${n}/package.json`)),t);if(St(o))return o}catch{}return null}function Cm(e){return globalThis.require??xs("node:module").createRequire(e)}function qa(){if(process.env.MN_DISABLE_NATIVE_DUST==="1")return!1;return za()!==null}function Am(e,t,r){if(e+1>=t)return"existing";if(r)return"seed";return"fresh"}function xm(e){if(!St(e))return-2;try{let t=JSON.parse(Ka(e,"utf-8"));return typeof t.last_applied_event_id==="number"?t.last_applied_event_id:-2}catch{return-2}}function Em(e,t){let r=it(Ja(),ae,$e,e);if(!St(r))bm(r,{recursive:!0,mode:Se});return it(r,`dust-native-${t.slice(0,20)}.json`)}function Tn(e,t){let r=it(Ja(),ae,$e);if(e&&t){try{Ha(it(r,e,`dust-native-${t.slice(0,20)}.json`))}catch{}return}let n=(s)=>{if(!St(s))return;try{for(let o of Ba(s))if(o.startsWith("dust-native-")&&o.endsWith(".json"))try{Ha(it(s,o))}catch{}}catch{}};if(e){n(it(r,e));return}if(!St(r))return;try{for(let s of Ba(r))n(it(r,s))}catch{}}function Xa(e,t,r){return new Promise((n,s)=>{let o=za();if(!o){s(Error("dust-sync sidecar not found"));return}let i=t.networkId.toLowerCase(),a=Ze(e),c=Em(i,a),d=["--indexer-ws",t.indexerWS,"--out",c],u=Am(xm(c),r.startFromId,!!r.initialState);if(u==="seed"){let w={dust_state:Buffer.from(r.initialState.serialize()).toString("hex"),last_applied_event_id:r.startFromId-1,owned_generation_indices:r.initialRetention?.ownedGenerationIndices??[],generation_frontier:r.initialRetention?.generationFrontier??0,balance:"0",available_coins:0,events_applied:0,partial:!0};vm(c,JSON.stringify(w),{mode:be})}if(u!=="fresh")d.push("--resume",c);let p=Sm(o,d,{stdio:["pipe","pipe","pipe"]}),f=()=>{try{p.kill("SIGINT")}catch{}};r.signal?.addEventListener("abort",f,{once:!0}),p.stdin.on("error",()=>{});let g=Buffer.from(mt(e)).toString("hex");p.stdin.write(g+`
|
|
103
|
+
`),p.stdin.end();let h="",m="";p.stdout.on("data",(w)=>{h+=w.toString()}),p.stderr.on("data",(w)=>{let y=w.toString();m=(m+y).slice(-2000);for(let S of y.matchAll(/applied (\d+) \/ (\d+)/g))r.onProgress?.(Number(S[1]),Number(S[2]))}),p.on("error",(w)=>{r.signal?.removeEventListener("abort",f),s(w)}),p.on("close",(w)=>{if(r.signal?.removeEventListener("abort",f),w!==0&&!St(c)){s(Error(`dust-sync exited ${w}: ${m.trim().slice(-300)}`));return}try{let y=h.trim().split(`
|
|
104
|
+
`).filter(Boolean).pop(),S=y?JSON.parse(y):JSON.parse(Ka(c,"utf-8"));n(Tm(S))}catch(y){s(Error(`dust-sync output parse failed: ${y.message}`))}})})}function Tm(e){let t=new Date,r=Va.DustLocalState.deserialize(new Uint8Array(Buffer.from(e.dust_state,"hex")));if(process.env[fo]!=="1"){let s=new Set(e.owned_generation_indices.map((o)=>BigInt(o)));r=xn(r,s,BigInt(e.generation_frontier)).state}r=r.processTtls(t);let n=r.utxos.length;return{balance:r.walletBalance(t),availableCoins:n,eventCount:e.events_applied,ownedUtxoCount:n,syncTime:r.syncTime instanceof Date?r.syncTime:new Date(String(r.syncTime)),state:r,retention:{ownedGenerationIndices:e.owned_generation_indices,generationFrontier:e.generation_frontier},lastAppliedEventId:e.last_applied_event_id,partial:e.partial}}var ho=E(()=>{Nt();go();Dt()});import*as Za from"@midnight-ntwrk/ledger-v8";class Qa{now;fetchTip;fetchUnshielded;fetchDust;fetchChainId;cacheDir;dustMemo=new Map;unshieldedMemo=new Map;tipMemo=new Map;constructor(e={}){this.now=e.now??Date.now,this.fetchTip=e.fetchTip??Dm,this.fetchUnshielded=e.fetchUnshielded??Pm,this.fetchDust=e.fetchDust??Mm,this.fetchChainId=e.fetchChainId??An,this.cacheDir=e.cacheDir}async dust(e,t,r={}){let n=Nn(t),s=Ze(e),o=`${n}:${s}`;if(!r.forceFresh){let h=await this.tryMemo(o,t,this.dustMemo,r.signal);if(h)return{...h,fromCache:!0,eventsApplied:0}}let i=await this.fetchChainId(t.node).catch(()=>null);_a(n,i,this.cacheDir);let a=i??void 0,c=r.forceFresh?null:Mr(n,s,this.cacheDir),d=c!==null,u=0,p=c?.lastAppliedEventId??-1,f=null;for(let h=0;h<Rm;h++){if(r.signal?.aborted)throw Error("Operation cancelled");let m=c?c.lastAppliedEventId+1:0;if(r.onStatus?.(h>0?`Resuming dust from event ${m} (continuation ${h+1})…`:c?`Resuming dust from event ${m}…`:"Reading dust events…"),f=await this.fetchDust(e,t,{startFromId:m,initialState:c?.state,initialRetention:c?.retention,signal:r.signal,onProgress:(w,y)=>{let S=Math.max(1,y+1-m);r.onStatus?.(`Reading dust events… ${w}/${S}`),r.onProgress?.(w,y)},onCheckpoint:(w,y,S)=>{try{so(n,s,w,y,this.cacheDir,a,S)}catch{}}}),p=f.lastAppliedEventId>=0?f.lastAppliedEventId:c?.lastAppliedEventId??-1,f.lastAppliedEventId>=0||!c)try{so(n,s,f.state,p,this.cacheDir,a,f.retention)}catch{}if(u+=f.eventCount,!f.partial)break;c=Mr(n,s,this.cacheDir)}if(!f)throw Error("Dust sync exhausted retries without producing a result");let g={state:f.state,balance:f.balance,availableCoins:f.availableCoins,ownedUtxoCount:f.ownedUtxoCount,syncTime:f.syncTime,fromCache:d,eventsApplied:u,lastAppliedEventId:p,partial:f.partial,fetchedAt:this.now()};return await this.memoize(this.dustMemo,o,g,t,r.signal),g}async unshielded(e,t,r={}){let n=Nn(t),s=typeof e==="string"?e:ve(e,n),o=`${n}:${s}`;if(!r.forceFresh){let c=await this.tryMemo(o,t,this.unshieldedMemo,r.signal);if(c)return{...c,fromCache:!0}}let a={...await this.fetchUnshielded(s,t,r.onProgress),fromCache:!1,fetchedAt:this.now()};return await this.memoize(this.unshieldedMemo,o,a,t,r.signal),a}async withFacade(e,t,r,n={}){let s=n.syncMode??"full",o=n.requireStrictSync??!0,i=o&&!n.readOnly,a=Nn(t),c=ve(e,a),d=t.networkId!=="Undeployed",u=n.syncTimeoutMs??(d?Im:$m),p=await this.fetchChainId(t.node).catch(()=>null);Ua(a,p,this.cacheDir);let f=p??void 0;if(i&&!n.noPrime&&!n.forceFresh)try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch(y){n.onSyncWarning?.("PrePrime",y.message)}let g,h,m=!1,w=async()=>{if(m||!g)return;m=!0;try{await Ue(g)}catch{}};try{for(let b=1;b<=jr;b++){if(n.signal?.aborted)throw Error("Operation cancelled");let v=n.forceFresh?null:wt(c,a,this.cacheDir);g=await Qe(e,t,v);try{h=await ht(g,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:u,syncMode:s,requireStrictSync:o});break}catch(R){if(n.signal?.aborted)throw Error("Operation cancelled");if(R instanceof bn&&b<jr&&i){n.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${b+1}/${jr})...`),await Ue(g).catch(()=>{}),g=void 0,Je(c,a,this.cacheDir),gt(a,Ze(e),this.cacheDir);try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch{}continue}if(b<jr&&String(R?.message??"").includes("timed out")){try{await je(c,a,g.facade,this.cacheDir,f)}catch{}n.onStatus?.(`Sync timed out, retrying (attempt ${b+1}/${jr})...`),await Ue(g).catch(()=>{}),g=void 0;continue}throw R}}if(!g||!h)throw Error("Sync failed: no facade state after retries");let y,S=0;while(!0){if(S++,n.signal?.aborted)throw Error("Operation cancelled");try{y=await r({bundle:g,state:h});break}catch(b){if(!(i&&S<Ya&&Fr(b)))throw b;if(n.onStatus?.(`Refreshing wallet state (attempt ${S+1}/${Ya})...`),await Ue(g).catch(()=>{}),g=void 0,await new Promise((P)=>setTimeout(P,_m)),n.signal?.aborted)throw Error("Operation cancelled");let R=wt(c,a,this.cacheDir);g=await Qe(e,t,R),h=await ht(g,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:u,syncMode:s,requireStrictSync:o})}}if(!n.skipAutoSave)try{await je(c,a,g.facade,this.cacheDir,f)}catch{}if(!n.readOnly)this.invalidate({network:t,seed:e});return y}finally{await w()}}invalidate(e){let t=Nn(e.network),r=e.kinds??["dust","unshielded","facade"];if(r.includes("dust"))if(e.seed){let n=Ze(e.seed);this.dustMemo.delete(`${t}:${n}`)}else this.deleteByPrefix(this.dustMemo,`${t}:`);if(r.includes("unshielded")){let n=e.address??(e.seed?ve(e.seed,t):null);if(n)this.unshieldedMemo.delete(`${t}:${n}`);else this.deleteByPrefix(this.unshieldedMemo,`${t}:`)}if(r.includes("facade")&&e.seed){let n=ve(e.seed,t);try{Je(n,t,this.cacheDir)}catch{}}}resetTipMemo(){this.tipMemo.clear()}async tryMemo(e,t,r,n){let s=r.get(e);if(!s)return null;let o;try{o=await this.getTip(t,n)}catch{return s.value}if(o===s.tipAtFetch)return s.value;return r.delete(e),null}async memoize(e,t,r,n,s){try{let o=await this.getTip(n,s);e.set(t,{value:r,fetchedAt:this.now(),tipAtFetch:o})}catch{B("repo",`tip unavailable; skipping memo for ${t}`)}}async getTip(e,t){let r=this.tipMemo.get(e.networkId);if(r&&this.now()-r.fetchedAt<Nm)return r.tip;let n=await this.fetchTip(e,t);return this.tipMemo.set(e.networkId,{tip:n,fetchedAt:this.now()}),n}deleteByPrefix(e,t){for(let r of e.keys())if(r.startsWith(t))e.delete(r)}}function Dm(e){return zt({url:e.node,timeoutMs:3000},"chain_getBlockHash",[])}function Pm(e,t,r){return Kt(e,t.indexerWS,r)}function Om(e,t,r){let n=mt(e),s=Za.DustSecretKey.fromSeed(n);return Wa(s,t.indexerWS,r)}async function Mm(e,t,r){if(qa())try{return await Xa(e,t,r)}catch(n){B("dust",`native sidecar failed, using WASM: ${n.message}`)}return Om(e,t,r)}function Nn(e){let t=e.networkId.toLowerCase();if(xe(t))return t;throw Error(`Unsupported network: ${e.networkId}`)}function me(){if(!wo)wo=new Qa;return wo}var Nm=5000,Rm=6,$m=30000,Im=120000,jr=3,Ya=5,_m=5000,wo=null;var at=E(()=>{Ie();Ke();Dt();yt();po();Pr();go();ho();ot();Cn();Nt();Ge()});import*as Xt from"@midnight-ntwrk/ledger-v8";function Lm(e){let t=Xt.unshieldedToken().raw,r=0n,n=0;for(let s of e.coins)if(s.type===t)r+=s.value,n++;return{balance:r,count:n}}function ec(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:u=0}=r,p=500,f=d??new Xt.ZswapLocalState,g=[],h=0,m=u-1,w=-1,y=()=>{if(g.length===0)return;if(f=f.replayEventsWithChanges(e,g).state,h+=g.length,g.length=0,s&&m>=0)try{s(f,m)}catch{}};return En(t,{query:Fm,variables:{id:u},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(S)=>{let b=S?.zswapLedgerEvents;if(!b)return!1;let v;try{v=Xt.Event.deserialize(new Uint8Array(Buffer.from(b.raw,"hex")))}catch(R){throw Error(`Failed to deserialize zswap event ${b.id}: ${R.message}`)}if(g.push(v),m=b.id,b.maxId>w)w=b.maxId;if(g.length>=500)try{y()}catch(R){throw Error(`Failed applying zswap events: ${R.message}`)}return n?.(h+g.length,w),m>=w},buildResult:(S)=>{try{y();let{balance:b,count:v}=Lm(f);return{balance:b,availableCoins:v,eventCount:h,state:f,lastAppliedEventId:m,partial:S}}catch(b){throw Error(`Failed to build shielded state: ${b.message}`)}}})}var Fm=`
|
|
103
105
|
subscription ZswapLedgerEvents($id: Int) {
|
|
104
106
|
zswapLedgerEvents(id: $id) {
|
|
105
107
|
id
|
|
@@ -107,26 +109,26 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
107
109
|
maxId
|
|
108
110
|
}
|
|
109
111
|
}
|
|
110
|
-
`;var
|
|
111
|
-
Expected a bech32m address for network "${t.networkId}"`)}}function
|
|
112
|
-
Available: ${
|
|
112
|
+
`;var tc=E(()=>{mo()});import{existsSync as Rn,mkdirSync as Um,writeFileSync as jm,readFileSync as Wm,unlinkSync as So,readdirSync as rc,renameSync as Bm}from"node:fs";import{join as Yt,dirname as Hm}from"node:path";import{homedir as nc}from"node:os";import{randomBytes as Gm}from"node:crypto";import*as Wr from"@midnight-ntwrk/ledger-v8";function oc(e){return Wr.ZswapSecretKeys.fromSeed(Tt(e)).coinPublicKey}function ic(e,t){let r=t??Yt(nc(),ae,$e);return Yt(r,e)}function bo(e,t,r){let n=t.slice(0,20);return Yt(ic(e,r),`shielded-${n}.json`)}function Km(e,t,r,n){let s=bo(e,t,r);if(!Rn(s))return null;try{let o=JSON.parse(Wm(s,"utf-8"));if(o.version!==sc)return null;if(o.network!==e)return null;if(o.coinPublicKeyHex!==t)return null;if(typeof o.lastAppliedEventId!=="number")return null;if(typeof o.zswapState!=="string")return null;if(n&&o.chainId&&o.chainId!==n)return null;return{state:Wr.ZswapLocalState.deserialize(new Uint8Array(Buffer.from(o.zswapState,"hex"))),lastAppliedEventId:o.lastAppliedEventId}}catch{return null}}function yo(e,t,r,n,s,o){let i={version:sc,network:e,coinPublicKeyHex:t,lastAppliedEventId:n,timestamp:new Date().toISOString(),zswapState:Buffer.from(r.serialize()).toString("hex"),...o?{chainId:o}:{}},a=bo(e,t,s),c=Hm(a);if(!Rn(c))Um(c,{recursive:!0,mode:Se});let d=a+`.tmp.${Gm(4).toString("hex")}`;try{jm(d,JSON.stringify(i),{mode:be}),Bm(d,a)}catch(u){try{So(d)}catch{}throw u}}function $n(e,t,r){let n=r??Yt(nc(),ae,$e);if(e&&t){let o=bo(e,t,r);try{So(o)}catch{}return}let s=(o)=>{if(!Rn(o))return;try{for(let i of rc(o))if(i.startsWith("shielded-")&&i.endsWith(".json"))try{So(Yt(o,i))}catch{}}catch{}};if(e){s(ic(e,r));return}if(!Rn(n))return;try{for(let o of rc(n))s(Yt(n,o))}catch{}}async function ac(e,t,r,n={}){let s=Wr.ZswapSecretKeys.fromSeed(Tt(e)),o=s.coinPublicKey,i=n.forceFresh?null:Km(t,o,void 0,n.chainId),a=i?i.lastAppliedEventId+1:0,c=await ec(s,r,{initialState:i?.state,startFromId:a,onProgress:n.onProgress,signal:n.signal,timeoutMs:n.timeoutMs,onCheckpoint:(d,u)=>{try{yo(t,o,d,u,void 0,n.chainId)}catch{}}});if(c.lastAppliedEventId>=0)yo(t,o,c.state,c.lastAppliedEventId,void 0,n.chainId);else if(!i)yo(t,o,c.state,-1,void 0,n.chainId);return{balance:c.balance,availableCoins:c.availableCoins,eventCount:c.eventCount,lastAppliedEventId:c.lastAppliedEventId>=0?c.lastAppliedEventId:i?.lastAppliedEventId??-1,fromCache:i!==null,partial:c.partial}}var sc=1;var vo=E(()=>{Nt();tc()});function cc(e={}){let t=Math.min(Math.max(e.windowMs??15000,1000),60000),r=[],n=null,s=(i)=>{let a=i-t;while(r.length>0&&r[0].t<a)r.shift()},o=()=>{let i=r[r.length-1],a=r[0],c=i.highest>0?Math.min(100,Math.round(i.applied/i.highest*100)):null,d=null,u=null;if(r.length>=2){let p=i.applied-a.applied,f=i.t-a.t;if(f>=1000&&p>0){d=p/(f/1000);let g=Math.max(0,i.highest-i.applied);u=g>0?g/d:0}}return{applied:i.applied,highest:i.highest,percent:c,ratePerSec:d,etaSec:u}};return{sample(i){return r.push(i),s(i.t),n=o(),n},snapshot(){return n},reset(){r.length=0,n=null}}}function dc(e,t="Syncing"){let r=[t];if(e.percent!==null)r.push(`${e.percent}%`);else if(e.highest===0)r.push(`${e.applied} events`);if(e.etaSec!==null&&e.etaSec>0)r.push(`ETA ${Jm(e.etaSec)}`);if(e.ratePerSec!==null&&e.ratePerSec>0)r.push(`${Math.round(e.ratePerSec)} evt/s`);return r.join(" · ")}function Jm(e){if(!Number.isFinite(e)||e<0)return"?";if(e<60)return`${Math.ceil(e)}s`;let t=Math.floor(e/60),r=Math.round(e-t*60);if(t<60)return r>0?`${t}m ${r}s`:`${t}m`;let n=Math.floor(t/60),s=t-n*60;return s>0?`${n}h ${s}m`:`${n}h`}import*as Ao from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Vm,UnshieldedAddress as zm}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as ko}from"@midnight-ntwrk/wallet-sdk-abstractions";function Br(e){if(e<=0)throw Error("Amount must be greater than 0");if(!Number.isFinite(e))throw Error("Amount must be a finite number");let t=e.toFixed(6),[r,n]=t.split("."),s=r+(n??"").padEnd(6,"0"),o=BigInt(s);if(o<=0n)throw Error("Amount too small — minimum is 0.000001 NIGHT");return o}function Hr(e){let t=Number(e);if(Number.isNaN(t)||!Number.isFinite(t))throw Error(`Invalid amount: "${e}" — must be a positive number`);if(t<=0)throw Error(`Invalid amount: "${e}" — must be greater than 0`);return t}function Xm(e,t){let r=qm[t.networkId];if(r===void 0)throw Error(`Unknown networkId: ${t.networkId}`);try{return Vm.parse(e).decode(zm,r)}catch(n){throw Error(`Invalid recipient address: ${n.message}
|
|
113
|
+
Expected a bech32m address for network "${t.networkId}"`)}}function In(e){let t=e<0n?-e:e,r=t/1000000000000000n,n=t%1000000000000000n;return`${e<0n?"-":""}${r}.${n.toString().padStart(15,"0").slice(0,6)}`}function Co(e){let t=Math.round(e/1000);if(t<60)return`${t}s`;let r=Math.floor(t/60),n=t%60;return`${r}m ${n}s`}function Ce(){let{warn:e,error:t}=console,r=(n)=>n.some((s)=>String(s).includes("RPC-CORE"));return console.warn=(...n)=>{if(!r(n))e(...n)},console.error=(...n)=>{if(!r(n))t(...n)},()=>{console.warn=e,console.error=t}}async function Ym(e,t,r){let n=new Date(Date.now()+hr*60*1000);await Promise.race([e.facade.dust.waitForSyncedState(),new Promise((d,u)=>setTimeout(()=>u(Error("Insufficient funds: dust wallet sync timed out")),Ns))]);let s=await e.facade.dust.createDustGenerationTransaction(new Date,n,t,e.keystore.getPublicKey(),r),o=s.intents?.get(1);if(!o)throw Error("Dust generation intent not found on transaction");let i=e.keystore.signData(o.signatureData(1)),a=await e.facade.dust.addDustGenerationSignature(s,i),c=await e.facade.finalizeTransaction(a);return await e.facade.submitTransaction(c)}async function Zm(e,t,r,n){let s=Date.now(),o=s+Gi,i,a=!1,c=setInterval(()=>{if(a&&n){let d=Co(Date.now()-s);n(`Waiting for dust generation capacity (${d} elapsed, ~5 min on fresh wallets)...`)}},1000);try{while(Date.now()<o)try{return await Ym(e,t,r)}catch(d){if(i=d,vn(d)&&Date.now()+Is<o){a=!0;let u=Co(Date.now()-s);n?.(`Waiting for dust generation capacity (${u} elapsed, ~5 min on fresh wallets)...`),await new Promise((p)=>setTimeout(p,Is));continue}throw d}throw i??Error("Dust registration timed out")}finally{clearInterval(c)}}async function tt(e,t,r){let n=r??await e.facade.waitForSyncedState();if(n.dust.availableCoins.length>0||n.dust.balance(new Date)>0n)return t?.("Dust available"),{alreadyAvailable:!0};let s=n.unshielded.availableCoins.filter((a)=>a.meta?.registeredForDustGeneration!==!0),o;if(s.length>0){t?.(`Registering ${s.length} UTXO(s) for dust generation...`);let a=s.map((c)=>({...c.utxo,ctime:new Date(c.meta.ctime)}));o=await Zm(e,a,n.dust.address,t)}else t?.("UTXOs already registered, waiting for dust generation...");t?.("Waiting for dust tokens...");let i=Date.now();while(Date.now()-i<Rs){try{if((await Promise.race([e.facade.waitForSyncedState(),new Promise((c,d)=>setTimeout(()=>d(Error("Poll sync timed out")),Ns))])).dust.balance(new Date)>0n)return t?.("Dust available"),{alreadyAvailable:!1,txHash:o}}catch{}await new Promise((a)=>setTimeout(a,5000))}throw Error("Timed out waiting for dust tokens. Try running: midnight dust register")}async function Qm(e,t,r,n,s,o,i){let a=Date.now(),c=a+Rs,d,u=0;while(!0)try{if(d)await co(e,"lite");let p=new Date(Date.now()+hr*60*1000);B("transfer","Building transfer transaction...");let f=await e.facade.transferTransaction([{type:"unshielded",outputs:[{amount:r,receiverAddress:t,type:Ao.unshieldedToken().raw}]}],{shieldedSecretKeys:e.zswapSecretKeys,dustSecretKey:e.dustSecretKey},{ttl:p,payFees:!0});B("transfer","Signing recipe...");let g=await e.facade.signRecipe(f,(S)=>e.keystore.signData(S));B("transfer","Generating ZK proof..."),n?.();let h=await Promise.race([e.facade.finalizeRecipe(g),new Promise((S,b)=>{setTimeout(()=>b(Error("ZK proof generation timed out")),tn)})]);B("transfer","Submitting transaction to node..."),s?.();let m=Date.now(),w=i?setInterval(()=>i(Date.now()-m),1000):void 0,y;try{y=await e.facade.submitTransaction(h)}finally{if(w)clearInterval(w)}return B("transfer",`Transaction submitted: ${y}`),y}catch(p){if(d=p,(p?.code===Ki||p?.message?.includes("115")||p?.message?.toLowerCase().includes("stale"))&&++u<Hi)continue;if(Fr(p))throw p;if(vn(p)&&Date.now()<c){let g=Co(Date.now()-a);o?.(`Dust insufficient, re-ensuring (${g} elapsed)...`);try{let h=await co(e,"lite"),m=h.dust.balance(new Date);if(m>0n&&m<gr)throw Error(`Insufficient dust for transaction fees.
|
|
114
|
+
Available: ${In(m)} DUST, need ≥${In(gr)} DUST.
|
|
113
115
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
114
|
-
Check status: midnight dust status`);await tt(e,o,h)}catch(h){if(String(h?.message).startsWith("Insufficient dust"))throw h;await new Promise((m)=>setTimeout(m,5000))}continue}throw p}}async function
|
|
115
|
-
Available: ${
|
|
116
|
+
Check status: midnight dust status`);await tt(e,o,h)}catch(h){if(String(h?.message).startsWith("Insufficient dust"))throw h;await new Promise((m)=>setTimeout(m,5000))}continue}throw p}}async function Zt(e){let{seedBuffer:t,networkConfig:r,recipientAddress:n,amountNight:s,signal:o,onSync:i,onSyncDetail:a,onDust:c,onProving:d,onSubmitting:u,onSubmittingTick:p,onSyncWarning:f}=e,g=Br(s),h=Xm(n,r),m=he(f),w=Ce();try{return await me().withFacade(t,r,async({bundle:y,state:S})=>{if(o?.aborted)throw Error("Operation cancelled");B("transfer","Sync complete, checking balance...");let b=S.unshielded.balances[Ao.unshieldedToken().raw]??0n,v=S.unshielded.availableCoins?.length??0;if(B("transfer",`Balance: ${Number(b)/Ts} NIGHT, coins: ${v}`),b<g){let q=Number(b)/Ts;throw Error(`Insufficient balance: ${q.toFixed(6)} NIGHT available, ${s} NIGHT requested`)}let R=S.dust.balance(new Date);if(R>0n&&R<gr)throw Error(`Insufficient dust for transaction fees.
|
|
117
|
+
Available: ${In(R)} DUST, need ≥${In(gr)} DUST.
|
|
116
118
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
117
|
-
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(
|
|
118
|
-
`)},fail(d){if(t)return;t=!0,
|
|
119
|
+
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(B("transfer","Ensuring dust availability..."),await tt(y,c,S),B("transfer","Dust available"),o?.aborted)throw Error("Operation cancelled");return B("transfer","Building and submitting transaction..."),{txHash:await Qm(y,h,g,d,u,c,p),amountMicroNight:g}},{syncMode:"lite",requireStrictSync:!0,signal:o,onStatus:c,onSyncProgress:i,onSyncDetail:a,onSyncWarning:f})}finally{w(),m()}}var qm;var bt=E(()=>{Ke();at();ot();qm={PreProd:ko.NetworkId.PreProd,Preview:ko.NetworkId.Preview,Undeployed:ko.NetworkId.Undeployed}});function pc(){return Pt}function uc(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function G(e){let t=!1;if(!ut()){let a=e;process.stderr.write(`⠋ ${a}`);let c={update(d){a=d,process.stderr.write(`\r⠋ ${a}\x1B[K`)},stop(d){if(t)return;t=!0,Pt=null,process.stderr.write(`\r✓ ${d??a}\x1B[K
|
|
120
|
+
`)},fail(d){if(t)return;t=!0,Pt=null,process.stderr.write(`\r✗ ${d??a}\x1B[K
|
|
119
121
|
`)},log(d){process.stderr.write(`\r\x1B[K${d}
|
|
120
|
-
`),process.stderr.write(`⠋ ${a}`)}};return
|
|
121
|
-
`)},fail(a){if(t)return;t=!0,clearInterval(o),
|
|
122
|
+
`),process.stderr.write(`⠋ ${a}`)}};return Pt=c,c}let r=0,n=e,s=()=>{let a=L(lc[r]),d=(process.stderr.columns||80)-4,u=n;if(uc(u).length>d)u=uc(u).slice(0,d);process.stderr.write(`\r${a} ${u}\x1B[K`),r=(r+1)%lc.length};s();let o=setInterval(s,ef),i={update(a){n=a},stop(a){if(t)return;t=!0,clearInterval(o),Pt=null;let c=a??n;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${c}\x1B[K
|
|
123
|
+
`)},fail(a){if(t)return;t=!0,clearInterval(o),Pt=null;let c=a??n;process.stderr.write(`\r\x1B[31m✗\x1B[0m ${c}\x1B[K
|
|
122
124
|
`)},log(a){process.stderr.write(`\r\x1B[K${a}
|
|
123
|
-
`),s()}};return
|
|
124
|
-
Drop --network (we'll infer from the address) or pass an address for ${n}.`);if(!n&&r)e={...e,flags:{...e.flags,network:r}};let{name:s,config:o}=
|
|
125
|
+
`),s()}};return Pt=i,i}async function _n(e,t,r){let n=Date.now(),s=(a)=>{let c=Math.floor(a/1000),d=Math.floor(c/60).toString().padStart(2,"0"),u=(c%60).toString().padStart(2,"0");return`${d}:${u}`},o=()=>e.update(`${t} ${s(Date.now()-n)}`);o();let i=setInterval(o,1000);try{return await r}finally{clearInterval(i)}}var lc,ef=80,Pt=null;var Ve=E(()=>{lc=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var gc={};fe(gc,{default:()=>Dn});import*as mc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as tf}from"@midnight-ntwrk/wallet-sdk-address-format";async function Dn(e){if(e.subcommand)return nf(e);return fc(e)}function rf(e){let t=e.match(/^mn_addr_([a-z]+)1/);if(!t)return null;let r=t[1];return xe(r)?r:null}async function nf(e){if(Re(e))De();let t=e.subcommand;B("balance",`address=${t}`);let r=rf(t),n=A(e,"network");if(n&&r&&n!==r)throw Error(`Address belongs to ${r} but --network is ${n}.
|
|
126
|
+
Drop --network (we'll infer from the address) or pass an address for ${n}.`);if(!n&&r)e={...e,flags:{...e.flags,network:r}};let{name:s,config:o}=te({args:e});if(N(e,"shielded")){let a=ha(t);if(a){B("balance",`shielded positional → wallet ${a.wallet.name} on ${a.network}`);let c={...e,flags:{...e.flags,wallet:a.wallet.file,network:a.network}};return fc(c)}throw Error("Shielded balances are private — they can only be read with the wallet's secret key, "+`not from an address alone.
|
|
125
127
|
This address isn't one of your wallets. Check its shielded balance from the wallet that owns it:
|
|
126
|
-
midnight balance --wallet <name> --shielded --network ${s}`)}
|
|
127
|
-
`);else for(let[c,d]of a.balances)process.stdout.write(`${
|
|
128
|
+
midnight balance --wallet <name> --shielded --network ${s}`)}Le(o,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},s);let i=G(`Checking balance on ${s}...`);try{let a=await me().unshielded(t,o,{forceFresh:N(e,"no-cache"),onProgress:(c,d)=>{if(d>0){let u=Math.round(c/d*100);i.update(`Syncing transactions... ${u}%`)}}});if(i.stop(`Synced ${a.txCount} transactions`),N(e,"json")){let c={};for(let[u,p]of a.balances){let f=Dr(u)?"NIGHT":u;c[f]=Dr(u)?Et(p):p.toString()}let d=c.NIGHT!==void 0?{NIGHT:c.NIGHT}:{};if(dt(e)){D({network:s,balances:c,...d,utxoCount:a.utxoCount});return}D({address:t,network:s,balances:c,...d,utxoCount:a.utxoCount,txCount:a.txCount});return}if(a.balances.size===0)process.stdout.write(`0
|
|
129
|
+
`);else for(let[c,d]of a.balances)process.stdout.write(`${Dr(c)?"NIGHT":c}=${d}
|
|
128
130
|
`);if(process.stderr.write(`
|
|
129
|
-
`+
|
|
131
|
+
`+W("Balance")+`
|
|
130
132
|
|
|
131
133
|
`),process.stderr.write(C("Address",re(t))+`
|
|
132
134
|
`),process.stderr.write(C("Network",s)+`
|
|
@@ -134,85 +136,83 @@ This address isn't one of your wallets. Check its shielded balance from the wall
|
|
|
134
136
|
`),process.stderr.write(C("Transactions",a.txCount.toString())+`
|
|
135
137
|
`),process.stderr.write(`
|
|
136
138
|
`),a.balances.size===0)process.stderr.write(` ${l("No balance found")}
|
|
137
|
-
`);else for(let[c,d]of a.balances)if(
|
|
139
|
+
`);else for(let[c,d]of a.balances)if(Dr(c))process.stderr.write(C("NIGHT",k(sn(d)))+`
|
|
138
140
|
`);else{let u=c.slice(0,8)+"…"+c.slice(-8);process.stderr.write(C(`Token ${u}`,k(d.toString()))+`
|
|
139
141
|
`)}process.stderr.write(`
|
|
140
|
-
`+
|
|
142
|
+
`+V()+`
|
|
141
143
|
|
|
142
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
143
|
-
`+
|
|
144
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function fc(e){if(Re(e))De();let{name:t,config:r}=te({args:e});B("balance",`network=${t} indexerWS=${r.indexerWS}`);let{seed:n,walletPath:s,config:o}=Zs(e);B("balance",`wallet path=${s??"(from --seed/MN_SEED)"}`);let i=o?.addresses[t]??ve(n,t),a=o?.shieldedAddresses?.[t]??"";Le(r,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},t);let c=he(),d=Ce(),u=N(e,"no-cache"),p=N(e,"json"),f=mc.unshieldedToken().raw,g=null;try{if(!p){if(process.stderr.write(`
|
|
145
|
+
`+W("Balance")+`
|
|
144
146
|
|
|
145
147
|
`),process.stderr.write(C("Address",re(i))+`
|
|
146
148
|
`),a)process.stderr.write(C("Shielded",re(a))+`
|
|
147
149
|
`);process.stderr.write(C("Network",t)+`
|
|
148
150
|
`),process.stderr.write(`
|
|
149
151
|
`+k("Unshielded")+`
|
|
150
|
-
`)}if(!p)g=
|
|
152
|
+
`)}if(!p)g=G("Checking unshielded...");B("balance",`phase=unshielded forceFresh=${u}`);let h=await me().unshielded(i,r,{forceFresh:u}),m=h.balances.get(f)??0n,w=h.utxoCount;if(B("balance",`unshielded fromCache=${h.fromCache} utxos=${w} txs=${h.txCount}`),g)if(g.stop("Unshielded ready"),g=null,m>0n)process.stderr.write(C(" NIGHT",k(sn(m)))+`
|
|
151
153
|
`),process.stderr.write(C(" UTXOs",w.toString())+`
|
|
152
154
|
`);else process.stderr.write(` ${l("No unshielded balance")}
|
|
153
155
|
`);if(!p)process.stdout.write(`NIGHT=${m}
|
|
154
156
|
`),process.stderr.write(`
|
|
155
157
|
`+k("Shielded")+`
|
|
156
|
-
`);let y=
|
|
158
|
+
`);let y=Gt(t,N(e,"force-shielded")),S=a,b=0n,v=0,R=0;if(y){if(!p)g=G("Syncing shielded...");let P=cc(),q=It(r.networkId);if(S=tf.encode(q,$r(n)).asString(),s)Ht(s,t,S);let U=await An(r.node).catch(()=>null)??void 0,X=await ac(n,t,r.indexerWS,{forceFresh:u,chainId:U,onProgress:(O,F)=>{if(!g)return;let Q=P.sample({applied:O,highest:F,t:Date.now()});g.update(dc(Q,"Syncing shielded"))}});if(b=X.balance,v=X.availableCoins,R=0,g)if(g.stop("Shielded ready"),g=null,b>0n)process.stderr.write(C(" NIGHT",k(sn(b)))+`
|
|
157
159
|
`),process.stderr.write(C(" Coins",`${v} available, ${R} pending`)+`
|
|
158
160
|
`);else process.stderr.write(` ${l("No shielded balance")}
|
|
159
|
-
`)}else if(!p)process.stderr.write(` ${l("Skipped — "+
|
|
160
|
-
`);if(p){if(
|
|
161
|
+
`)}else if(!p)process.stderr.write(` ${l("Skipped — "+gn(t))}
|
|
162
|
+
`);if(p){if(dt(e)){D({network:t,unshielded:{NIGHT:Et(m),utxoCount:w},shielded:{NIGHT:Et(b),availableCoins:v,pendingCoins:R},shieldedSynced:y});return}D({address:i,shieldedAddress:S,network:t,unshielded:{NIGHT:Et(m),utxoCount:w},shielded:{NIGHT:Et(b),availableCoins:v,pendingCoins:R},shieldedSynced:y});return}process.stdout.write(`SHIELDED_NIGHT=${y?b:"skipped"}
|
|
161
163
|
`),process.stderr.write(`
|
|
162
|
-
`+
|
|
164
|
+
`+V()+`
|
|
163
165
|
|
|
164
|
-
`)}catch(h){throw g?.fail("Failed"),h}finally{d(),c()}}var
|
|
166
|
+
`)}catch(h){throw g?.fail("Failed"),h}finally{d(),c()}}var xo=E(()=>{ot();Ie();ke();fn();pe();Ie();hn();wn();Pr();at();vo();Ge();po();Ke();bt();ue();Ve()});var hc={};fe(hc,{default:()=>Pn});async function Pn(e){let t=mn(e,{requireExplicit:!0,label:"address"}),r=A(e,"index"),n=r!==void 0?parseInt(r,10):0;if(isNaN(n)||n<0||!Number.isInteger(Number(r??"0")))throw Error("Key index must be a non-negative integer");let s=_e({args:e}),o=ve(t,s,n),i=`m/44'/2400'/0'/NightExternal/${n}`;if(N(e,"json")){D({address:o,network:s,index:n,path:i});return}process.stdout.write(o+`
|
|
165
167
|
`),process.stderr.write(`
|
|
166
168
|
`),process.stderr.write(C("Network",s)+`
|
|
167
169
|
`),process.stderr.write(C("Index",n.toString())+`
|
|
168
170
|
`),process.stderr.write(C("Address",re(o))+`
|
|
169
171
|
`),process.stderr.write(C("Path",l(i))+`
|
|
170
|
-
`),process.stderr.write(
|
|
172
|
+
`),process.stderr.write(V()+`
|
|
171
173
|
|
|
172
|
-
`)}var
|
|
174
|
+
`)}var Eo=E(()=>{fn();Ge();pe();ue()});var wc={};fe(wc,{default:()=>On});async function On(e){let t=_e({args:e}),r=Buffer.from(rt,"hex"),n=ve(r,t);if(N(e,"json")){D({address:n,network:t});return}process.stdout.write(n+`
|
|
173
175
|
`),process.stderr.write(`
|
|
174
176
|
`),process.stderr.write(C("Network",t)+`
|
|
175
177
|
`),process.stderr.write(C("Address",re(n))+`
|
|
176
178
|
`),process.stderr.write(C("Seed",l("0x01 (genesis)"))+`
|
|
177
|
-
`),process.stderr.write(
|
|
179
|
+
`),process.stderr.write(V()+`
|
|
178
180
|
|
|
179
|
-
`)}var
|
|
181
|
+
`)}var To=E(()=>{Ge();pe();ue()});var Sc={};fe(Sc,{default:()=>Mn});import*as yc from"@midnight-ntwrk/ledger-v8";function Gr(e,t,r){let n={readTime:0n,computeTime:0n,blockUsage:0n,bytesWritten:0n,bytesChurned:0n};n[t]=r;let o=e.normalizeFullness(n)[t];return Math.round(Number(r)/o)}function sf(e){return{readTime:Gr(e,"readTime",1000000000n),computeTime:Gr(e,"computeTime",1000000000n),blockUsage:Gr(e,"blockUsage",10000n),bytesWritten:Gr(e,"bytesWritten",10000n),bytesChurned:Gr(e,"bytesChurned",1000000n)}}async function Mn(e){let t=yc.LedgerParameters.initialParameters(),r=sf(t);if(N(e,"json")){D(r);return}for(let[n,s]of Object.entries(r))process.stdout.write(`${n}=${s}
|
|
180
182
|
`);process.stderr.write(`
|
|
181
|
-
`+
|
|
183
|
+
`+W("Block Limits")+`
|
|
182
184
|
|
|
183
185
|
`),process.stderr.write(l(" Derived from LedgerParameters.initialParameters()")+`
|
|
184
186
|
|
|
185
|
-
`);for(let[n,s]of Object.entries(r)){let o=
|
|
187
|
+
`);for(let[n,s]of Object.entries(r)){let o=of[n]??"";process.stderr.write(C(n,`${k(s.toLocaleString())} ${l(o)}`)+`
|
|
186
188
|
`)}process.stderr.write(`
|
|
187
|
-
`+
|
|
189
|
+
`+V()+`
|
|
188
190
|
`),process.stderr.write(l(" bytesWritten is typically the tightest constraint")+`
|
|
189
191
|
`),process.stderr.write(l(" for large contract deployments.")+`
|
|
190
192
|
|
|
191
|
-
`)}var
|
|
193
|
+
`)}var of;var No=E(()=>{ue();of={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});var kc={};fe(kc,{default:()=>Qt});import*as bc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as vc,ShieldedAddress as af}from"@midnight-ntwrk/wallet-sdk-address-format";async function Qt(e,t){lt(e);let r=e.subcommand;if(!r)throw Error(`Missing amount.
|
|
192
194
|
Usage: midnight airdrop <amount> [--wallet <name|file|address>]
|
|
193
195
|
Example: midnight airdrop 1000
|
|
194
196
|
Example: midnight airdrop 1000 --wallet alice
|
|
195
|
-
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=
|
|
197
|
+
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=Hr(r),{name:s,config:o}=te({args:e});if(Le(o,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},s),s!=="undeployed")throw Error(`Airdrop is only available on the "undeployed" network (local devnet).
|
|
196
198
|
Current network: "${s}"
|
|
197
|
-
On preprod/preview, use a faucet or transfer from another wallet.`);let i=N(e,"shielded"),
|
|
199
|
+
On preprod/preview, use a faucet or transfer from another wallet.`);let i=A(e,"wallet"),a=N(e,"shielded")||i!==void 0&&i.startsWith("mn_shield-addr_"),c=df(e,s,o,a);if(a)return pf(e,c,n,s,o,t);return uf(e,c,n,s,o,t)}function cf(e){return e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_")}function df(e,t,r,n){let s=A(e,"wallet");if(s!==void 0&&cf(s))return lf(s,t,r,n);let o=ie(s),i=ce(o);if(n){let a=It(r.networkId),c=Buffer.from(i.seed,"hex"),d=$r(c),u=vc.encode(a,d).asString();return{kind:"wallet",raw:d,bech32m:u,walletPath:o}}return{kind:"address",address:i.addresses[t]}}function lf(e,t,r,n){let s=e.startsWith("mn_shield-addr_");if(n&&!s)throw Error(`--shielded was passed but --wallet is an unshielded address.
|
|
198
200
|
Pass a shielded address (mn_shield-addr_...) or drop --shielded.
|
|
199
|
-
Got: ${e}`);if(!n&&s)throw Error(`--wallet is a shielded address but --shielded was not passed.
|
|
200
|
-
Add --shielded, or pass an unshielded address (mn_addr_...).
|
|
201
201
|
Got: ${e}`);let o=n?`mn_shield-addr_${t}1`:`mn_addr_${t}1`;if(!e.startsWith(o))throw Error(`Address does not match network "${t}".
|
|
202
202
|
Expected prefix: ${o}
|
|
203
|
-
Got: ${e}`);if(n){let i=
|
|
204
|
-
`+
|
|
203
|
+
Got: ${e}`);if(n){let i=It(r.networkId),a;try{a=vc.parse(e).decode(af,i)}catch(c){throw Error(`Invalid shielded address: ${c.message}`)}return{kind:"address",raw:a,bech32m:e}}return{kind:"address",address:e}}async function uf(e,t,r,n,s,o){if(Re(e))De();let i=t.address,a=Buffer.from(rt,"hex");process.stderr.write(`
|
|
204
|
+
`+W("Airdrop")+`
|
|
205
205
|
|
|
206
206
|
`),process.stderr.write(C("Network",n)+`
|
|
207
207
|
`),process.stderr.write(C("From",l("genesis (seed 0x01)"))+`
|
|
208
208
|
`),process.stderr.write(C("To",re(i,!0))+`
|
|
209
209
|
`),process.stderr.write(C("Amount",k(r+" NIGHT"))+`
|
|
210
210
|
`),process.stderr.write(`
|
|
211
|
-
`);let c=
|
|
211
|
+
`);let c=G("Starting genesis wallet...");try{let d=await Zt({seedBuffer:a,networkConfig:s,recipientAddress:i,amountNight:r,signal:o,onSync(u,p){if(p>0){let f=Math.round(u/p*100);c.update(`Syncing genesis wallet... ${f}%`)}},onDust(u){c.update(`Dust: ${u}`)},onProving(){c.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){c.update("Submitting and waiting for finalization (typically 12 to 30s)...")},onSubmittingTick(u){let p=Math.floor(u/1000),f=Math.floor(p/60).toString().padStart(2,"0"),g=(p%60).toString().padStart(2,"0");c.update(`Submitting and waiting for finalization... ${f}:${g} elapsed (typically 12 to 30s)`)},onSyncWarning(u,p){c.update(`Syncing genesis wallet... (${p}, retrying)`)}});if(c.stop("Transaction submitted"),N(e,"json")){D({txHash:d.txHash,amount:r,recipient:i,network:n});return}process.stdout.write(d.txHash+`
|
|
212
212
|
`),process.stderr.write(`
|
|
213
|
-
`+
|
|
213
|
+
`+pt(`Airdropped ${r} NIGHT to your wallet`,d.txHash)+`
|
|
214
214
|
`),process.stderr.write(`
|
|
215
|
-
`+
|
|
215
|
+
`+V()+`
|
|
216
216
|
`),process.stderr.write(l(" Verify: midnight balance")+`
|
|
217
217
|
`),process.stderr.write(l(" Register dust: midnight dust register")+`
|
|
218
218
|
`),process.stderr.write(l(" Note: Dust generation takes a few minutes on a fresh wallet.")+`
|
|
@@ -221,66 +221,66 @@ Got: ${e}`);if(n){let i=_t(r.networkId),a;try{a=Pc.parse(e).decode(_f,i)}catch(c
|
|
|
221
221
|
`)}catch(d){if(c.fail("Failed"),d instanceof Error&&d.message.toLowerCase().includes("dust"))throw Error(`${d.message}
|
|
222
222
|
|
|
223
223
|
On a fresh localnet, the minimum airdrop is ~1 NIGHT.
|
|
224
|
-
Try: midnight airdrop 1`);throw d}}async function
|
|
225
|
-
`+
|
|
224
|
+
Try: midnight airdrop 1`);throw d}}async function pf(e,t,r,n,s,o){let i=Br(r);if(Re(e))De();let a=Buffer.from(rt,"hex"),c=bc.unshieldedToken().raw,{raw:d,bech32m:u}=t;if(t.kind==="wallet")Ht(t.walletPath,n,u);process.stderr.write(`
|
|
225
|
+
`+W("Shielded Airdrop")+`
|
|
226
226
|
|
|
227
227
|
`),process.stderr.write(C("Network",n)+`
|
|
228
228
|
`),process.stderr.write(C("From",l("genesis shielded (seed 0x01)"))+`
|
|
229
229
|
`),process.stderr.write(C("To",re(u,!0))+`
|
|
230
230
|
`),process.stderr.write(C("Amount",k(r+" NIGHT (shielded)"))+`
|
|
231
231
|
`),process.stderr.write(`
|
|
232
|
-
`);let p=
|
|
232
|
+
`);let p=he(),f=Ce(),g=G("Syncing genesis wallet...");try{let h=await me().withFacade(a,s,async({bundle:m,state:w})=>{let y=w.shielded.balances[c]??0n;if(y<i){let P=Number(y)/1e6;throw Error(`Genesis wallet has insufficient shielded balance: ${P.toFixed(6)} NIGHT available, ${r} NIGHT requested`)}if(g.update("Checking dust..."),await tt(m,(P)=>g.update(P)),o?.aborted)throw Error("Operation cancelled");g.update("Building shielded transaction...");let S=await m.facade.transferTransaction([{type:"shielded",outputs:[{type:c,amount:i,receiverAddress:d}]}],{shieldedSecretKeys:m.zswapSecretKeys,dustSecretKey:m.dustSecretKey},{ttl:new Date(Date.now()+3600000)});g.update("Signing...");let b=await m.facade.signRecipe(S,(P)=>m.keystore.signData(P));g.update("Generating ZK proof (this may take a few minutes)...");let v=await m.facade.finalizeRecipe(b),R=await _n(g,"Submitting and waiting for finalization (typically 12 to 30s)...",m.facade.submitTransaction(v));return String(R)},{syncMode:"full",requireStrictSync:!0,signal:o,onStatus:(m)=>g.update(m),onSyncProgress:(m,w)=>{if(w>0){let y=Math.min(Math.round(m/w*100),100);g.update(y>=100?"Syncing genesis wallet...":`Syncing genesis wallet... ${y}%`)}},onSyncDetail:(m)=>g.update(`Syncing genesis wallet... (waiting on: ${m})`)});if(g.stop("Transaction submitted"),N(e,"json")){D({txHash:h,amount:r,shieldedAddress:u,network:n,type:"shielded"});return}process.stdout.write(h+`
|
|
233
233
|
`),process.stderr.write(`
|
|
234
|
-
`+
|
|
234
|
+
`+pt(`Airdropped ${r} shielded NIGHT to your wallet`,h)+`
|
|
235
235
|
`),process.stderr.write(`
|
|
236
|
-
`+
|
|
236
|
+
`+V()+`
|
|
237
237
|
`),process.stderr.write(l(" Verify: midnight balance --shielded")+`
|
|
238
238
|
|
|
239
|
-
`)}catch(h){throw g.fail("Failed"),h}finally{f(),p()}}var
|
|
239
|
+
`)}catch(h){throw g.fail("Failed"),h}finally{f(),p()}}var Fn=E(()=>{ot();ke();pe();Ie();wn();Ge();bt();Ke();at();ue();Ve()});var xc={};fe(xc,{default:()=>Ln});import*as Ac from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Cc,ShieldedAddress as mf}from"@midnight-ntwrk/wallet-sdk-address-format";async function Ln(e,t){lt(e);let r=e.subcommand,n=e.positionals[0];if(!r)throw Error(`Missing recipient address.
|
|
240
240
|
Usage: midnight transfer <to> <amount>
|
|
241
241
|
Example: midnight transfer mn_addr_undeployed1... 100
|
|
242
242
|
Example: midnight transfer alice 100`);if(!n)throw Error(`Missing amount.
|
|
243
243
|
Usage: midnight transfer <to> <amount>
|
|
244
|
-
Example: midnight transfer mn_addr_undeployed1... 100`);let s=N(e,"shielded"),o=
|
|
245
|
-
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function
|
|
246
|
-
`+
|
|
244
|
+
Example: midnight transfer mn_addr_undeployed1... 100`);let s=N(e,"shielded"),o=ff(r,e,s);if(s)return hf(e,o,n,t);return gf(e,o,n,t)}function ff(e,t,r){if(e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_"))return e;let n=ie(e),s=ce(n),{name:o}=te({args:t});if(r){let i=s.shieldedAddresses?.[o];if(!i)throw Error(`Wallet "${e}" has no shielded address for network "${o}".
|
|
245
|
+
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function gf(e,t,r,n){let s=Hr(r),o=ie(A(e,"wallet")),i=ce(o),a=Buffer.from(i.seed,"hex"),{name:c,config:d}=te({args:e}),u=i.addresses[c];if(Le(d,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},c),process.stderr.write(`
|
|
246
|
+
`+W("Transfer")+`
|
|
247
247
|
|
|
248
248
|
`),process.stderr.write(C("Network",c)+`
|
|
249
249
|
`),process.stderr.write(C("From",re(u,!0))+`
|
|
250
250
|
`),process.stderr.write(C("To",re(t,!0))+`
|
|
251
251
|
`),process.stderr.write(C("Amount",k(s+" NIGHT"))+`
|
|
252
252
|
`),process.stderr.write(`
|
|
253
|
-
`),
|
|
253
|
+
`),Re(e))De();let p=G("Starting wallet...");try{let f=await Zt({seedBuffer:a,networkConfig:d,recipientAddress:t,amountNight:s,signal:n,onSync(g,h){if(h>0){let m=Math.min(Math.round(g/h*100),100);p.update(m>=100?"Syncing wallet...":`Syncing wallet... ${m}%`)}},onSyncDetail(g){p.update(`Syncing wallet... (waiting on: ${g})`)},onDust(g){p.update(`Dust: ${g}`)},onProving(){p.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){p.update("Submitting and waiting for finalization (typically 12 to 30s)...")},onSubmittingTick(g){let h=Math.floor(g/1000),m=Math.floor(h/60).toString().padStart(2,"0"),w=(h%60).toString().padStart(2,"0");p.update(`Submitting and waiting for finalization... ${m}:${w} elapsed (typically 12 to 30s)`)},onSyncWarning(g,h){p.update(`Syncing wallet... (${h}, retrying)`)}});if(p.stop("Transaction submitted"),N(e,"json")){D({txHash:f.txHash,amount:s,recipient:t,network:c});return}process.stdout.write(f.txHash+`
|
|
254
254
|
`),process.stderr.write(`
|
|
255
|
-
`+
|
|
255
|
+
`+pt(`Transferred ${s} NIGHT`,f.txHash)+`
|
|
256
256
|
`),process.stderr.write(`
|
|
257
|
-
`+
|
|
257
|
+
`+V()+`
|
|
258
258
|
`),process.stderr.write(l(" Verify: midnight balance")+`
|
|
259
259
|
|
|
260
|
-
`)}catch(f){throw p.fail("Failed"),f}}async function
|
|
260
|
+
`)}catch(f){throw p.fail("Failed"),f}}async function hf(e,t,r,n){let s=Hr(r),o=Br(s),i=ie(A(e,"wallet")),a=ce(i),c=Buffer.from(a.seed,"hex"),{name:d,config:u}=te({args:e});if(!Gt(d,N(e,"force-shielded")))throw Error(gn(d));let p=a.addresses[d],f=It(u.networkId),g=Ac.unshieldedToken().raw;Le(u,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},d);let h;try{h=Cc.parse(t).decode(mf,f)}catch(S){throw Error(`Invalid shielded address: ${S.message}
|
|
261
261
|
Expected a shielded address (mn_shield-addr_...) for network "${u.networkId}"`)}if(process.stderr.write(`
|
|
262
|
-
`+
|
|
262
|
+
`+W("Shielded Transfer")+`
|
|
263
263
|
|
|
264
264
|
`),process.stderr.write(C("Network",d)+`
|
|
265
265
|
`),process.stderr.write(C("To",re(t,!0))+`
|
|
266
266
|
`),process.stderr.write(C("Amount",k(s+" NIGHT (shielded)"))+`
|
|
267
267
|
`),process.stderr.write(`
|
|
268
|
-
`),
|
|
269
|
-
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(y.update("Checking dust..."),await tt(b,(F)=>y.update(F)),n?.aborted)throw Error("Operation cancelled");y.update("Building shielded transaction...");let
|
|
268
|
+
`),Re(e))De();let m=he(),w=Ce(),y=G("Syncing wallet...");try{let S=await me().withFacade(c,u,async({bundle:b,state:v})=>{let R=Cc.encode(f,v.shielded.address).asString();Ht(i,d,R);let P=v.shielded.balances[g]??0n;if(P<o){let F=Number(P)/1e6;throw Error(`Insufficient shielded balance: ${F.toFixed(6)} NIGHT available, ${s} NIGHT requested.
|
|
269
|
+
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(y.update("Checking dust..."),await tt(b,(F)=>y.update(F)),n?.aborted)throw Error("Operation cancelled");y.update("Building shielded transaction...");let q=await b.facade.transferTransaction([{type:"shielded",outputs:[{type:g,amount:o,receiverAddress:h}]}],{shieldedSecretKeys:b.zswapSecretKeys,dustSecretKey:b.dustSecretKey},{ttl:new Date(Date.now()+3600000)});y.update("Signing...");let U=await b.facade.signRecipe(q,(F)=>b.keystore.signData(F));y.update("Generating ZK proof (this may take a few minutes)...");let X=await b.facade.finalizeRecipe(U),O=await _n(y,"Submitting and waiting for finalization (typically 12 to 30s)...",b.facade.submitTransaction(X));return String(O)},{syncMode:"full",requireStrictSync:!0,signal:n,onStatus:(b)=>y.update(b),onSyncProgress:(b,v)=>{if(v>0){let R=Math.min(Math.round(b/v*100),100);y.update(R>=100?"Syncing wallet...":`Syncing wallet... ${R}%`)}},onSyncDetail:(b)=>y.update(`Syncing wallet... (waiting on: ${b})`)});if(y.stop("Transaction submitted"),N(e,"json")){D({txHash:S,amount:s,recipient:t,network:d,type:"shielded"});return}process.stdout.write(S+`
|
|
270
270
|
`),process.stderr.write(`
|
|
271
|
-
`+
|
|
271
|
+
`+pt(`Transferred ${s} shielded NIGHT`,S)+`
|
|
272
272
|
`),process.stderr.write(`
|
|
273
|
-
`+
|
|
273
|
+
`+V()+`
|
|
274
274
|
`),process.stderr.write(l(" Verify: midnight balance --shielded")+`
|
|
275
275
|
|
|
276
|
-
`)}catch(S){throw y.fail("Failed"),S}finally{w(),m()}}var
|
|
276
|
+
`)}catch(S){throw y.fail("Failed"),S}finally{w(),m()}}var Ro=E(()=>{ot();ke();pe();Ie();hn();wn();bt();Ke();at();ue();Ve()});async function wf(e,t){let r=await Qe(e,t,null);try{return await r.facade.dust.serializeState()}finally{await Ue(r)}}async function Ec(e,t,r,n={}){let s=Ze(e),i=await(n.repository??me()).dust(e,r,{signal:n.signal,onProgress:n.onProgress}),a=await(n.buildBaseDust??wf)(e,r),c=i.lastAppliedEventId>=0?ao(a,{state:i.state,lastAppliedEventId:i.lastAppliedEventId}):a;return{network:t,dustPublicKey:s,offset:i.lastAppliedEventId,balance:i.balance,eventCount:i.eventsApplied,fromCache:i.fromCache,partial:i.partial,snapshot:c}}var Tc=E(()=>{Dt();Ke();at()});var Nc={};fe(Nc,{default:()=>er});async function er(e,t){let r=e.subcommand;if(!r||r!=="register"&&r!=="status"&&r!=="export")throw new Z(`Missing or invalid subcommand.
|
|
277
277
|
Usage:
|
|
278
278
|
midnight dust register Register NIGHT UTXOs for dust generation
|
|
279
279
|
midnight dust status Check dust registration status
|
|
280
|
-
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=
|
|
280
|
+
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=te({args:e});if(Le(s,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},n),Re(e))De();let o=N(e,"json"),i=dt(e);if(r==="export"){await yf(mn(e),n,s,o,i,t);return}let a=ce(ie(A(e,"wallet"))),c=Buffer.from(a.seed,"hex"),d=a.addresses[n];if(r==="status"){let g=await Sf(d,n,s.indexerWS,t);if(!g.isRegistered){bf(n,g,o,i);return}let h=!N(e,"no-cache");await kf(c,s,g,o,i,h,t);return}lt(e);let u={},p=he((g,h)=>u.current?.(g,h)),f=Ce();try{await vf(c,s,o,t,u)}finally{f(),p()}}async function yf(e,t,r,n,s,o){let i=G(`Reading dust events from ${t}...`);try{let a=await Ec(e,t,r,{signal:o,onProgress:(c,d)=>i.update(d>0?`Reading dust events... ${c}/${d+1}`:`Reading dust events... ${c}`)});if(i.stop(a.partial?"Dust snapshot ready (incomplete)":a.fromCache&&a.eventCount===0?"Cache up to date":"Dust snapshot ready"),n){D({subcommand:"export",network:a.network,dustPublicKey:a.dustPublicKey,offset:a.offset,dustBalance:Wt(a.balance),eventCount:a.eventCount,fromCache:a.fromCache,partial:a.partial,snapshot:a.snapshot});return}if(process.stdout.write(a.snapshot+`
|
|
281
281
|
`),s)return;if(process.stderr.write(`
|
|
282
282
|
`+C("Network",a.network)+`
|
|
283
|
-
`),process.stderr.write(C("Dust balance",
|
|
283
|
+
`),process.stderr.write(C("Dust balance",Sr(a.balance))+`
|
|
284
284
|
`),process.stderr.write(C("Snapshot offset",String(a.offset))+`
|
|
285
285
|
`),a.partial)process.stderr.write(`
|
|
286
286
|
`+M(k("⚠ Snapshot is INCOMPLETE — the sync did not reach the chain tip."))+`
|
|
@@ -288,12 +288,12 @@ Usage:
|
|
|
288
288
|
`+l(" Re-run `mn dust export` to resume from this checkpoint and finish.")+`
|
|
289
289
|
`);process.stderr.write(`
|
|
290
290
|
`+l("Restore with the wallet SDK dustSerializedState to skip the cold dust sync.")+`
|
|
291
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
292
|
-
`+
|
|
291
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Sf(e,t,r,n){process.stderr.write(`
|
|
292
|
+
`+W("Dust Status")+`
|
|
293
293
|
|
|
294
294
|
`),process.stderr.write(C("Network",t)+`
|
|
295
295
|
|
|
296
|
-
`);let s=
|
|
296
|
+
`);let s=G(`Checking registration on ${t}...`);try{let o=await Kt(e,r,(c,d)=>{if(d>0){let u=Math.min(Math.round(c/d*100),100);s.update(u>=100?"Checking registration...":`Checking registration... ${u}%`)}});if(n?.aborted)throw Error("Operation cancelled");let{registeredUtxos:i,unregisteredUtxos:a}=o;return s.stop("Registration checked"),{isRegistered:i>0,registeredUtxos:i,unregisteredUtxos:a}}catch(o){throw s.fail("Failed"),o}}function bf(e,t,r,n){let{registeredUtxos:s,unregisteredUtxos:o}=t,i=s+o;if(r){if(n){D({network:e,registered:!1,registeredUtxos:s,unregisteredUtxos:o});return}D({subcommand:"status",registered:!1,registeredUtxos:s,unregisteredUtxos:o,network:e});return}if(process.stdout.write(`registered=no
|
|
297
297
|
`),process.stdout.write(`registered_utxos=${s}
|
|
298
298
|
`),process.stdout.write(`unregistered_utxos=${o}
|
|
299
299
|
`),process.stderr.write(C("Registered",k("no"))+`
|
|
@@ -303,46 +303,46 @@ Usage:
|
|
|
303
303
|
`);else process.stderr.write(`
|
|
304
304
|
`+l("Not generating dust. Run: midnight dust register")+`
|
|
305
305
|
`);process.stderr.write(`
|
|
306
|
-
`+
|
|
306
|
+
`+V()+`
|
|
307
307
|
|
|
308
|
-
`)}async function
|
|
309
|
-
`+
|
|
308
|
+
`)}async function vf(e,t,r,n,s){let o=t.networkId.toLowerCase();process.stderr.write(`
|
|
309
|
+
`+W("Dust Register")+`
|
|
310
310
|
|
|
311
311
|
`),process.stderr.write(C("Network",o)+`
|
|
312
312
|
|
|
313
|
-
`);let i=
|
|
313
|
+
`);let i=G("Syncing wallet...");if(s)s.current=(a,c)=>i.update(`Syncing wallet... (${c}, retrying)`);try{let{result:a,dustBal:c}=await me().withFacade(e,t,async({bundle:d,state:u})=>{if(n?.aborted)throw Error("Operation cancelled");i.update("Checking dust status...");let p=await tt(d,(g)=>i.update(g),u);if(n?.aborted)throw Error("Operation cancelled");let f=await Fa(d);return{result:p,dustBal:f.dust.balance(new Date)}},{syncMode:"lite",requireStrictSync:!0,signal:n,onStatus:(d)=>i.update(d),onSyncProgress:(d,u)=>{if(u>0){let p=Math.min(Math.round(d/u*100),100);i.update(p>=100?"Syncing wallet...":`Syncing wallet... ${p}%`)}},onSyncDetail:(d)=>i.update(`Syncing wallet... (waiting on: ${d})`)});if(i.stop(a.alreadyAvailable?"Dust already available":"Dust registration complete"),r){let d={subcommand:"register",dustBalance:Wt(c)};if(a.txHash)d.txHash=a.txHash;D(d);return}process.stdout.write(c.toString()+`
|
|
314
314
|
`),process.stderr.write(`
|
|
315
|
-
`+
|
|
315
|
+
`+pt(a.alreadyAvailable?`Dust tokens already available: ${Sr(c)}`:`Dust tokens available: ${Sr(c)}`)+`
|
|
316
316
|
|
|
317
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
317
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function kf(e,t,r,n,s,o,i){let a=t.networkId.toLowerCase(),c=G(`Reading dust events from ${a}...`);try{let d=await me().dust(e,t,{forceFresh:!o,signal:i,onStatus:(f)=>c.update(f)});c.stop(d.fromCache&&d.eventsApplied===0?"Cache up to date":"Dust events applied");let{registeredUtxos:u,unregisteredUtxos:p}=r;if(n){if(s){D({network:a,registered:!0,registeredUtxos:u,unregisteredUtxos:p,dustBalance:Wt(d.balance),dustAvailable:d.availableCoins>0});return}D({subcommand:"status",registered:!0,registeredUtxos:u,unregisteredUtxos:p,dustBalance:Wt(d.balance),dustAvailable:d.availableCoins>0,eventsApplied:d.eventsApplied,ownedUtxos:d.ownedUtxoCount,cached:d.fromCache,network:a});return}if(process.stdout.write(`registered=yes
|
|
318
318
|
`),process.stdout.write(`dust=${d.balance}
|
|
319
319
|
`),process.stdout.write(`registered_utxos=${u}
|
|
320
320
|
`),process.stdout.write(`unregistered_utxos=${p}
|
|
321
321
|
`),process.stderr.write(C("Registered",k("yes"))+`
|
|
322
322
|
`),process.stderr.write(C("UTXOs",`${u} registered, ${p} unregistered`)+`
|
|
323
|
-
`),process.stderr.write(C("Dust Balance",k(
|
|
323
|
+
`),process.stderr.write(C("Dust Balance",k(Sr(d.balance)))+`
|
|
324
324
|
`),process.stderr.write(C("Dust Available",d.availableCoins>0?"yes":"no")+`
|
|
325
325
|
`),process.stderr.write(C("Events applied",d.eventsApplied.toString()+(d.fromCache?" (delta)":""))+`
|
|
326
326
|
`),p>0)process.stderr.write(`
|
|
327
327
|
`+l(`${p} UTXO(s) not yet registered. Run: midnight dust register`)+`
|
|
328
328
|
`);process.stderr.write(`
|
|
329
|
-
`+
|
|
330
|
-
|
|
331
|
-
`)}catch(d){throw c.fail("Failed"),d}}var
|
|
332
|
-
`)}else if(n){if(
|
|
333
|
-
`)}else{if(
|
|
334
|
-
`)}}var
|
|
335
|
-
Valid keys: ${
|
|
336
|
-
Valid keys: ${
|
|
337
|
-
`)}else if(t==="unset"){
|
|
338
|
-
`)}else{let n=e.positionals[1];if(n===void 0)throw new
|
|
339
|
-
Usage: midnight config set ${r} <value>`);if(
|
|
340
|
-
`)}}var
|
|
329
|
+
`+V()+`
|
|
330
|
+
|
|
331
|
+
`)}catch(d){throw c.fail("Failed"),d}}var Un=E(()=>{Be();ot();ke();fn();pe();Ie();Ke();bt();Pr();Tc();at();ue();Ve()});var Rc={};fe(Rc,{default:()=>jn});async function jn(e){if(e.subcommand!=="clear")throw new Z("Usage: midnight cache clear [--network <name>] [--wallet <name|file>]");let r=A(e,"wallet"),n=A(e,"network"),s=N(e,"json");if(r){let o=ie(r),i=ce(o),{name:a}=te({args:e}),c=i.addresses[a];Je(c,a);let d=Ze(Buffer.from(i.seed,"hex"));gt(a,d),Tn(a,d);let u=oc(Buffer.from(i.seed,"hex"));if($n(a,u),s){D({action:"clear",scope:"wallet",wallet:r,network:a});return}process.stderr.write(H("✓")+` Cache cleared for wallet "${r}" on ${a}
|
|
332
|
+
`)}else if(n){if(Je(void 0,n),gt(n),Tn(n),$n(n),s){D({action:"clear",scope:"network",network:n});return}process.stderr.write(H("✓")+` Cache cleared for network "${n}"
|
|
333
|
+
`)}else{if(Je(),gt(),Tn(),$n(),s){D({action:"clear",scope:"all"});return}process.stderr.write(H("✓")+` Cache cleared
|
|
334
|
+
`)}}var $o=E(()=>{Be();yt();Dt();vo();ho();ke();pe()});var $c={};fe($c,{default:()=>Wn});async function Wn(e){let t=e.subcommand;if(!t||!["get","set","unset"].includes(t))throw new Z(`Usage: midnight config <get|set|unset> <key> [value]
|
|
335
|
+
Valid keys: ${Ws().join(", ")}`);let r=e.positionals[0];if(!r)throw new Z(`Missing config key.
|
|
336
|
+
Valid keys: ${Ws().join(", ")}`);if(t==="get"){let n=ca(r);if(N(e,"json")){D({action:"get",key:r,value:n});return}process.stdout.write(n+`
|
|
337
|
+
`)}else if(t==="unset"){la(r);let n=r==="network"?"(default)":"(removed)";if(N(e,"json")){D({action:"unset",key:r,value:n});return}process.stderr.write(H("✓")+` ${r} ${n}
|
|
338
|
+
`)}else{let n=e.positionals[1];if(n===void 0)throw new Z(`Missing value for config set.
|
|
339
|
+
Usage: midnight config set ${r} <value>`);if(da(r,n),N(e,"json")){D({action:"set",key:r,value:n});return}process.stderr.write(H("✓")+` ${r} = ${n}
|
|
340
|
+
`)}}var Io=E(()=>{Be();Bt()});import{execSync as Kr}from"child_process";import{existsSync as Ic,mkdirSync as Cf,readFileSync as Af,writeFileSync as _c}from"fs";import{homedir as xf}from"os";import{join as Do}from"path";function Gn(){try{return Kr("docker compose version",{...Hn,timeout:1e4}).trim()}catch{try{throw Kr("docker --version",{...Hn,timeout:5000}),Error(`Docker Compose v2 is required.
|
|
341
341
|
Install it from https://docs.docker.com/compose/install/`)}catch(e){if(e instanceof Error&&e.message.includes("Docker Compose v2"))throw e;throw Error(`Docker is required but was not found.
|
|
342
|
-
Install Docker from https://docs.docker.com/get-docker/`)}}}function
|
|
343
|
-
`),r=[];for(let n of t){if(!n.trim())continue;try{let s=JSON.parse(n),o=s.Service??"unknown";r.push({name:o,state:s.State??"unknown",health:s.Health??"",port
|
|
342
|
+
Install Docker from https://docs.docker.com/get-docker/`)}}}function tr(){if(Ic(_o)&&Ic(Bn)&&Af(_o,"utf-8").trim()===Dc)return!1;return Cf(Po,{recursive:!0,mode:Se}),_c(Bn,Rf,"utf-8"),_c(_o,Dc,"utf-8"),!0}function ze(e){return Kr(`docker compose -f "${Bn}" ${e}`,Hn)}function ct(){try{let e=ze("ps --format json");if(!e.trim())return[];let t=e.trim().split(`
|
|
343
|
+
`),r=[];for(let n of t){if(!n.trim())continue;try{let s=JSON.parse(n),o=s.Service??"unknown";r.push({name:o,state:s.State??"unknown",health:s.Health??"",port:$f[o]??"",image:s.Image??""})}catch{}}return r}catch{return[]}}function rr(e=120000,t=3000){let r=Date.now()+e;while(Date.now()<r){let n=ct();if(n.length===3&&n.every((o)=>o.state==="running")){if(n.every((i)=>i.health==="healthy"||i.health===""))return!0}Kr(`sleep ${t/1000}`,{timeout:t+1000})}return!1}function Oo(){return Bn}function Pc(){let e=[];for(let t of Mo)try{Kr(`docker rm -f "${t}"`,{...Hn,timeout:1e4}),e.push(t)}catch{}return e}var Dc="3.0.6",Ef="midnightntwrk/midnight-node:1.0.0",Tf="midnightntwrk/indexer-standalone:4.3.3",Nf="midnightntwrk/proof-server:8.1.0",Po,Bn,_o,Rf,Hn,$f,Mo;var Kn=E(()=>{Po=Do(xf(),ae,Vi),Bn=Do(Po,"compose.yml"),_o=Do(Po,".version"),Rf=`services:
|
|
344
344
|
proof-server:
|
|
345
|
-
image: '${
|
|
345
|
+
image: '${Nf}'
|
|
346
346
|
container_name: "proof-server"
|
|
347
347
|
# Self-heal across Docker Desktop restarts and transient stops. Without this,
|
|
348
348
|
# a stopped node/proof-server never comes back while the indexer (below) does,
|
|
@@ -353,7 +353,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function ur(){if(Gc(
|
|
|
353
353
|
- "6300:6300"
|
|
354
354
|
|
|
355
355
|
indexer:
|
|
356
|
-
image: '${
|
|
356
|
+
image: '${Tf}'
|
|
357
357
|
container_name: "indexer"
|
|
358
358
|
# unless-stopped covers two cases: (1) indexer >=4.3.x runs an SPO sub-indexer
|
|
359
359
|
# that queries block #1 at startup and exits the whole process if it isn't there
|
|
@@ -389,7 +389,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function ur(){if(Gc(
|
|
|
389
389
|
condition: service_started
|
|
390
390
|
|
|
391
391
|
node:
|
|
392
|
-
image: '${
|
|
392
|
+
image: '${Ef}'
|
|
393
393
|
container_name: "node"
|
|
394
394
|
# Self-heal across Docker Desktop restarts / transient stops (see proof-server).
|
|
395
395
|
restart: unless-stopped
|
|
@@ -403,38 +403,38 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function ur(){if(Gc(
|
|
|
403
403
|
start_period: 5s
|
|
404
404
|
environment:
|
|
405
405
|
CFG_PRESET: "dev"
|
|
406
|
-
`,
|
|
407
|
-
`)}async function
|
|
408
|
-
`);let r=
|
|
406
|
+
`,Hn={encoding:"utf-8",timeout:30000};$f={node:"9944",indexer:"8088","proof-server":"6300"};Mo=["node","indexer","proof-server"]});async function Oc(e,t={}){let r=t.timeoutMs??30000,n=t.pollIntervalMs??1000,s=Date.now()+r;while(Date.now()<s){try{let o=await zt({url:e,timeoutMs:3000},"chain_getHeader"),i=typeof o?.number==="string"?o.number:"0x0",a=Number.parseInt(i,16);if(Number.isFinite(a)&&a>=1)return}catch{}await new Promise((o)=>setTimeout(o,n))}throw Error(`Node did not produce a block within ${r/1000}s`)}var Mc=E(()=>{Cn()});async function Fc(e,t,r={}){let n=r.timeoutMs??30000,s=r.pollIntervalMs??1000,o=Date.now()+n;while(Date.now()<o){try{if((await Kt(t,e)).utxoCount>0)return}catch{}await new Promise((i)=>setTimeout(i,s))}throw Error(`Indexer did not report funds for ${t.slice(0,20)}… within ${n/1000}s`)}var Lc=E(()=>{Pr()});async function Uc(e,t={}){let r=t.timeoutMs??30000,n=t.pollIntervalMs??1000,s=t.requestTimeoutMs??2000,o=Date.now()+r,i=e.endsWith("/")?e:e+"/";while(Date.now()<o){try{let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{if((await fetch(i,{method:"GET",signal:a.signal})).ok)return}finally{clearTimeout(c)}}catch{}await new Promise((a)=>setTimeout(a,n))}throw Error(`Proof server at ${i} did not respond within ${r/1000}s`)}var Hc={};fe(Hc,{default:()=>Jn});import{spawn as jc}from"child_process";import{existsSync as If,rmSync as _f}from"node:fs";import{resolve as Df}from"node:path";function Pf(e){return Wc.includes(e)}function Bc(e){let t=[];for(let r of e){let n=r.state==="running"?H:J,s=r.health?` (${r.health})`:"",o=r.port?`:${r.port}`:"",i=r.image?` ${l(r.image)}`:"";if(t.push(` ${r.name.padEnd(16)}${n(r.state)}${l(s)}${l(o)}`),i)t.push(i)}return t.join(`
|
|
407
|
+
`)}async function Of(e){if(tr())process.stderr.write(l(` Wrote compose.yml to ${Oo()}`)+`
|
|
408
|
+
`);let r=G("Starting local network...");try{if(ze("up -d"),r.update("Waiting for services to be healthy..."),!rr(120000))r.stop(M("Services started but not all healthy yet")),process.stderr.write(`
|
|
409
409
|
`+l(" Tip: run ")+k("midnight localnet logs")+l(" to check for errors")+`
|
|
410
|
-
`);else{r.update("Waiting for chain to produce first block...");try{
|
|
410
|
+
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() => Mc());await Promise.resolve().then(() => Lc());await Promise.resolve();await Promise.resolve().then(() => Ie());await Promise.resolve().then(() => Ge());await Promise.resolve();let p=Ar("undeployed");await Oc(p.node,{timeoutMs:30000}),r.update("Waiting for indexer to ingest genesis state...");let f=ve(Buffer.from(rt,"hex"),"undeployed");await Fc(p.indexerWS,f,{timeoutMs:30000}),r.update("Waiting for proof server..."),await Uc(p.proofServer,{timeoutMs:30000}),r.stop("Local network is running")}catch(o){r.stop(M("Services running but chain/indexer/proof-server not fully ready yet")),process.stderr.write(`
|
|
411
411
|
`+l(" Tip: give it a few more seconds then retry. Run ")+k("midnight localnet logs")+l(" if this persists.")+`
|
|
412
412
|
`)}}}catch(s){if(r.fail("Failed to start local network"),s instanceof Error){if(s.message.includes("is already in use by container"))throw Error(`Container name conflict — containers with the same names already exist
|
|
413
413
|
`+`(likely from a previous midnight-local-network setup).
|
|
414
414
|
|
|
415
415
|
Run "midnight localnet clean" to remove them, then try again.`);if(s.message.includes("address already in use"))throw Error(`Port conflict detected — another process is using a required port.
|
|
416
|
-
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=
|
|
417
|
-
`+
|
|
416
|
+
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=ct();if(e){D({subcommand:"up",services:n.map((s)=>({name:s.name,state:s.state,port:s.port,health:s.health,image:s.image}))});return}if(n.length>0)process.stderr.write(`
|
|
417
|
+
`+Bc(n)+`
|
|
418
418
|
`);for(let s of n)process.stdout.write(`${s.name}=${s.state}:${s.port}
|
|
419
419
|
`);process.stderr.write(`
|
|
420
420
|
`+l(" Next: ")+k("midnight wallet generate dev --network undeployed")+`
|
|
421
|
-
`)}async function
|
|
422
|
-
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function
|
|
423
|
-
`+
|
|
421
|
+
`)}async function Mf(e){let t=G("Stopping local network...");try{if(ze("stop"),t.stop("Local network stopped (containers preserved)"),e){D({subcommand:"stop",status:"stopped"});return}}catch(r){throw t.fail("Failed to stop local network"),r}}async function Ff(e){let t=G("Tearing down local network...");try{ze("down --volumes");await Promise.resolve().then(() => yt());await Promise.resolve().then(() => Dt());Je(void 0,"undeployed"),gt("undeployed");let s=Lf();if(t.stop("Local network removed (containers, networks, volumes, caches)"),e){D({subcommand:"down",status:"removed",cachesCleared:!0,dappLevelDbWiped:s});return}if(s)process.stderr.write(l(" Also cleared dapp leveldb at ./midnight-level-db (private state from old chain)")+`
|
|
422
|
+
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function Lf(){let e=Df(process.cwd(),"midnight-level-db");if(!If(e))return!1;try{return _f(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function Uf(e){let t=ct();if(e){D({subcommand:"status",services:t.map((r)=>({name:r.name,state:r.state,port:r.port,health:r.health,image:r.image}))});return}if(t.length===0){process.stderr.write(`
|
|
423
|
+
`+W("Localnet Status")+`
|
|
424
424
|
|
|
425
425
|
`),process.stderr.write(l(" No services running.")+`
|
|
426
426
|
`),process.stderr.write(l(" Run ")+k("midnight localnet up")+l(" to start.")+`
|
|
427
427
|
|
|
428
428
|
`);return}process.stderr.write(`
|
|
429
|
-
`+
|
|
429
|
+
`+W("Localnet Status")+`
|
|
430
430
|
|
|
431
|
-
`),process.stderr.write(
|
|
431
|
+
`),process.stderr.write(Bc(t)+`
|
|
432
432
|
`),process.stderr.write(`
|
|
433
|
-
`+
|
|
433
|
+
`+V()+`
|
|
434
434
|
|
|
435
435
|
`);for(let r of t)process.stdout.write(`${r.name}=${r.state}:${r.port}
|
|
436
|
-
`)}async function
|
|
437
|
-
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",u)})}let s=
|
|
436
|
+
`)}async function jf(e){let t=G("Removing conflicting containers...");try{try{ze("down")}catch{}let r=Pc();if(r.length>0)t.stop(`Removed ${r.length} container${r.length>1?"s":""}: ${r.join(", ")}`);else t.stop("No conflicting containers found");if(e){D({subcommand:"clean",status:"cleaned",removed:r});return}}catch(r){throw t.fail("Failed to clean up"),r}}async function Wf(e){let t=Oo(),r=A(e,"tail"),n=N(e,"json");if(r!==void 0||n){let o=r??"200",i=jc("docker",["compose","-f",t,"logs","--tail",o,"--no-color"],{stdio:["ignore","pipe","pipe"]}),a="",c="";return i.stdout.on("data",(d)=>{a+=d.toString()}),i.stderr.on("data",(d)=>{c+=d.toString()}),new Promise((d,u)=>{i.on("close",(p)=>{if(p!==0&&p!==null){u(Error(`docker compose logs exited with code ${p}: ${c.trim()}`));return}if(n)D({tail:Number(o),lines:a.split(`
|
|
437
|
+
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",u)})}let s=jc("docker",["compose","-f",t,"logs","-f"],{stdio:"inherit"});return new Promise((o,i)=>{s.on("close",(a)=>{if(a===0||a===130||a===null)o();else i(Error(`docker compose logs exited with code ${a}`))}),s.on("error",i)})}async function Jn(e){let t=e.subcommand;if(!t||!Pf(t))throw new Z(`Usage: midnight localnet <${Wc.join("|")}>
|
|
438
438
|
|
|
439
439
|
Subcommands:
|
|
440
440
|
up Start the local network
|
|
@@ -444,17 +444,17 @@ Subcommands:
|
|
|
444
444
|
logs Stream service logs
|
|
445
445
|
clean Remove conflicting containers
|
|
446
446
|
|
|
447
|
-
Example: midnight localnet up`);
|
|
448
|
-
`+
|
|
447
|
+
Example: midnight localnet up`);Gn();let r=N(e,"json");switch(process.stderr.write(`
|
|
448
|
+
`+W("Localnet")+`
|
|
449
449
|
|
|
450
|
-
`),t){case"up":return
|
|
450
|
+
`),t){case"up":return Of(r);case"stop":return Mf(r);case"down":return Ff(r);case"status":return Uf(r);case"logs":return Wf(e);case"clean":return jf(r)}}var Wc;var Fo=E(()=>{Be();Kn();ue();Ve();Wc=["up","stop","down","status","logs","clean"]});var Jc={};fe(Jc,{default:()=>nr});import*as Kc from"fs";import*as Lo from"path";import{homedir as Bf}from"os";import{generateMnemonic as Hf,mnemonicToSeedSync as Gc,mnemonicToEntropy as Gf,validateMnemonic as Kf}from"@scure/bip39";import{wordlist as Uo}from"@scure/bip39/wordlists/english.js";async function nr(e){let t=e.subcommand;switch(t){case"generate":return Jf(e);case"list":case"ls":return Vf(e);case"use":return zf(e);case"info":return qf(e);case"remove":case"rm":return Xf(e);case"seed":return Yf(e);default:throw new Z(`Unknown wallet subcommand: "${t??"(none)"}"
|
|
451
451
|
Available: generate, list, use, info, remove, seed
|
|
452
|
-
Run "midnight help wallet" for usage.`)}}async function
|
|
453
|
-
Usage: midnight wallet generate <name> [--network <name>]`);if(!
|
|
454
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=
|
|
455
|
-
Use --force to overwrite.`);let a,c;if(n!==void 0){let m=n.replace(/^0x/,"");if(m.length!==64||!/^[0-9a-fA-F]+$/.test(m))throw Error("Seed must be a 64-character hex string (32 bytes)");a=Buffer.from(m,"hex")}else if(s!==void 0){if(!
|
|
452
|
+
Run "midnight help wallet" for usage.`)}}async function Jf(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
453
|
+
Usage: midnight wallet generate <name> [--network <name>]`);if(!At(t))throw Error(`Invalid wallet name: "${t}"
|
|
454
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=_e({args:e}),n=A(e,"seed"),s=A(e,"mnemonic");if(n!==void 0&&s!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let o=Lo.join(Bf(),ae,Lt),i=Lo.join(o,`${t}.json`);if(Kc.existsSync(i)&&!N(e,"force"))throw Error(`Wallet "${t}" already exists: ${i}
|
|
455
|
+
Use --force to overwrite.`);let a,c;if(n!==void 0){let m=n.replace(/^0x/,"");if(m.length!==64||!/^[0-9a-fA-F]+$/.test(m))throw Error("Seed must be a 64-character hex string (32 bytes)");a=Buffer.from(m,"hex")}else if(s!==void 0){if(!Kf(s,Uo))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");c=s,a=Buffer.from(Gc(c))}else c=Hf(Uo,256),a=Buffer.from(Gc(c));let d=Rt(a),u=Rr(a),p=d[r],f={seed:a.toString("hex"),addresses:d,shieldedAddresses:u,createdAt:new Date().toISOString()};if(c)f.mnemonic=c;let g=cn(f,i);if(Ir(t),N(e,"json")){let m={name:t,addresses:d,shieldedAddresses:u,activeAddress:p,activeNetwork:r,seed:a.toString("hex"),file:g,createdAt:f.createdAt,active:!0};if(c)m.mnemonic=c;D(m);return}process.stdout.write(p+`
|
|
456
456
|
`),process.stderr.write(`
|
|
457
|
-
`+
|
|
457
|
+
`+W("Wallet Generated")+`
|
|
458
458
|
|
|
459
459
|
`),process.stderr.write(C("Name",t)+`
|
|
460
460
|
`),process.stderr.write(C("Network",r)+`
|
|
@@ -469,28 +469,28 @@ Use --force to overwrite.`);let a,c;if(n!==void 0){let m=n.replace(/^0x/,"");if(
|
|
|
469
469
|
`);process.stderr.write(M(k(" SEED (hex):"))+`
|
|
470
470
|
`),process.stderr.write(` ${a.toString("hex")}
|
|
471
471
|
|
|
472
|
-
`),process.stderr.write(
|
|
472
|
+
`),process.stderr.write(V()+`
|
|
473
473
|
`),process.stderr.write(l(" Next: midnight wallet list | midnight balance")+`
|
|
474
474
|
|
|
475
|
-
`),process.stderr.write(
|
|
476
|
-
`)}async function
|
|
475
|
+
`),process.stderr.write(H("✓")+` Wallet saved
|
|
476
|
+
`)}async function Vf(e){let t=Vs(),r=_e({args:e});if(N(e,"json")){if(dt(e)){D({activeNetwork:r,wallets:t.map((a)=>({name:a.name,active:a.isActive,network:r,address:a.addresses[r]??null,shieldedAddress:a.shieldedAddresses?.[r]??null}))});return}D({activeNetwork:r,wallets:t.map((a)=>({name:a.name,active:a.isActive,addresses:a.addresses,shieldedAddresses:a.shieldedAddresses,createdAt:a.createdAt,file:a.file}))});return}if(t.length===0){process.stderr.write(`
|
|
477
477
|
No wallets found.
|
|
478
478
|
`),process.stderr.write(l(" Create one: midnight wallet generate <name> --network <name>")+`
|
|
479
479
|
|
|
480
480
|
`);return}process.stderr.write(`
|
|
481
|
-
`+
|
|
481
|
+
`+W("Wallets")+`
|
|
482
482
|
|
|
483
483
|
`);let n=Math.max(...t.map((a)=>a.name.length)),s=19,o=19,i=" ".repeat(n-4);process.stderr.write(` ${l("name")}${i} ${l("unshielded".padEnd(s))} ${l("shielded")}
|
|
484
|
-
`);for(let a of t){let c=a.isActive?
|
|
484
|
+
`);for(let a of t){let c=a.isActive?H("●"):" ",d=a.isActive?k(L(a.name)):L(a.name),u=" ".repeat(n-a.name.length),p=a.addresses[r]??"(unknown)",f=a.shieldedAddresses?.[r],g=f?re(f,!0):l("—".padEnd(o));process.stderr.write(` ${c} ${d}${u} ${re(p,!0)} ${g}
|
|
485
485
|
`)}process.stderr.write(`
|
|
486
|
-
`+
|
|
486
|
+
`+V()+`
|
|
487
487
|
`),process.stderr.write(l(` ● = active wallet · network: ${r} · details: midnight wallet info <name>`)+`
|
|
488
488
|
|
|
489
|
-
`)}async function
|
|
490
|
-
Usage: midnight wallet use <name>`);if(
|
|
491
|
-
`)}async function
|
|
489
|
+
`)}async function zf(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
490
|
+
Usage: midnight wallet use <name>`);if(Ir(t),N(e,"json")){D({wallet:t,active:!0});return}process.stderr.write(H("✓")+` Active wallet set to "${t}"
|
|
491
|
+
`)}async function qf(e){let t=A(e,"wallet")??e.positionals[0]??ft(),r=ie(t),n=ce(r),s=t===ft(),o=_e({args:e}),i=n.addresses[o];if(N(e,"json")){if(dt(e)){D({name:t,active:s,network:o,address:i,shieldedAddress:n.shieldedAddresses?.[o]??null});return}let c={name:t,addresses:n.addresses,activeAddress:i,activeNetwork:o,createdAt:n.createdAt,file:r,active:s};if(n.shieldedAddresses)c.shieldedAddresses=n.shieldedAddresses;D(c);return}process.stdout.write(i+`
|
|
492
492
|
`),process.stderr.write(`
|
|
493
|
-
`+
|
|
493
|
+
`+W(`Wallet: ${t}`)+`
|
|
494
494
|
|
|
495
495
|
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],u=d===o,p=n.addresses[d],f=n.shieldedAddresses?.[d],g=u?k(L(d))+l(" (active)"):d;if(process.stderr.write(` ${g}
|
|
496
496
|
`),process.stderr.write(` ${l("unshielded")} ${re(p)}
|
|
@@ -498,21 +498,21 @@ Usage: midnight wallet use <name>`);if(Qt(t),N(e,"json")){P({wallet:t,active:!0}
|
|
|
498
498
|
`);else process.stderr.write(` ${l("shielded ")} ${l("(unavailable)")}
|
|
499
499
|
`);if(c<a.length-1)process.stderr.write(`
|
|
500
500
|
`)}process.stderr.write(`
|
|
501
|
-
`+
|
|
501
|
+
`+V()+`
|
|
502
502
|
|
|
503
503
|
`),process.stderr.write(` ${l("created")} ${n.createdAt}
|
|
504
504
|
`),process.stderr.write(` ${l("file ")} ${r}
|
|
505
|
-
`),process.stderr.write(` ${l("active ")} ${s?
|
|
505
|
+
`),process.stderr.write(` ${l("active ")} ${s?H("yes"):"no"}
|
|
506
506
|
|
|
507
|
-
`)}async function
|
|
508
|
-
Usage: midnight wallet remove <name>`);if(
|
|
509
|
-
`)}async function
|
|
510
|
-
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(
|
|
507
|
+
`)}async function Xf(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
508
|
+
Usage: midnight wallet remove <name>`);if(wa(t),N(e,"json")){D({wallet:t,removed:!0});return}process.stderr.write(H("✓")+` Wallet "${t}" removed
|
|
509
|
+
`)}async function Yf(e){let t=A(e,"wallet")??e.positionals[0]??ft(),r=ie(t),n=await import("fs"),s=JSON.parse(n.readFileSync(r,"utf-8"));if(!s.seed)throw Error(`Wallet "${t}" has no seed in ${r}`);let o=N(e,"entropy"),i;if(o){if(!s.mnemonic)throw Error(`Wallet "${t}" has no mnemonic on file — cannot derive BIP-39 entropy.
|
|
510
|
+
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(Gf(s.mnemonic,Uo)).toString("hex")}if(N(e,"json")){let c={name:t,seed:s.seed};if(s.mnemonic)c.mnemonic=s.mnemonic;if(i)c.entropy=i;D(c);return}if(process.stderr.write(`
|
|
511
511
|
`),process.stderr.write(M(k(" ⚠ WARNING: This will display your wallet seed and mnemonic."))+`
|
|
512
512
|
`),process.stderr.write(M(" Anyone with this seed can access your funds.")+`
|
|
513
513
|
`),process.stderr.write(M(" Never share it. Never paste it into a website.")+`
|
|
514
514
|
`),process.stderr.write(`
|
|
515
|
-
`),!await
|
|
515
|
+
`),!await Zf(" Show seed? (y/N) ")){process.stderr.write(l(" Cancelled.")+`
|
|
516
516
|
|
|
517
517
|
`);return}if(process.stdout.write(s.seed+`
|
|
518
518
|
`),process.stderr.write(`
|
|
@@ -525,52 +525,51 @@ Usage: midnight wallet remove <name>`);if(po(t),N(e,"json")){P({wallet:t,removed
|
|
|
525
525
|
`),process.stderr.write(l(" Note: seed and entropy derive DIFFERENT Midnight wallets from the")+`
|
|
526
526
|
`),process.stderr.write(l(" same mnemonic. Use the value your target project accepts.")+`
|
|
527
527
|
`);process.stderr.write(`
|
|
528
|
-
`)}function
|
|
528
|
+
`)}function Zf(e){return new Promise((t)=>{let r=xs("readline"),n=r.createInterface({input:process.stdin,output:process.stderr});n.question(e,(s)=>{n.close(),t(s.trim().toLowerCase()==="y")})})}var Vn=E(()=>{Be();Ge();pe();ke();ue()});var Yc={};fe(Yc,{default:()=>Xc});function Wo(e){let t=Date.now()-new Date(e).getTime();if(t<60000)return"just now";if(t<3600000)return`${Math.floor(t/60000)}m ago`;if(t<86400000)return`${Math.floor(t/3600000)}h ago`;return`${Math.floor(t/86400000)}d ago`}function jo(e){let t=!1,r=!1;for(let n of Object.values(e)){if(n.status==="down")t=!0;if(n.status==="degraded")r=!0}if(t)return"down";if(r)return"degraded";return"up"}async function zn(e){let t=`${nn}${e}`,r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw Error(`Dashboard returned HTTP ${r.status} for ${e}`);return r.json()}async function rg(e){let t=A(e,"network");if(t)return t;try{await Promise.resolve().then(() => Bt());let n=Ee();if(n.network&&xe(n.network))return n.network}catch{}return}async function Xn(e,t={}){let r=new AbortController,n=setTimeout(()=>r.abort(),tg),s=Date.now();try{return{response:await fetch(e,{...t,signal:r.signal}),latencyMs:Date.now()-s}}finally{clearTimeout(n)}}async function ng(e){let t=new Date().toISOString();try{let{response:r,latencyMs:n}=await Xn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"{ block { height } }"})});if(!r.ok){if(r.status===403)return{status:"degraded",latencyMs:n,lastChecked:t,notes:"HTTP 403 — likely WAF blocking"};return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`}}let s=await r.json();if(!s?.data)return{status:"down",latencyMs:n,lastChecked:t,notes:"No data field"};let o=s.data?.block?.height;return{status:n>qn?"degraded":"up",latencyMs:n,lastChecked:t,...o!==void 0?{blockHeight:o}:{},...n>qn?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function sg(e){let t=new Date().toISOString(),r=e.replace(/^wss:/,"https:").replace(/^ws:/,"http:");try{let{response:n,latencyMs:s}=await Xn(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"system_health",params:[]})});if(!n.ok){if(n.status===403)return{status:"degraded",latencyMs:s,lastChecked:t,notes:"HTTP 403 — likely WAF blocking"};return{status:"down",latencyMs:s,lastChecked:t,notes:`HTTP ${n.status}`}}let i=(await n.json())?.result;if(!i)return{status:"down",latencyMs:s,lastChecked:t,notes:"No result in response"};let a=i.peers??0,c=i.isSyncing??!1,d="up",u;if(c)d="degraded",u="Node is syncing";else if(a===0)d="degraded",u="No peers";return{status:d,latencyMs:s,lastChecked:t,peers:a,isSyncing:c,...u?{notes:u}:{}}}catch(n){return{status:"down",latencyMs:0,lastChecked:t,notes:n.message}}}async function og(e){let t=new Date().toISOString();if(!e)return{status:"unknown",latencyMs:0,lastChecked:t,notes:"No faucet URL"};try{let{response:r,latencyMs:n}=await Xn(e);if(!r.ok)return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`};return{status:n>zc?"degraded":"up",latencyMs:n,lastChecked:t,...n>zc?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function ig(e){let t=new Date().toISOString();if(!e)return{status:"unknown",latencyMs:0,lastChecked:t,notes:"URL not configured"};try{let{response:r,latencyMs:n}=await Xn(e);if(!r.ok)return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`};let s=await r.text();if(!s||s.length===0)return{status:"down",latencyMs:n,lastChecked:t,notes:"Empty response"};return{status:n>qn?"degraded":"up",latencyMs:n,lastChecked:t,...n>qn?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function qc(e){if(!xe(e))return{};let t=Ar(e),r=Qf[e];if(!r)return{};let[n,s,o,i]=await Promise.all([ng(t.indexer),sg(t.node),og(r.faucet),ig(r.explorer)]);return{indexer:n,rpc:s,faucet:o,explorer:i}}function ag(e,t,r){process.stderr.write(`
|
|
529
529
|
`+k(e)+`
|
|
530
530
|
`),process.stderr.write(l(" "+"─".repeat(62))+`
|
|
531
|
-
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(
|
|
532
|
-
`)}else if(i){let c=
|
|
533
|
-
`)}}}function
|
|
534
|
-
`+
|
|
531
|
+
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(eg[s]??s).padEnd(18);if(o){let c=Vc[o.status]??l("—"),d=o.latencyMs>0?l(` ${o.latencyMs}ms`):"",u=o.notes?l(` — ${o.notes}`):"",p="";if(i&&i.status!==o.status&&i.status!=="unknown")p=l(` (canary: ${i.status}${i.lastChecked?" "+Wo(i.lastChecked):""})`);process.stderr.write(` ${nt(a)}${c}${d}${u}${p}
|
|
532
|
+
`)}else if(i){let c=Vc[i.status]??l("—"),d=i.latencyMs>0?l(` ${i.latencyMs}ms`):"",u=i.lastChecked?l(` (${Wo(i.lastChecked)})`):"",p=i.notes?l(` — ${i.notes}`):"";process.stderr.write(` ${nt(a)}${c}${d}${u}${p}
|
|
533
|
+
`)}}}function cg(e,t){let r=t?e.filter((n)=>n.affects.toLowerCase().includes(t.toLowerCase())):e;if(r.length===0)return;process.stderr.write(`
|
|
534
|
+
`+W("Known Issues")+`
|
|
535
535
|
|
|
536
|
-
`);for(let n of r)process.stderr.write(` ${
|
|
536
|
+
`);for(let n of r)process.stderr.write(` ${J(n.id.padEnd(28))}${n.summary}
|
|
537
537
|
`),process.stderr.write(` ${" ".repeat(28)}${l(n.status)}
|
|
538
|
-
`)}async function
|
|
539
|
-
`+
|
|
540
|
-
`),i?.lastUpdated)process.stderr.write(l(` Canary: ${
|
|
538
|
+
`)}async function Xc(e){let t=N(e,"json"),r=N(e,"all"),n=N(e,"watch"),s=await rg(e)??"preprod",o=G("Checking network status..."),i=null,a=null,c,d;if(r)d=["preprod","preview"];else d=[s];let[u,...p]=await Promise.all([Promise.all([zn("/api/status"),zn("/api/issues")]).catch((m)=>(c=m.message,null)),...d.map((m)=>qc(m))]);if(u)[i,a]=u;o.stop("Done");let f={};for(let m=0;m<d.length;m++)f[d[m]]=p[m];if(t){let m={lastUpdated:i?.lastUpdated??null,dashboard:nn,canaryAvailable:i!==null,networks:{}};for(let y of d){let S=f[y]??{},b=i?.networks[y],v={...b,...S};m.networks[y]={overall:jo(v),live:S,canary:b??null}}if(a){let y=r?void 0:d[0];m.issues=y?a.issues.filter((S)=>S.affects.toLowerCase().includes(y.toLowerCase())):a.issues}if(c)m.canaryError=c;D(m);let w=d.reduce((y,S)=>{let b={...i?.networks[S]??{},...f[S]??{}},v=jo(b);if(v==="down")return"down";if(v==="degraded"&&y!=="down")return"degraded";return y},"up");if(w==="down")process.exitCode=2;else if(w==="degraded")process.exitCode=1;return}let g=()=>{if(process.stderr.write(`
|
|
539
|
+
`+W("Midnight Network Status")+`
|
|
540
|
+
`),i?.lastUpdated)process.stderr.write(l(` Canary: ${Wo(i.lastUpdated)}`)+" ");if(process.stderr.write(l("Live: just now")+`
|
|
541
541
|
`),c)process.stderr.write(l(` (Dashboard unreachable: ${c})`)+`
|
|
542
542
|
`);if(d.length===0){process.stderr.write(`
|
|
543
543
|
`+l("No network data available.")+`
|
|
544
544
|
|
|
545
|
-
`);return}for(let m of d)
|
|
546
|
-
`+
|
|
547
|
-
`),process.stderr.write(l(" Dashboard: ")+L(
|
|
548
|
-
|
|
549
|
-
`)};if(g(),n){let m=setInterval(async()=>{try{let[w,...y]=await Promise.all([Promise.all([
|
|
550
|
-
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(m),process.exit(0)})})}let h=d.reduce((m,w)=>{let y={...i?.networks[w]??{},...f[w]??{}},S=
|
|
551
|
-
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((u)=>u!==a),d=
|
|
552
|
-
Expected: managed/<name>/compiler/${
|
|
553
|
-
Searched: ${
|
|
554
|
-
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function
|
|
555
|
-
`),"approve";if(t.autoApproveReads&&
|
|
556
|
-
`),"approve";if(
|
|
557
|
-
`)
|
|
558
|
-
`),process.stderr.write(
|
|
559
|
-
`),"reject";if(Kr)return process.stderr.write(V(" Rejected: another approval prompt is active")+`
|
|
545
|
+
`);return}for(let m of d)ag(m,i?.networks[m],f[m]??{});if(a){let m=r?void 0:d[0];cg(a.issues,m)}process.stderr.write(`
|
|
546
|
+
`+V()+`
|
|
547
|
+
`),process.stderr.write(l(" Dashboard: ")+L(nn)+`
|
|
548
|
+
|
|
549
|
+
`)};if(g(),n){let m=setInterval(async()=>{try{let[w,...y]=await Promise.all([Promise.all([zn("/api/status"),zn("/api/issues")]).catch(()=>null),...d.map((S)=>qc(S))]);if(w)[i,a]=w;for(let S=0;S<d.length;S++)f[d[S]]=y[S];process.stderr.write("\x1B[2J\x1B[H"),g()}catch{process.stderr.write(l(" Refresh failed — retrying in 30s")+`
|
|
550
|
+
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(m),process.exit(0)})})}let h=d.reduce((m,w)=>{let y={...i?.networks[w]??{},...f[w]??{}},S=jo(y);if(S==="down")return"down";if(S==="degraded"&&m!=="down")return"degraded";return m},"up");if(h==="down")process.exitCode=2;else if(h==="degraded")process.exitCode=1}var Qf,eg,Vc,tg=15000,qn=5000,zc=1e4;var Zc=E(()=>{Ie();ue();Ve();Qf={preprod:{faucet:"https://faucet.preprod.midnight.network/",explorer:"https://preprod.midnightexplorer.com/"},preview:{faucet:"https://faucet.preview.midnight.network/",explorer:null},undeployed:{faucet:"",explorer:""}},eg={indexer:"Indexer",rpc:"RPC Node",faucet:"Faucet",explorer:"Explorer",chain:"Chain",dust:"Dust Generation",wallet:"Wallet Ops",dapp:"DApp Flow"},Vc={up:H("UP"),down:J("DOWN"),degraded:k("\x1B[33mDEGRADED\x1B[0m"),unknown:l("—")}});import{existsSync as Bo,readFileSync as dg,readdirSync as lg}from"node:fs";import{join as sr,basename as ug}from"node:path";function qe(e,t){let r=sr(e,"compiler",Yn);if(Bo(r))return ed(r,e,[]);for(let n of Qc){let s=n?sr(e,n,"managed"):sr(e,"managed");if(!Bo(s))continue;let o;try{o=lg(s).sort()}catch{continue}let i=o.filter((u)=>Bo(sr(s,u,"compiler",Yn)));if(i.length===0)continue;let a;if(t){if(!i.includes(t))throw Error(`Contract "${t}" not found in ${s}
|
|
551
|
+
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((u)=>u!==a),d=sr(s,a,"compiler",Yn);return ed(d,sr(s,a),c)}throw Error(`No compiled contract found in ${e}
|
|
552
|
+
Expected: managed/<name>/compiler/${Yn}
|
|
553
|
+
Searched: ${Qc.map((n)=>n?`${n}/managed/`:"managed/").join(", ")}
|
|
554
|
+
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function ed(e,t,r){let n;try{n=JSON.parse(dg(e,"utf-8"))}catch(o){throw Error(`Failed to parse ${e}: ${o.message}`)}return{info:pg(n,e,t,r),infoPath:e}}function pg(e,t,r,n){if(typeof e!=="object"||e===null||Array.isArray(e))throw Error(`${t}: must be a JSON object`);let s=e,o=typeof s["compiler-version"]==="string"?s["compiler-version"]:"unknown",i=typeof s["language-version"]==="string"?s["language-version"]:"unknown",a=typeof s["runtime-version"]==="string"?s["runtime-version"]:"unknown",c=Array.isArray(s.circuits)?s.circuits:[],d=Array.isArray(s.witnesses)?s.witnesses:[];return{name:ug(r),managedDir:r,compilerVersion:o,languageVersion:i,runtimeVersion:a,circuits:c,witnesses:d,siblings:n}}function Pe(e){switch(e["type-name"]){case"Uint":return"bigint";case"Bytes":return"Uint8Array";case"Opaque":return e.tsType??"unknown";case"Tuple":if(!e.types||e.types.length===0)return"void";return`[${e.types.map(Pe).join(", ")}]`;case"Boolean":return"boolean";case"String":return"string";case"Vector":return e.types?.[0]?`${Pe(e.types[0])}[]`:"unknown[]";case"Map":if(e.types&&e.types.length>=2)return`Map<${Pe(e.types[0])}, ${Pe(e.types[1])}>`;return"Map<unknown, unknown>";case"Set":return e.types?.[0]?`Set<${Pe(e.types[0])}>`:"Set<unknown>";case"Option":return e.types?.[0]?`${Pe(e.types[0])} | null`:"unknown | null";default:return e["type-name"]??"unknown"}}function td(e){let t=e.arguments.map((r)=>`${r.name}: ${Pe(r.type)}`).join(", ");return`${e.name}(${t})`}function rd(e){if(e.pure)return"pure";let t=["impure"];if(e.proof)t.push("proof");return t.join(", ")}function nd(e){let t=e.arguments.map((s)=>`${s.name}: ${Pe(s.type)}`).join(", "),r=Pe(e["result type"]),n=r!=="void"?` → ${r}`:"";return`${e.name}(${t})${n}`}function sd(e){return{name:e.name,compilerVersion:e.compilerVersion,languageVersion:e.languageVersion,runtimeVersion:e.runtimeVersion,managedDir:e.managedDir,siblings:e.siblings,circuits:e.circuits.map((t)=>({name:t.name,pure:t.pure,proof:t.proof,arguments:t.arguments.map((r)=>({name:r.name,type:Pe(r.type)})),returnType:Pe(t["result-type"])})),witnesses:e.witnesses.map((t)=>({name:t.name,arguments:t.arguments.map((r)=>({name:r.name,type:Pe(r.type)})),returnType:Pe(t["result type"])}))}}var Yn="contract-info.json",Qc;var Jr=E(()=>{Qc=["","contract/src","contract","contracts/src","contracts","src"]});import*as od from"node:readline";function gg(e){return mg.has(e)}function hg(e){return fg.has(e)}function wg(e){let t=[],r=e.dappName?`Request from "${e.dappName}"`:"DApp Request";if(t.push(k(r)),t.push(""),t.push(` ${l("Action:")} ${L(e.method)}`),t.push(` ${l("Network:")} ${e.network}`),e.details.length>0){t.push("");for(let n of e.details)t.push(` ${l(n.label+":")} ${n.value}`)}return t.push(""),t.push(` ${H("[A]pprove")} ${J("[R]eject")}`),Yi(t,"heavy")}async function id(e,t={}){if(t.approveAll)return process.stderr.write(l(` Auto-approved: ${e.method}`)+`
|
|
555
|
+
`),"approve";if(t.autoApproveReads&&gg(e.method))return process.stderr.write(l(` Auto-approved (read-only): ${e.method}`)+`
|
|
556
|
+
`),"approve";if(!process.stdin.isTTY){process.stderr.write(J(" Cannot prompt for approval: stdin is not a TTY")+`
|
|
557
|
+
`);let n=hg(e.method)?"Balancing prompts like any other write":`${e.method} needs a terminal to approve`;return process.stderr.write(l(` ${n}: use --approve-all for non-interactive environments`)+`
|
|
558
|
+
`),"reject"}if(Vr)return process.stderr.write(J(" Rejected: another approval prompt is active")+`
|
|
560
559
|
`),"reject";process.stderr.write(`
|
|
561
|
-
`+
|
|
562
|
-
|
|
563
|
-
`),
|
|
564
|
-
`),"reject"}return new Promise((n)=>{let s=(o)=>{
|
|
565
|
-
`)}),c.on("connection",(u)=>{let p=`conn_${++
|
|
566
|
-
`)},
|
|
567
|
-
`)}function S(){return new Date(Date.now()+
|
|
568
|
-
`),!await
|
|
569
|
-
`)}};function
|
|
570
|
-
`)}var
|
|
571
|
-
${r}`)}}async function
|
|
572
|
-
${n}`)}}async function
|
|
573
|
-
${r}`)}}function
|
|
560
|
+
`+wg(e)+`
|
|
561
|
+
|
|
562
|
+
`),Vr=!0;let r;try{r=od.createInterface({input:process.stdin,output:process.stderr})}catch{return Vr=!1,process.stderr.write(J(" Cannot create readline interface")+`
|
|
563
|
+
`),"reject"}return new Promise((n)=>{let s=(o)=>{Vr=!1,r.close(),n(o)};r.on("close",()=>{if(Vr)s("reject")}),r.question(M(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var mg,fg,Vr=!1;var ad=E(()=>{ue();mg=new Set(["getShieldedBalances","getUnshieldedBalances","getDustBalance","getShieldedAddresses","getUnshieldedAddress","getDustAddress","getTxHistory","getConfiguration","getConnectionStatus"]),fg=new Set(["balanceUnsealedTransaction","balanceSealedTransaction"])});import{WebSocketServer as yg}from"ws";function bg(e){if(Ho(e))return Sg[e.code]??-32603;return-32603}function Ho(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="DAppConnectorAPIError"}function vg(e){if(!(e instanceof Error)&&!(typeof e==="object"&&e!==null&&("_tag"in e)))return;let t=[],r=e.cause,n=new Set;while(r&&!n.has(r)){n.add(r);let s=r;if(r instanceof Error||typeof r==="object"&&s._tag){let o=s._tag,i=s.message??"";t.push(o?`[${o}] ${i}`:i),r=s.cause}else if(typeof r==="string"){t.push(r);break}else{try{t.push(JSON.stringify(r))}catch{t.push(String(r))}break}}if(t.length===0)return;return{causes:t}}function Zn(e,t){if(typeof t==="bigint")return t.toString();return t}function kg(e,t){return t}function Cg(e){let t;try{t=JSON.parse(e,kg)}catch{throw Object.assign(Error("Parse error"),{rpcCode:-32700})}if(typeof t!=="object"||t===null||t.jsonrpc!=="2.0"||typeof t.method!=="string")throw Object.assign(Error("Invalid Request"),{rpcCode:-32600});let r=t;if(r.id===void 0||r.id===null)throw Object.assign(Error("Missing request id"),{rpcCode:-32600});return r}function Qn(e){let{port:t,handlers:r,onConnect:n,onDisconnect:s,onRequest:o,onResponse:i}=e,a=new Map,c=new yg({port:t,host:"127.0.0.1"});c.on("error",(u)=>{process.stderr.write(`WebSocket server error: ${u.message}
|
|
564
|
+
`)}),c.on("connection",(u)=>{let p=`conn_${++Ag}`,f={ws:u,id:p,connectedAt:new Date,authenticated:!1,requestCount:0,notify(m,w){if(u.readyState!==u.OPEN)return;let y={jsonrpc:"2.0",method:m,...w&&{params:w}};u.send(JSON.stringify(y,Zn))}};a.set(p,f),n?.(f);let g=!1,h=()=>{if(g)return;g=!0,a.delete(p),s?.(f)};u.on("message",async(m)=>{let w=null,y,S,b=Date.now();try{y=Cg(m.toString("utf-8")),w=y.id,f.requestCount++,o?.(f,y);let v=r[y.method];if(!v){let U={jsonrpc:"2.0",id:y.id,error:{code:-32601,message:`Method not found: ${y.method}`}};u.send(JSON.stringify(U,Zn));return}S={notify:f.notify.bind(f),connectionId:p,requestId:y.id,metadata:{}};let R=await v(y.params??{},S),P=Date.now()-b;if(y.method==="connect"&&R&&typeof R==="object")f.authenticated=!0,f.networkId=R.networkId;let q={jsonrpc:"2.0",id:y.id,result:R};u.send(JSON.stringify(q,Zn)),i?.(f,y,P,R,void 0,S.metadata)}catch(v){let R=Date.now()-b,P=v?.rpcCode??bg(v),q=v instanceof Error?v.message:"Internal error",U=Ho(v)?{type:v.type,code:v.code}:vg(v),X={jsonrpc:"2.0",id:w,error:{code:P,message:q,data:U}};if(u.send(JSON.stringify(X,Zn)),y){let O={message:q,code:Ho(v)?v.code:void 0};i?.(f,y,R,void 0,O,S?.metadata)}}}),u.on("close",h),u.on("error",()=>{h();try{u.close()}catch{}})});async function d(){for(let u of a.values())u.ws.close(1001,"Server shutting down");return a.clear(),new Promise((u,p)=>{c.close((f)=>{if(f)p(f);else u()})})}return{wss:c,connections:a,close:d}}function Oe(e,t){let r=Error(t);return r.type="DAppConnectorAPIError",r.code=e,r.reason=t,r}var Sg,Ag=0;var es=E(()=>{Sg={Rejected:-32000,PermissionRejected:-32001,Disconnected:-32002,InvalidRequest:-32602,InternalError:-32603}});function cd(e){let t=[],r,n;function s(){if(r!==void 0&&n!==void 0){let a=Date.now()-n;t.push({phase:r,durationMs:a}),e?.onComplete?.(r,a),r=void 0,n=void 0}}function o(a){s(),r=a,n=Date.now(),e?.onStart?.(a)}function i(){return[...t]}return{start:o,complete:s,getTimings:i}}import{Transaction as dd}from"@midnight-ntwrk/ledger-v8";function Tg(e){return Buffer.from(e).toString("hex")}function ts(e){if(!/^[0-9a-fA-F]*$/.test(e))throw Error("Invalid hex string: contains non-hex characters");if(e.length%2!==0)throw Error("Invalid hex string: odd length");return new Uint8Array(Buffer.from(e,"hex"))}function pd(e){return Tg(e.serialize())}function md(e){return dd.deserialize(ld,ud,Eg,ts(e))}function Go(e){return dd.deserialize(ld,ud,xg,ts(e))}var ld="signature",ud="proof",xg="binding",Eg="pre-binding";var fd=()=>{};function gd(e){let t=Buffer.from(`midnight_signed_message:${e.length}:`,"utf-8");return new Uint8Array(Buffer.concat([t,e]))}import{Transaction as Ng}from"@midnight-ntwrk/ledger-v8";function rs(e,t){let r=[];r.push({label:"Tx size",value:_g(e.length/2)});let n=Rg(e,t);if(n){let s=$g(n);if(s.action)r.push({label:"Type",value:s.action});if(s.circuits.length>0)r.push({label:"Circuits",value:s.circuits.join(", ")});if(s.ttl)r.push({label:"TTL",value:s.ttl})}return r}function Rg(e,t){let r=Ig(e),n=t==="sealed"?[["signature","proof","binding"],["signature","proof","pre-binding"]]:[["signature","proof","pre-binding"],["signature","pre-proof","pre-binding"]];for(let[s,o,i]of n)try{return Ng.deserialize(s,o,i,r).toString(!0)}catch{}return null}function $g(e){let t={networkId:null,action:null,circuits:[],ttl:null},r=e.match(/network_id:\s*"([^"]+)"/);if(r)t.networkId=r[1];if(e.includes("Deploy ContractState"))t.action="Deploy contract";else if(e.match(/Call\s/))t.action="Call contract";let n=/(\w+):\s*<verifier key>/g,s;while((s=n.exec(e))!==null)t.circuits.push(s[1]);if(t.circuits.length===0){let i=e.match(/Call\s+\S+\s+(\w+)/);if(i)t.circuits.push(i[1])}let o=e.match(/ttl:\s*Timestamp\((\d+)\)/);if(o){let i=parseInt(o[1],10),a=new Date(i*1000);t.ttl=a.toISOString().replace("T"," ").slice(0,19)}return t}function Ig(e){return new Uint8Array(Buffer.from(e,"hex"))}function _g(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;return`${(t/1024).toFixed(1)} MB`}var hd=()=>{};import{DustLocalState as Dg}from"@midnight-ntwrk/ledger-v8";import{CoreWallet as Xe}from"@midnight-ntwrk/wallet-sdk-dust-wallet/v1";var Ot,Pg,Og,JA;var wd=E(()=>{Ot=new Map,Pg=Xe.applyEventsWithChanges;Xe.applyEventsWithChanges=function(t,r,n,s){let o=Pg.call(Xe,t,r,n,s),i=Array.isArray(o)?o[0]:o;if(Ot.size>0&&i?.pendingDust){let a=new Set(i.pendingDust.map((c)=>c.nullifier));for(let c of Ot.keys())if(!a.has(c))Ot.delete(c)}return o};Og=Xe.spendCoins;Xe.spendCoins=function(t,r,n,s){let o=null;try{o=t.state.serialize()}catch{}let i=Og.call(Xe,t,r,n,s),a=i[1]??i;if(o&&a?.pendingDust){for(let c of a.pendingDust)if(!Ot.has(c.nullifier))Ot.set(c.nullifier,o)}return i};JA=Xe.revertTransaction;Xe.revertTransaction=function(t,r){let n=Xe.pendingDustToMap(t.pendingDust),s=[],o=r.intents;if(o)for(let a of o.values()){let c=a.dustActions?.spends;if(!c)continue;for(let d of c)if(n.has(d.oldNullifier))s.push(d.oldNullifier)}let i=t.state;for(let a of s){let c=Ot.get(a);if(c){try{i=Dg.deserialize(c)}catch{}Ot.delete(a)}}return{...t,state:i,pendingDust:t.pendingDust.filter((a)=>!s.includes(a.nullifier))}};Xe.applyFailed=Xe.revertTransaction});import*as Mt from"rxjs";import{MidnightBech32m as Ko,UnshieldedAddress as Mg,ShieldedAddress as Fg}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as Jo}from"@midnight-ntwrk/wallet-sdk-abstractions";function Ug(e){let t=[],r=e,n=new Set;while(r&&!n.has(r)){n.add(r);let o=r;if(r instanceof Error||typeof r==="object"&&o._tag){let i=o._tag,a=o.message??"";if(i&&a)t.push(`[${i}] ${a}`);else if(a)t.push(a);else if(i)t.push(`[${i}]`);if(o.data&&typeof o.data==="object")try{t.push(`data=${JSON.stringify(o.data)}`)}catch{}r=o.cause}else if(typeof r==="string"){t.push(r);break}else{try{let i=JSON.stringify(r);if(i&&i!=="{}")t.push(i);else t.push(String(r))}catch{t.push(String(r))}break}}let s=[];for(let o of t)if(s.length===0||s[s.length-1]!==o)s.push(o);return s.join(" → ")||"Unknown error"}function ns(e){let{bundle:t,networkConfig:r,approvalOptions:n,callbacks:s}=e,{facade:o,keystore:i,zswapSecretKeys:a,dustSecretKey:c}=t,d=Lg[r.networkId];if(d===void 0)throw Error(`Unknown networkId: ${r.networkId}`);let u,p=o.state().pipe(Mt.filter((I)=>I.isSynced)).subscribe((I)=>{u=I});function f(){if(!u)throw Oe("Disconnected","Wallet not synced yet");return u}let g={shieldedSecretKeys:a,dustSecretKey:c},h=new Map;function m(I,x,T){let _=h.get(I);if(!_)_=new Map,h.set(I,_);let K=setTimeout(async()=>{if(_.delete(x),_.size===0)h.delete(I);try{await o.revert(T)}catch{}process.stderr.write(l(` abandoned tx reverted (${I})`)+`
|
|
565
|
+
`)},zi);_.set(x,{recipe:T,timer:K})}function w(I,x){let T=h.get(I);if(!T)return;let _=T.get(x);if(_)clearTimeout(_.timer),T.delete(x);if(T.size===0)h.delete(I)}async function y(I){let x=h.get(I);if(!x||x.size===0)return;h.delete(I);for(let[,T]of x){clearTimeout(T.timer);try{await o.revert(T.recipe)}catch{}}process.stderr.write(l(` reverted ${x.size} pending tx(s) on disconnect`)+`
|
|
566
|
+
`)}function S(){return new Date(Date.now()+hr*60*1000)}async function b(I,x){x?.start("signing");let T=await o.signRecipe(I,(j)=>i.signData(j));x?.start("proving");let _,K=await Promise.race([o.finalizeRecipe(T),new Promise((j,ee)=>{_=setTimeout(()=>ee(Error("ZK proof generation timed out")),tn)})]);return clearTimeout(_),x?.complete(),{hex:pd(K),finalized:K}}async function v(I,x=[],T){T?.notify("approval:pending",{method:I});let _=await id({method:I,network:r.networkId,details:x,dappName:T?.connectionId},n),K=_==="reject"?"rejected":"approved";if(T?.notify("approval:resolved",{method:I,result:K}),_==="reject")throw Oe("Rejected","User rejected the request")}function R(I){return Ko.encode(d,I).asString()}function P(I){let x={};for(let T of I){let _=T.kind;if(_!=="shielded"&&_!=="unshielded")throw Oe("InvalidRequest",`Invalid output kind: "${_}" — must be "shielded" or "unshielded"`);if(!x[_])x[_]=[];let K=BigInt(T.value),j;if(_==="unshielded")j=Ko.parse(T.recipient).decode(Mg,d);else j=Ko.parse(T.recipient).decode(Fg,d);x[_].push({type:T.type,receiverAddress:j,amount:K})}return Object.entries(x).map(([T,_])=>({type:T,outputs:_}))}function q(I,x){return cd({onStart:(T)=>{let _=x?.connectionId??"unknown";s?.onPhaseStart?.(_,I,T),x?.notify("progress",{method:I,phase:T,status:"started"})},onComplete:(T,_)=>{let K=x?.connectionId??"unknown";s?.onPhaseComplete?.(K,I,T,_),x?.notify("progress",{method:I,phase:T,status:"completed",durationMs:_})}})}function U(){if(!u)return!1;try{let I=u.dust;return I?.availableCoins?.length>0||I?.balance(new Date)>0n}catch{return!1}}async function X(I){return new Promise((x)=>{if(U()){x(!0);return}let T=o.state().pipe(Mt.filter(()=>U()),Mt.take(1),Mt.timeout(I)).subscribe({next:()=>{T.unsubscribe(),x(!0)},error:()=>{T.unsubscribe(),x(!1)}})})}async function O(I){for(let x=1;x<=yr;x++)try{return await I()}catch(T){let _=String(T?.message??T??"");if(!(/no dust tokens/i.test(_)||/dust.*unavailable/i.test(_))||x===yr)throw T;if(process.stderr.write(l(` dust unavailable, waiting for recovery (${x}/${yr})... [${_.slice(0,60)}]`)+`
|
|
567
|
+
`),!await X(Ds)&&x<yr)await new Promise((ee)=>setTimeout(ee,Ds))}throw Error("unreachable")}let F={connect:async(I)=>{let x=String(I.networkId??"");if(x.toLowerCase()!==r.networkId.toLowerCase())throw Oe("InvalidRequest",`Network mismatch: wallet is on ${r.networkId}, requested ${x}`);return{networkId:r.networkId}},getUnshieldedBalances:async()=>f().unshielded.balances,getShieldedBalances:async()=>f().shielded.balances,getDustBalance:async()=>{let x=f().dust.balance(new Date);return{cap:x,balance:x}},getUnshieldedAddress:async()=>{let I=f();return{unshieldedAddress:R(I.unshielded.address)}},getShieldedAddresses:async()=>{let x=f().shielded.address;return{shieldedAddress:R(x),shieldedCoinPublicKey:x.coinPublicKeyString(),shieldedEncryptionPublicKey:x.encryptionPublicKeyString()}},getDustAddress:async()=>{let I=f();return{dustAddress:R(I.dust.address)}},getTxHistory:async(I)=>{let x=f(),T=Number(I.pageNumber??0),_=Number(I.pageSize??20);try{let K=x.unshielded.transactionHistory,j=[],ee=0,ye=T*_;for await(let oe of K.getAll()){if(ee>=ye+_)break;if(ee>=ye)j.push({txHash:oe.hash,txStatus:oe.status==="SUCCESS"?{status:"finalized"}:{status:"pending"}});ee++}return j}catch{return[]}},getConfiguration:async()=>({indexerUri:r.indexer,indexerWsUri:r.indexerWS,proverServerUri:r.proofServer,substrateNodeUri:r.node,networkId:r.networkId}),getConnectionStatus:async()=>({status:"connected",networkId:d}),makeTransfer:async(I,x)=>{let T=I.desiredOutputs;if(!Array.isArray(T)||T.length===0)throw Oe("InvalidRequest","desiredOutputs must be a non-empty array");let _=q("makeTransfer",x),K=T.map((Me,Fe)=>({label:`Output ${Fe+1}`,value:`${Me.value} → ${String(Me.recipient).slice(0,20)}... (${Me.kind})`}));_.start("approve"),await v("makeTransfer",K,x),_.start("building");let j=P(T),ee=I.options?.payFees??!0,ye=await O(()=>o.transferTransaction(j,g,{ttl:S(),payFees:ee})),{hex:oe,finalized:le}=await b(ye,_);return m(x.connectionId,oe,ye),x.metadata.phases=_.getTimings(),{tx:oe}},submitTransaction:async(I,x)=>{let T=String(I.tx??"");if(!T)throw Oe("InvalidRequest","tx is required");let _=q("submitTransaction",x);_.start("approve");try{await v("submitTransaction",rs(T,"sealed"),x)}catch(j){let ye=h.get(x.connectionId)?.get(T);if(ye)try{await o.revert(ye.recipe)}catch{}throw w(x.connectionId,T),j}let K=Go(T);_.start("submitting");try{let j=await o.submitTransaction(K);return _.complete(),w(x.connectionId,T),x.metadata.phases=_.getTimings(),{txHash:j}}catch(j){_.complete();let ye=h.get(x.connectionId)?.get(T);if(ye)try{await o.revert(ye.recipe)}catch{}w(x.connectionId,T);let oe=Ug(j),le=Error(`Transaction submission failed: ${oe}`);throw le.cause=j,le}},balanceUnsealedTransaction:async(I,x)=>{let T=String(I.tx??"");if(!T)throw Oe("InvalidRequest","tx is required");let _=q("balanceUnsealedTransaction",x);_.start("approve"),await v("balanceUnsealedTransaction",rs(T,"unsealed"),x),_.start("building");let K=md(T),j=await O(()=>o.balanceUnboundTransaction(K,g,{ttl:S()})),{hex:ee,finalized:ye}=await b(j,_);return m(x.connectionId,ee,j),x.metadata.phases=_.getTimings(),{tx:ee}},balanceSealedTransaction:async(I,x)=>{let T=String(I.tx??"");if(!T)throw Oe("InvalidRequest","tx is required");let _=q("balanceSealedTransaction",x);_.start("approve"),await v("balanceSealedTransaction",rs(T,"sealed"),x),_.start("building");let K=Go(T),j=await O(()=>o.balanceFinalizedTransaction(K,g,{ttl:S()})),{hex:ee,finalized:ye}=await b(j,_);return m(x.connectionId,ee,j),x.metadata.phases=_.getTimings(),{tx:ee}},makeIntent:async(I,x)=>{let{desiredInputs:T,desiredOutputs:_,options:K}=I;if(!K)throw Oe("InvalidRequest","options is required for makeIntent");let j=q("makeIntent",x);j.start("approve"),await v("makeIntent",[],x),j.start("building");let ee={};if(Array.isArray(T))for(let Fe of T){let Ne=Fe.kind;if(!ee[Ne])ee[Ne]={};ee[Ne][Fe.type]=BigInt(Fe.value)}let ye=P(_??[]),oe=await O(()=>o.initSwap(ee,ye,g,{ttl:S(),payFees:K.payFees??!0})),{hex:le,finalized:Me}=await b(oe,j);return m(x.connectionId,le,oe),x.metadata.phases=j.getTimings(),{tx:le}},signData:async(I,x)=>{let T=String(I.data??""),_=I.options;if(!T||!_?.encoding)throw Oe("InvalidRequest","data and options.encoding are required");if(_.keyType&&_.keyType!=="unshielded")throw Oe("InvalidRequest",`Unsupported keyType: "${_.keyType}" — only "unshielded" is supported`);await v("signData",[{label:"Encoding",value:_.encoding},{label:"Data",value:T.length>64?T.slice(0,64)+"...":T}],x);let K;switch(_.encoding){case"hex":K=ts(T);break;case"base64":K=new Uint8Array(Buffer.from(T,"base64"));break;case"text":K=new Uint8Array(Buffer.from(T,"utf-8"));break;default:throw Oe("InvalidRequest",`Unknown encoding: ${_.encoding}`)}let j=i.signData(gd(K)),ee=i.getPublicKey();return{data:T,signature:String(j),verifyingKey:String(ee)}},getProvingProvider:async()=>({provingProvider:"ready",proverServerUri:r.proofServer}),hintUsage:async(I)=>{let x=I.methodNames??[];process.stderr.write(l(` DApp hints usage: ${x.join(", ")}`)+`
|
|
568
|
+
`)}};function Q(){p.unsubscribe();for(let[,I]of h)for(let[,x]of I)clearTimeout(x.timer);h.clear()}function de(){for(let[,I]of h)if(I.size>0)return!0;return!1}return{handlers:F,revertPendingTxs:y,hasPendingTxs:de,dispose:Q}}var Lg;var Vo=E(()=>{ad();es();fd();hd();wd();Lg={PreProd:Jo.NetworkId.PreProd,Preview:Jo.NetworkId.Preview,Undeployed:Jo.NetworkId.Undeployed}});import{Socket as jg}from"node:net";function Wg(e){return new Promise((t)=>{let r=new jg;r.setTimeout(1000),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("timeout",()=>{r.destroy(),t(!1)}),r.once("error",()=>t(!1)),r.connect(e,"127.0.0.1")})}async function Bg(e){let t=(await import("ws")).default;return new Promise((r)=>{let n=new t(`ws://127.0.0.1:${e}`),s=setTimeout(()=>{try{n.close()}catch{}r(null)},2000);n.on("open",()=>{n.send(JSON.stringify({jsonrpc:"2.0",id:1,method:"getConnectionStatus",params:{}}))}),n.on("message",(o)=>{clearTimeout(s);try{let a=JSON.parse(o.toString())?.result?.networkId;n.close(),r(typeof a==="string"?a:null)}catch{n.close(),r(null)}}),n.on("error",()=>{clearTimeout(s),r(null)})})}async function ss(e){let t=e.port??xt,r=(e.network??"undeployed").toLowerCase(),n=e.onMessage??(()=>{});if(await Wg(t)){let s=await Bg(t);if(!s)throw Error(`Port ${t} is in use by a process that does not look like mn serve. Free the port (e.g. \`lsof -nP -iTCP:${t} -sTCP:LISTEN\` then \`kill <pid>\`) and retry.`);let o=s.toLowerCase();if(o!==r)throw Error(`mn serve is already running on port ${t} for network ${o}, but this run needs ${r}. Stop the wrong-network serve first (\`pkill -f 'mn serve'\`) and retry.`);return n(`Reusing existing mn serve on port ${t}`),{port:t,async stop(){}}}return Hg(e)}async function Hg(e){let t=e.port??xt,r=e.onMessage??(()=>{}),n=ce(ie(e.wallet)),s=Buffer.from(n.seed,"hex"),{name:o,config:i}=te({args:{command:"serve",subcommand:void 0,positionals:[],flags:e.network?{network:e.network}:{}}}),a=n.addresses[o],c=he((h,m)=>{r(`SDK: ${m}`)}),d=Ce();r("Building wallet facade...");let u=wt(a,o),p=await Qe(s,i,u);r("Syncing wallet..."),await ht(p,{onProgress:(h,m)=>{if(m>0){let w=Math.min(Math.round(h/m*100),100);r(`Syncing wallet... ${w}%`)}}}),r("Wallet synced"),r("Waiting for dust..."),await Vt(p),r("Dust ready");try{await je(a,o,p.facade)}catch{}let f=ns({bundle:p,networkConfig:i,approvalOptions:{approveAll:!0,autoApproveReads:!0},callbacks:{onPhaseStart:(h,m,w)=>{r(`${w}...`)},onPhaseComplete:(h,m,w,y)=>{r(`${w} ${Math.round(y)}ms`)}}}),g=Qn({port:t,handlers:f.handlers,onConnect:(h)=>{r(`connected ${h.id}`)},onDisconnect:(h)=>{r(`disconnected ${h.id}`),f.revertPendingTxs(h.id).catch(()=>{})},onRequest:(h,m)=>{r(`${h.id} → ${m.method}`)},onResponse:(h,m,w,y,S)=>{if(S)r(`${h.id} ← ${m.method} FAILED: ${S.message}`);else r(`${h.id} ← ${m.method} (${Math.round(w)}ms)`)}});return r(`Server ready on ws://localhost:${t}`),{port:t,async stop(){g.close(),f.dispose(),d(),c();try{await Ue(p)}catch{}}}}var zo=E(()=>{ke();pe();Ke();yt();bt();Vo();es()});import{existsSync as yd}from"node:fs";import{join as Sd}from"node:path";function is(e){for(let t of os){let r=Sd(e,t);if(yd(r))return r}return null}function Kg(e){for(let t of Gg){let r=Sd(e,t);if(yd(r))return r}return null}function as(e){let{projectRoot:t,witnessNames:r}=e,n=Kg(t),s=[`Contract declares ${r.length} witness(es): ${r.join(", ")}`,"but no compiled witnesses module was found.","",`Searched (relative to ${t}):`,...os.map((o)=>` - ${o}`),""];if(n)s.push(`Found ${n} — looks like it isn't compiled yet.`,'Build it (e.g. "npm run build") so a .js exists, then retry.');else s.push('Add a witnesses module exporting a "witnesses" object that maps each',"declared name to its implementation. Example: src/witnesses.ts → tsc → dist/witnesses.js.");return s.join(`
|
|
569
|
+
`)}var os,Gg;var cs=E(()=>{os=["dist/witnesses.js","src/witnesses.js","contract/dist/witnesses.js","contract/src/witnesses.js"],Gg=["src/witnesses.ts","contract/src/witnesses.ts"]});function ds(e){if(typeof e==="number")return Number.isInteger(e)?BigInt(e):e;if(typeof e==="string"){if(/^-?\d+n$/.test(e))return BigInt(e.slice(0,-1));return e}if(Array.isArray(e)){if(e.length>0&&e.every((t)=>typeof t==="number"&&Number.isInteger(t)&&t>=0&&t<=255))return Uint8Array.from(e);return e.map(ds)}if(e&&typeof e==="object"&&Object.getPrototypeOf(e)===Object.prototype){let t={};for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))t[r]=ds(e[r]);return t}return e}function bd(e,t){let r=new Uint8Array(32);if(e&&e.length===64){for(let s=0;s<32;s++)r[s]=parseInt(e.substr(s*2,2),16);return r}let n=t??"";if(n.length>=64){for(let s=0;s<32;s++)r[s]=parseInt(n.substr(s*2,2),16);return r}return globalThis.crypto.getRandomValues(r),r}import{spawn as Jg}from"node:child_process";import{writeFileSync as Vg,unlinkSync as vd,existsSync as ls,symlinkSync as kd}from"node:fs";import{join as zr,dirname as Cd}from"node:path";import{fileURLToPath as zg}from"node:url";function qg(){let e=Cd(zg(import.meta.url));for(let t=0;t<8;t++){let r=zr(e,"node_modules");if(ls(r))return r;let n=Cd(e);if(n===e)break;e=n}return null}async function or(e){let t=Qg(e),r=await Xo(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`State script returned unexpected output:
|
|
570
|
+
${r}`)}}async function us(e){let t=Yg(e),r=e.privateStateSecretKey?{MN_PRIVATE_STATE_SECRET:e.privateStateSecretKey}:void 0,n=await Xo(e.dappDir,t,e.onMessage,r);try{return JSON.parse(n)}catch{throw Error(`Deploy script returned unexpected output:
|
|
571
|
+
${n}`)}}async function ps(e){let t=Zg(e),r=await Xo(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`Call script returned unexpected output:
|
|
572
|
+
${r}`)}}function Ad(e){return`
|
|
574
573
|
import WebSocket from 'ws';
|
|
575
574
|
|
|
576
575
|
const RPC_URL = 'ws://127.0.0.1:${e}';
|
|
@@ -611,7 +610,7 @@ function rpcCall(method, params = {}) {
|
|
|
611
610
|
function rpcClose() {
|
|
612
611
|
if (rpcWs) rpcWs.close();
|
|
613
612
|
}
|
|
614
|
-
`}function
|
|
613
|
+
`}function xd(){return`
|
|
615
614
|
// Wallet provider backed by mn serve RPC
|
|
616
615
|
const walletProvider = {
|
|
617
616
|
getCoinPublicKey: () => {
|
|
@@ -641,7 +640,7 @@ const walletProvider = {
|
|
|
641
640
|
|
|
642
641
|
// Get wallet state for coin/encryption public keys
|
|
643
642
|
const walletState = await rpcCall('getShieldedAddresses', {});
|
|
644
|
-
`}function
|
|
643
|
+
`}function Ed(e,t){return`
|
|
645
644
|
import { pathToFileURL } from 'node:url';
|
|
646
645
|
import { resolve } from 'node:path';
|
|
647
646
|
import { CompiledContract } from '@midnight-ntwrk/compact-js';
|
|
@@ -655,7 +654,7 @@ const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract',
|
|
|
655
654
|
// Both relative-to-cwd locations and contract/<...> locations are checked
|
|
656
655
|
// so mn dev (which chdirs into the contract sub-package) and mn contract
|
|
657
656
|
// deploy run from a workspace root both work.
|
|
658
|
-
const WITNESS_CANDIDATES = ${JSON.stringify(
|
|
657
|
+
const WITNESS_CANDIDATES = ${JSON.stringify(os)};
|
|
659
658
|
let witnesses;
|
|
660
659
|
let createPrivateState;
|
|
661
660
|
for (const p of WITNESS_CANDIDATES) {
|
|
@@ -686,7 +685,7 @@ if (!witnesses) {
|
|
|
686
685
|
// Uses a deterministic seed derived from the wallet so post/takeDown use the same key.
|
|
687
686
|
// The private state provider (leveldb) persists between calls, but initialPrivateState
|
|
688
687
|
// is the fallback when no stored state exists yet.
|
|
689
|
-
${
|
|
688
|
+
${Xg}
|
|
690
689
|
function makeInitialPrivateState() {
|
|
691
690
|
if (createPrivateState) {
|
|
692
691
|
// Secret precedence (see resolvePrivateStateSecretKey, injected above via
|
|
@@ -712,7 +711,7 @@ const compiled = witnesses
|
|
|
712
711
|
CompiledContract.withVacantWitnesses,
|
|
713
712
|
(c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR),
|
|
714
713
|
);
|
|
715
|
-
`}function
|
|
714
|
+
`}function Td(e,t,r){return`
|
|
716
715
|
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
717
716
|
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
718
717
|
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
@@ -735,23 +734,23 @@ const providers = {
|
|
|
735
734
|
walletProvider,
|
|
736
735
|
midnightProvider: walletProvider,
|
|
737
736
|
};
|
|
738
|
-
`}function
|
|
737
|
+
`}function Yg(e){let t=e.privateStateKey??`${e.contractName}PrivateState`,r=JSON.stringify(e.args??[]);return`
|
|
739
738
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
740
739
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
741
740
|
|
|
742
|
-
${
|
|
743
|
-
${
|
|
741
|
+
${Ad(e.servePort)}
|
|
742
|
+
${Ed(e.contractName,e.managedDir)}
|
|
744
743
|
|
|
745
744
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
746
745
|
await rpcConnect();
|
|
747
746
|
process.stderr.write('Connected\\n');
|
|
748
747
|
|
|
749
|
-
${
|
|
750
|
-
${
|
|
748
|
+
${xd()}
|
|
749
|
+
${Td(e.managedDir,e.networkConfig,t)}
|
|
751
750
|
|
|
752
751
|
import { deployContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
753
752
|
|
|
754
|
-
${
|
|
753
|
+
${Nd}
|
|
755
754
|
const constructorArgs = (${r}).map(coerceArg);
|
|
756
755
|
process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n');
|
|
757
756
|
const deployed = await deployContract(providers, {
|
|
@@ -767,19 +766,19 @@ process.stderr.write('Deploy complete: ' + address + '\\n');
|
|
|
767
766
|
console.log(JSON.stringify({ contractAddress: address }));
|
|
768
767
|
rpcClose();
|
|
769
768
|
process.exit(0);
|
|
770
|
-
`}function
|
|
769
|
+
`}function Zg(e){let t=e.privateStateKey??`${e.contractName}PrivateState`;return`
|
|
771
770
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
772
771
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
773
772
|
|
|
774
|
-
${
|
|
775
|
-
${
|
|
773
|
+
${Ad(e.servePort)}
|
|
774
|
+
${Ed(e.contractName,e.managedDir)}
|
|
776
775
|
|
|
777
776
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
778
777
|
await rpcConnect();
|
|
779
778
|
process.stderr.write('Connected\\n');
|
|
780
779
|
|
|
781
|
-
${
|
|
782
|
-
${
|
|
780
|
+
${xd()}
|
|
781
|
+
${Td(e.managedDir,e.networkConfig,t)}
|
|
783
782
|
|
|
784
783
|
import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
785
784
|
|
|
@@ -792,14 +791,14 @@ const deployed = await findDeployedContract(providers, {
|
|
|
792
791
|
});
|
|
793
792
|
|
|
794
793
|
process.stderr.write('Calling ${e.circuit}...\\n');
|
|
795
|
-
${
|
|
794
|
+
${Nd}
|
|
796
795
|
const args = (${JSON.stringify(e.args??[])}).map(coerceArg);
|
|
797
796
|
await deployed.callTx.${e.circuit}(...args);
|
|
798
797
|
|
|
799
798
|
console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(e.circuit)} }));
|
|
800
799
|
rpcClose();
|
|
801
800
|
process.exit(0);
|
|
802
|
-
`}function
|
|
801
|
+
`}function Qg(e){return`
|
|
803
802
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
804
803
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
805
804
|
|
|
@@ -862,20 +861,20 @@ for (const key of Object.keys(state)) {
|
|
|
862
861
|
|
|
863
862
|
console.log(JSON.stringify({ fields, maps }));
|
|
864
863
|
process.exit(0);
|
|
865
|
-
`}function
|
|
866
|
-
`,r?.(h)}),u.on("close",(g)=>{if(a(),g!==0){d(Error(f.trim()||`Script exited with code ${g}`));return}c(p.trim())}),u.on("error",(g)=>{a(),d(g)})})}var
|
|
867
|
-
const resolvePrivateStateSecretKey = (${
|
|
868
|
-
`;
|
|
869
|
-
const coerceArg = (${
|
|
870
|
-
`;
|
|
864
|
+
`}function th(e){if(!qo)return[];let t=[];if(!ls(e)){try{kd(qo,e),t.push(e)}catch{}return t}for(let r of eh){let n=zr(qo,r),s=zr(e,r);if(!ls(n)||ls(s))continue;try{kd(n,s),t.push(s)}catch{}}return t}async function Xo(e,t,r,n){let s=zr(e,"node_modules"),o=th(s),i=zr(e,`.mn-contract-${Date.now()}.mjs`);Vg(i,t);let a=()=>{try{vd(i)}catch{}for(let c of o.slice().reverse())try{vd(c)}catch{}};return new Promise((c,d)=>{let u=Jg("node",[i],{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1",...n}}),p="",f="";u.stdout?.on("data",(g)=>{p+=g.toString()}),u.stderr?.on("data",(g)=>{let h=g.toString().trim();if(h)f+=h+`
|
|
865
|
+
`,r?.(h)}),u.on("close",(g)=>{if(a(),g!==0){d(Error(f.trim()||`Script exited with code ${g}`));return}c(p.trim())}),u.on("error",(g)=>{a(),d(g)})})}var qo,Xg,Nd,eh;var qr=E(()=>{cs();qo=qg();Xg=`
|
|
866
|
+
const resolvePrivateStateSecretKey = (${bd.toString()});
|
|
867
|
+
`;Nd=`
|
|
868
|
+
const coerceArg = (${ds.toString()});
|
|
869
|
+
`;eh=["@midnight-ntwrk","ws"]});import{indexerPublicDataProvider as rh}from"@midnight-ntwrk/midnight-js-indexer-public-data-provider";function Rd(e){return rh(e.indexer,e.indexerWS??e.indexer.replace("http","ws"))}var $d=()=>{};var Pd={};fe(Pd,{default:()=>ir});import{resolve as ms}from"node:path";function Xr(){return{update(){},stop(){},fail(){},log(){}}}function nh(e){return Id.includes(e)}async function ir(e,t){let r=e.subcommand;if(!r||!nh(r))throw new Z(`Usage: midnight contract <${Id.join("|")}>
|
|
871
870
|
|
|
872
871
|
inspect Show circuits, witnesses, and types for a compiled contract
|
|
873
872
|
deploy Deploy a contract to the network
|
|
874
873
|
call Call a circuit on a deployed contract
|
|
875
874
|
state Read the ledger state of a deployed contract
|
|
876
875
|
|
|
877
|
-
Run "midnight help contract" for more info.`);switch(r){case"inspect":return
|
|
878
|
-
`+
|
|
876
|
+
Run "midnight help contract" for more info.`);switch(r){case"inspect":return sh(e);case"deploy":return oh(e);case"call":return ah(e);case"state":return ch(e)}}function fs(e){let t=A(e,"managed"),r=A(e,"path");return ms(t??r??process.cwd())}async function sh(e){let t=N(e,"json"),r=fs(e),n=A(e,"name"),{info:s}=qe(r,n);if(t){D(sd(s));return}if(process.stderr.write(`
|
|
877
|
+
`+W(`Contract: ${s.name}`)+`
|
|
879
878
|
|
|
880
879
|
`),process.stderr.write(C("Compiler",s.compilerVersion)+`
|
|
881
880
|
`),process.stderr.write(C("Language",s.languageVersion)+`
|
|
@@ -883,18 +882,18 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return Nh(
|
|
|
883
882
|
`),process.stderr.write(`
|
|
884
883
|
`+k(" Circuits")+`
|
|
885
884
|
`),s.circuits.length===0)process.stderr.write(l(" (none)")+`
|
|
886
|
-
`);else for(let o of s.circuits){let i=
|
|
885
|
+
`);else for(let o of s.circuits){let i=td(o),a=rd(o),c=o.pure?L(a):M(a);process.stderr.write(` ${i} ${l("—")} ${c}
|
|
887
886
|
`)}if(process.stderr.write(`
|
|
888
887
|
`+k(" Witnesses")+`
|
|
889
888
|
`),s.witnesses.length===0)process.stderr.write(l(" (none)")+`
|
|
890
|
-
`);else for(let o of s.witnesses)process.stderr.write(` ${
|
|
889
|
+
`);else for(let o of s.witnesses)process.stderr.write(` ${nd(o)}
|
|
891
890
|
`);if(s.siblings.length>0){process.stderr.write(`
|
|
892
891
|
`+k(" Other contracts in this project")+`
|
|
893
892
|
`);for(let o of s.siblings)process.stderr.write(` ${L(o)}
|
|
894
893
|
`);process.stderr.write(`
|
|
895
894
|
`+l(" Inspect a sibling: mn contract inspect --name <name>")+`
|
|
896
895
|
`)}process.stderr.write(`
|
|
897
|
-
`)}async function
|
|
896
|
+
`)}async function _d(e,t,r){await Promise.resolve().then(() => ke());await Promise.resolve().then(() => pe());await Promise.resolve().then(() => at());await Promise.resolve();let{config:c}=te({args:{command:"contract",subcommand:void 0,positionals:[],flags:{network:e}}}),d=ce(ie(r)),u=Buffer.from(d.seed,"hex"),p=d.addresses[e],f=t?Xr():G("Checking wallet..."),g=me();try{let m=(await g.unshielded(p,c)).balances.get(fr)??0n;if(m===0n)throw f.fail("No NIGHT balance"),Error(`Wallet has 0 NIGHT on ${e}.
|
|
898
897
|
|
|
899
898
|
Fund your wallet before deploying:
|
|
900
899
|
Address: ${p}
|
|
@@ -905,63 +904,63 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return Nh(
|
|
|
905
904
|
Register for dust generation:
|
|
906
905
|
Run: midnight dust register --network ${e}
|
|
907
906
|
Then wait: midnight dust status --network ${e}
|
|
908
|
-
`);f.stop(`Wallet OK (${m} NIGHT, dust available)`)}catch(h){throw f.fail("Wallet check failed"),h}}async function
|
|
909
|
-
`+
|
|
907
|
+
`);f.stop(`Wallet OK (${m} NIGHT, dust available)`)}catch(h){throw f.fail("Wallet check failed"),h}}async function Dd(e,t,r){await Promise.resolve().then(() => zo());let s=t?Xr():G("Starting mn serve..."),o=await ss({network:e,wallet:r,onMessage:(i)=>s.update(i)});return s.stop("mn serve ready (port "+o.port+")"),{port:o.port,stop:()=>o.stop()}}async function oh(e){let t=N(e,"json"),r=ms(A(e,"path")??process.cwd()),n=fs(e),s=A(e,"name");await Promise.resolve().then(() => qr());await Promise.resolve().then(() => pe());if(!t)process.stderr.write(`
|
|
908
|
+
`+W("Contract Deploy")+`
|
|
910
909
|
|
|
911
|
-
`);let{info:a}=
|
|
910
|
+
`);let{info:a}=qe(n,s),c=a.witnesses.map((w)=>w.name);if(c.length>0){await Promise.resolve().then(() => cs());if(!is(r))throw Error(as({projectRoot:r,witnessNames:c}))}let d=A(e,"network")??"undeployed",{config:u}=te({args:{command:"contract",subcommand:"deploy",positionals:[],flags:{network:d}}}),p=A(e,"args"),f=[];if(p)try{let w=JSON.parse(p);f=Array.isArray(w)?w:Object.values(w)}catch(w){throw new Z(`Invalid --args JSON: ${w.message}`)}let g=A(e,"secret-key");if(g!==void 0&&!/^[0-9a-fA-F]{64}$/.test(g))throw new Z("--secret-key must be 32 bytes of hex (64 chars)");if(!t){if(process.stderr.write(C("Contract",a.name)+`
|
|
912
911
|
`),process.stderr.write(C("Network",d)+`
|
|
913
912
|
`),f.length>0)process.stderr.write(C("Constructor args",String(f.length))+`
|
|
914
913
|
`);process.stderr.write(`
|
|
915
|
-
`)}await
|
|
914
|
+
`)}await _d(d,t,A(e,"wallet"));let h=await Dd(d,t,A(e,"wallet")),m=t?Xr():G("Deploying contract...");try{let w=await us({dappDir:r,networkConfig:u,managedDir:a.managedDir,contractName:a.name,servePort:h.port,args:f,privateStateSecretKey:g,onMessage:(y)=>m.update(y)});if(m.stop(H("✓")+" Contract deployed"),t)D({subcommand:"deploy",contractName:a.name,address:w.contractAddress,network:d});else process.stderr.write(`
|
|
916
915
|
`),process.stderr.write(C("Address",w.contractAddress)+`
|
|
917
916
|
`),process.stderr.write(`
|
|
918
|
-
`+
|
|
919
|
-
`)
|
|
920
|
-
`)}catch(w){throw m.fail("Deploy failed"),w}finally{await h.stop()}}function
|
|
917
|
+
`+H(" ✓ Deploy successful")+`
|
|
918
|
+
`),ih(w.contractAddress,a.circuits,d),process.stdout.write(w.contractAddress+`
|
|
919
|
+
`)}catch(w){throw m.fail("Deploy failed"),w}finally{await h.stop()}}function ih(e,t,r){let n=r==="undeployed"?"":` --network ${r}`;process.stderr.write(`
|
|
921
920
|
`+l(" Next:")+`
|
|
922
921
|
`),process.stderr.write(l(" mn contract state --address ")+L(e)+l(n)+`
|
|
923
922
|
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(l(" mn contract call --address ")+L(e)+l(" --circuit ")+L(s.name)+l(n)+`
|
|
924
923
|
`);process.stderr.write(`
|
|
925
|
-
`)}async function
|
|
926
|
-
`+
|
|
924
|
+
`)}async function ah(e){let t=N(e,"json"),r=ms(A(e,"path")??process.cwd()),n=fs(e),s=A(e,"name"),o=en(e,"address","contract address"),i=en(e,"circuit","circuit name"),a=A(e,"args");await Promise.resolve().then(() => qr());await Promise.resolve().then(() => pe());if(!t)process.stderr.write(`
|
|
925
|
+
`+W("Contract Call")+`
|
|
927
926
|
|
|
928
|
-
`);let{info:u}=
|
|
927
|
+
`);let{info:u}=qe(n,s),p=[];if(a)try{let w=JSON.parse(a);p=Array.isArray(w)?w:Object.values(w)}catch(w){throw new Z(`Invalid --args JSON: ${w.message}`)}let f=A(e,"network")??"undeployed",{config:g}=te({args:{command:"contract",subcommand:"call",positionals:[],flags:{network:f}}});if(!t)process.stderr.write(C("Contract",u.name)+`
|
|
929
928
|
`),process.stderr.write(C("Circuit",i)+`
|
|
930
929
|
`),process.stderr.write(C("Address",o.slice(0,20)+"...")+`
|
|
931
930
|
|
|
932
|
-
`);await
|
|
933
|
-
`+
|
|
931
|
+
`);await _d(f,t,A(e,"wallet"));let h=await Dd(f,t,A(e,"wallet")),m=t?Xr():G(`Calling ${i}...`);try{let w=await ps({dappDir:r,networkConfig:g,managedDir:u.managedDir,contractName:u.name,contractAddress:o,circuit:i,args:p,servePort:h.port,onMessage:(y)=>m.update(y)});if(m.stop(H("✓")+` ${i} called`),t)D({subcommand:"call",contractName:u.name,circuit:i,address:o,network:f,status:w.status});else process.stderr.write(`
|
|
932
|
+
`+H(" ✓ Circuit call successful")+`
|
|
934
933
|
|
|
935
|
-
`)}catch(w){throw m.fail("Call failed"),w}finally{await h.stop()}}async function
|
|
936
|
-
`+
|
|
934
|
+
`)}catch(w){throw m.fail("Call failed"),w}finally{await h.stop()}}async function ch(e){let t=N(e,"json"),r=ms(A(e,"path")??process.cwd()),n=fs(e),s=A(e,"name"),o=en(e,"address","contract address");await Promise.resolve().then(() => pe());await Promise.resolve().then(() => qr());let c=A(e,"network")??"undeployed",{config:d}=te({args:{command:"contract",subcommand:"state",positionals:[],flags:{network:c}}});if(!t)process.stderr.write(`
|
|
935
|
+
`+W("Contract State")+`
|
|
937
936
|
|
|
938
937
|
`),process.stderr.write(C("Address",o.slice(0,20)+"...")+`
|
|
939
938
|
`),process.stderr.write(C("Network",c)+`
|
|
940
939
|
|
|
941
|
-
`);let u=t?Xr():
|
|
940
|
+
`);let u=t?Xr():G("Querying contract state...");try{let{info:p}=qe(n,s),f=await or({dappDir:r,networkConfig:d,managedDir:p.managedDir,contractName:p.name,contractAddress:o,onMessage:(g)=>u.update(g)});if(u.stop(H("✓")+" State retrieved"),t)D({subcommand:"state",address:o,network:c,...f});else{let g=Object.keys(f.fields).length>0,h=Object.keys(f.maps).length>0;if(g||h){process.stderr.write(k(" Ledger State")+`
|
|
942
941
|
`);for(let[m,w]of Object.entries(f.fields))process.stderr.write(` ${m}: ${L(w)}
|
|
943
942
|
`);for(let[m,w]of Object.entries(f.maps))process.stderr.write(` ${m}: ${l(`Map (${w.size} entries)`)}
|
|
944
943
|
`)}else process.stderr.write(l(" (no ledger fields found)")+`
|
|
945
944
|
`);process.stderr.write(`
|
|
946
|
-
`)}}catch(p){u.stop(M("⚠")+" Parsed state unavailable, showing raw");
|
|
945
|
+
`)}}catch(p){u.stop(M("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() => $d());let h=await Rd(d).queryContractState(o);if(!h)throw Error(`No contract found at address ${o} on ${c}`);let m=h.data??h;if(t)D({subcommand:"state",address:o,network:c,raw:m});else process.stderr.write(k(" Raw State")+`
|
|
947
946
|
`),process.stderr.write(l(" (run from dApp root for parsed ledger fields)")+`
|
|
948
947
|
`),process.stderr.write(` ${JSON.stringify(m).slice(0,200)}
|
|
949
948
|
|
|
950
|
-
`)}}var
|
|
951
|
-
Run this command from the root of a dApp project, or create a ${
|
|
952
|
-
Check the build log: ${i}`);if(await
|
|
953
|
-
Check the build log: ${i}`)}function
|
|
949
|
+
`)}}var Id;var gs=E(()=>{Be();ue();Ve();Jr();Id=["inspect","deploy","call","state"]});import{existsSync as ar,readFileSync as Yr,readdirSync as dh}from"node:fs";import{join as Ft,resolve as lh}from"node:path";function hs(e){let t=lh(e??process.cwd()),r=Ft(t,Yo);if(!ar(r))throw Error(`No ${Yo} found in ${t}
|
|
950
|
+
Run this command from the root of a dApp project, or create a ${Yo} file.`);let n;try{n=JSON.parse(Yr(r,"utf-8"))}catch(o){throw Error(`Failed to parse ${r}: ${o.message}`)}return{config:mh(n,r),configPath:r,dappDir:t}}function Zo(e){let t=Ft(e,uh);if(!ar(t))return[];let r=dh(t,{withFileTypes:!0}),n=[];for(let s of r){if(!s.isDirectory())continue;let o=Ft(t,s.name),i=Ft(o,"suite.json");if(!ar(i))continue;let a;try{a=JSON.parse(Yr(i,"utf-8"))}catch(c){throw Error(`Failed to parse ${i}: ${c.message}`)}n.push({suite:fh(a,i),suiteDir:o})}return n}function Ud(e){let t=Ft(e,"assertions.json");if(!ar(t))return null;let r;try{r=JSON.parse(Yr(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return gh(r,t)}function jd(e){let t=Ft(e,"actions.json");if(!ar(t))return null;let r;try{r=JSON.parse(Yr(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return hh(r,t)}function Wd(e){let t=Ft(e,"prompt.md");if(!ar(t))return null;return Yr(t,"utf-8")}function mh(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw Error(`${t}: must be a JSON object`);let r=e;if(typeof r.name!=="string"||r.name.length===0)throw Error(`${t}: "name" is required and must be a non-empty string`);if(r.network!==void 0&&!Od.includes(r.network))throw Error(`${t}: "network" must be one of: ${Od.join(", ")}`);if(r.port!==void 0&&(typeof r.port!=="number"||r.port<1||r.port>65535))throw Error(`${t}: "port" must be a number between 1 and 65535`);if(r.buildCmd!==void 0&&typeof r.buildCmd!=="string")throw Error(`${t}: "buildCmd" must be a string`);if(r.buildDir!==void 0&&typeof r.buildDir!=="string")throw Error(`${t}: "buildDir" must be a string`);if(r.url!==void 0&&typeof r.url!=="string")throw Error(`${t}: "url" must be a string`);if(!Array.isArray(r.prep))throw Error(`${t}: "prep" is required and must be an array of prep step IDs`);for(let n of r.prep)if(typeof n!=="string"||!ph.test(n))throw Error(`${t}: invalid prep step "${n}". Valid steps: cache-clear, localnet-up, balance:<amount>, dust-register, dust-wait, mn-serve, build-and-serve`);return{name:r.name,network:r.network??"undeployed",port:r.port,buildCmd:r.buildCmd,buildDir:r.buildDir,url:r.url,contractEntry:r.contractEntry,prep:r.prep}}function fh(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw Error(`${t}: must be a JSON object`);let r=e;if(typeof r.name!=="string"||r.name.length===0)throw Error(`${t}: "name" is required and must be a non-empty string`);if(typeof r.description!=="string")throw Error(`${t}: "description" is required and must be a string`);if(!Md.includes(r.strategy))throw Error(`${t}: "strategy" must be one of: ${Md.join(", ")}`);if(r.timeout!==void 0&&(typeof r.timeout!=="number"||r.timeout<=0))throw Error(`${t}: "timeout" must be a positive number (seconds)`);if(r.browserMode!==void 0&&!Fd.includes(r.browserMode))throw Error(`${t}: "browserMode" must be one of: ${Fd.join(", ")}`);return{name:r.name,description:r.description,strategy:r.strategy,browserMode:r.browserMode,model:r.model,effort:r.effort,timeout:r.timeout,depends:Array.isArray(r.depends)?r.depends:void 0}}function gh(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw Error(`${t}: must be a JSON object`);let r=e;if(!Array.isArray(r.post))throw Error(`${t}: "post" is required and must be an array of assertion checks`);for(let n of r.post){if(typeof n!=="object"||n===null)throw Error(`${t}: each assertion check must be an object`);let s=n;if(typeof s.id!=="string")throw Error(`${t}: each assertion check must have a string "id"`);if(typeof s.type!=="string")throw Error(`${t}: assertion "${s.id}" must have a string "type"`);if(typeof s.expect!=="string"||s.expect!=="pass"&&s.expect!=="fail")throw Error(`${t}: assertion "${s.id}" must have "expect" set to "pass" or "fail"`)}return{pre:Array.isArray(r.pre)?r.pre:void 0,post:r.post}}function hh(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw Error(`${t}: must be a JSON object`);let r=e;if(!Array.isArray(r.actions))throw Error(`${t}: "actions" is required and must be an array`);for(let n of r.actions){if(typeof n!=="object"||n===null)throw Error(`${t}: each action must be an object`);let s=n;if(typeof s.id!=="string")throw Error(`${t}: each action must have a string "id"`);if(typeof s.type!=="string"||!Ld.includes(s.type))throw Error(`${t}: action "${s.id}" has invalid type "${s.type}". Valid: ${Ld.join(", ")}`);if(s.type==="contract-call"&&typeof s.circuit!=="string")throw Error(`${t}: action "${s.id}" (contract-call) requires a "circuit" field`)}return{actions:r.actions}}var Yo="dapp.test.json",uh="tests/suites",Od,Md,Fd,ph,Ld;var Bd=E(()=>{Od=["undeployed","preprod","preview"],Md=["browser","cli","hybrid"],Fd=["dom","script","vision","auto"],ph=/^(cache-clear|localnet-up|balance:\d+|dust|dust-register|dust-wait|mn-serve|build-and-serve)$/;Ld=["contract-deploy","contract-call","contract-state","wallet-cmd"]});function Hd(){let e=[];return{cleanups:e,addCleanup(t){e.push(t)}}}import{spawn as wh}from"node:child_process";import{createWriteStream as yh}from"node:fs";import{join as Sh}from"node:path";import bh from"node:http";import vh from"node:net";async function Kd(e){let{dappDir:t,buildCmd:r,buildDir:n=".",port:s,url:o,logFile:i,timeoutMs:a=240000,onMessage:c=()=>{}}=e;if(await kh(s)){if(await Gd(o))return c(`Reusing existing dev server on port ${s} (URL responds 200)`),{port:s,child:{kill:()=>!0},stop(){}};c(`Port ${s} in use by an unresponsive process — killing it`),await Ch(s),await new Promise((m)=>setTimeout(m,2000))}let d=Sh(t,n),u=yh(i,{flags:"a"}),p=wh("bash",["-lc",r],{cwd:d,stdio:["ignore","pipe","pipe"],detached:!1});p.stdout?.pipe(u),p.stderr?.pipe(u);let f=!1,g=null;p.on("exit",(m)=>{f=!0,g=m}),c(`Building (${r})...`);let h=Date.now()+a;while(Date.now()<h){if(f)throw Error(`Build process exited with code ${g} before the UI was ready.
|
|
951
|
+
Check the build log: ${i}`);if(await Gd(o))return c("UI ready"),{port:s,child:p,stop(){if(!f)p.kill("SIGTERM"),setTimeout(()=>{if(!f)p.kill("SIGKILL")},5000).unref();u.end()}};await new Promise((m)=>setTimeout(m,2000))}throw p.kill("SIGTERM"),u.end(),Error(`UI did not start within ${Math.round(a/1000)}s at ${o}
|
|
952
|
+
Check the build log: ${i}`)}function kh(e){return new Promise((t)=>{let r=new vh.Socket;r.setTimeout(1000),r.on("connect",()=>{r.destroy(),t(!0)}),r.on("timeout",()=>{r.destroy(),t(!1)}),r.on("error",()=>{t(!1)}),r.connect(e,"127.0.0.1")})}async function Ch(e){let{execSync:t}=await import("node:child_process");try{let r=t(`lsof -ti:${e}`,{encoding:"utf-8"}).trim();if(r)t(`kill ${r}`,{stdio:"pipe"})}catch{}}function Gd(e){return new Promise((t)=>{let r=bh.get(e,{timeout:3000},(n)=>{t(n.statusCode===200),n.resume()});r.on("error",()=>t(!1)),r.on("timeout",()=>{r.destroy(),t(!1)})})}var Jd=()=>{};import*as Xd from"@midnight-ntwrk/ledger-v8";import{execSync as Ah}from"node:child_process";import{join as xh}from"node:path";async function Yd(e,t,r,n){let s=[];for(let o of e.prep){let i=Date.now();n.onStepStart(o);try{await Eh(o,e,t,r,n);let a=Date.now()-i;s.push({step:o,status:"pass",duration:a}),n.onStepComplete(o,"pass",a)}catch(a){let c=Date.now()-i,d=a.message;throw s.push({step:o,status:"fail",duration:c,error:d}),n.onStepComplete(o,"fail",c,d),Error(`Prep step "${o}" failed: ${d}`)}}return s}async function Eh(e,t,r,n,s){if(e==="cache-clear")return Th(t);if(e==="localnet-up")return $h(s);if(e.startsWith("balance:")){let o=parseInt(e.split(":")[1],10);return Ih(o,t,s)}if(e==="dust"||e==="dust-register"||e==="dust-wait")return _h(t,s);if(e==="mn-serve")return Dh(t,n,s);if(e==="build-and-serve")return Ph(t,r,n,s);throw Error(`Unknown prep step: ${e}`)}async function Th(e){let t=e.network??"undeployed";Je(void 0,t)}function Rh(){try{return Ah(`curl -s -o /dev/null http://localhost:8088${kt} --max-time 3`,{timeout:5000,stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function zd(e,t){let r=Date.now();while(Date.now()-r<e){if(Rh())return!0;t?.("Waiting for indexer...");let{execSync:n}=xs("node:child_process");try{n("sleep 2",{timeout:3000})}catch{}}return!1}async function $h(e){Gn(),tr();let t=["node","indexer","proof-server"],r=ct();if(r.length>=3&&t.every((i)=>r.some((a)=>a.name===i&&a.state==="running"))&&r.every((i)=>!i.health||i.health==="healthy")){if(zd(1e4,(i)=>e.onMessage(i))){e.onMessage("Localnet OK (3 services healthy, indexer responding)");return}e.onMessage("Localnet containers running but indexer not responding. Restarting...")}let s=r.filter((i)=>i.state==="running").map((i)=>i.name),o=t.filter((i)=>!s.includes(i));if(o.length>0)e.onMessage(`Localnet missing: ${o.join(", ")}. Restarting clean...`);else e.onMessage("Localnet unhealthy. Restarting clean...");for(let i=1;i<=ws;i++){e.onMessage(`Attempt ${i}/${ws}: tearing down...`),ze("down"),e.onMessage(`Attempt ${i}/${ws}: starting...`),ze("up -d");let a=rr(Nh);if(a&&zd(Vd,(f)=>e.onMessage(f))){e.onMessage("Localnet running (indexer verified)");return}if(a){e.onMessage(`Attempt ${i}: Docker healthy but indexer not responding after ${Vd/1000}s`);continue}let c=ct(),d=t.filter((f)=>!c.some((g)=>g.name===f&&g.state==="running")),u=c.filter((f)=>f.state==="running"&&f.health&&f.health!=="healthy"),p=[];if(d.length>0)p.push(`not running: ${d.join(", ")}`);if(u.length>0)p.push(`unhealthy: ${u.map((f)=>f.name).join(", ")}`);e.onMessage(`Attempt ${i} failed: ${p.join("; ")||"timeout"}`)}throw Error(`Localnet failed to start after ${ws} attempts`)}async function Ih(e,t,r){let n=t.network??"undeployed",{config:s}=te({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:n}}}),o=ce(ie()),i=Buffer.from(o.seed,"hex"),a=o.addresses[n];r.onMessage("Checking balance...");let c=he((h,m)=>{r.onMessage(`SDK: ${m}`)}),d=Ce(),u=wt(a,n),p=await Qe(i,s,u);try{let h=await ht(p,{syncMode:"lite",onProgress:(y,S)=>{if(S>0){let b=Math.min(Math.round(y/S*100),100);r.onMessage(`Syncing wallet... ${b}%`)}},onSyncDetail:(y)=>{r.onMessage(`Syncing wallet... (${y})`)}}),m=Xd.unshieldedToken().raw,w=h.unshielded.balances[m]??0n;if(w>0n){r.onMessage(`Balance OK: ${w}`);try{await je(a,n,p.facade)}catch{}return}}finally{d(),c();try{await Ue(p)}catch{}}if(n!=="undeployed")throw Error(`Wallet has 0 NIGHT on ${n}. Fund your wallet before running tests:
|
|
954
953
|
mn airdrop ${e} (if faucet available)
|
|
955
|
-
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let f=Buffer.from(
|
|
954
|
+
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let f=Buffer.from(rt,"hex"),g=ve(f,n);await Zt({seedBuffer:f,networkConfig:s,recipientAddress:a,amountNight:e,onSync(h,m){},onDust(h){r.onMessage(`Dust: ${h}`)},onProving(){r.onMessage("Generating ZK proof...")},onSubmitting(){r.onMessage("Submitting airdrop transaction...")},onSyncWarning(h,m){r.onMessage(`Syncing genesis... (${m})`)}}),r.onMessage(`Airdropped ${e} NIGHT`)}async function _h(e,t){let r=e.network??"undeployed",{config:n}=te({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}}),s=ce(ie()),o=Buffer.from(s.seed,"hex"),i=s.addresses[r],a=he(),c=Ce(),d=wt(i,r),u=await Qe(o,n,d);try{if(t.onMessage("Syncing wallet..."),await ht(u,{syncMode:"lite"}),t.onMessage("Ensuring dust..."),(await tt(u,(h)=>t.onMessage(`Dust: ${h}`))).alreadyAvailable){t.onMessage("Dust already available");try{await je(i,r,u.facade)}catch{}return}t.onMessage("Dust registered. Waiting for coins to become available...");let f=await Vt(u,qd);if(!(()=>{try{let h=f.dust;return h?.availableCoins?.length>0||h?.balance(new Date)>0n}catch{return!1}})()){if(r!=="undeployed")throw Error(`Dust not available on ${r}. Register dust and wait for it to generate:
|
|
956
955
|
mn dust register
|
|
957
|
-
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${
|
|
958
|
-
`).filter(Boolean);e(`Found ${r.length} orphan chrome-devtools-mcp Chrome process(es), killing`);for(let n of r)try{
|
|
956
|
+
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${qd/1000}s. The chain may be slow — try again.`)}t.onMessage("Dust is available");try{await je(i,r,u.facade)}catch{}}finally{c(),a();try{await Ue(u)}catch{}}}async function Dh(e,t,r){r.onMessage("Starting mn serve...");let n=await ss({port:void 0,network:e.network,onMessage:(s)=>r.onMessage(`[serve] ${s}`)});t.serveHandle=n,t.addCleanup(async()=>n.stop()),r.onMessage(`mn serve ready on port ${n.port}`)}async function Ph(e,t,r,n){if(!e.buildCmd){n.onMessage("No buildCmd in config, skipping build");return}let s=e.port??4173,o=e.url??`http://localhost:${s}/`,i=xh(t,"tests","results",`build_${Date.now()}.log`),a=await Kd({dappDir:t,buildCmd:e.buildCmd,buildDir:e.buildDir,port:s,url:o,logFile:i,onMessage:(c)=>n.onMessage(`[build] ${c}`)});r.buildHandle=a,r.addCleanup(async()=>a.stop())}var Nh=30000,ws=2,Vd=30000,qd=90000;var Zd=E(()=>{yt();ke();pe();Kn();Ke();yt();bt();Ge();zo();Jd()});import{execSync as Qd,spawn as Oh}from"node:child_process";import{createWriteStream as Mh,existsSync as Fh,mkdirSync as Lh,readFileSync as Uh}from"node:fs";import{dirname as jh,join as Wh}from"node:path";import{homedir as Bh}from"node:os";function Hh(){let e=Wh(Bh(),".claude.json");if(!Fh(e))return!1;try{let t=JSON.parse(Uh(e,"utf-8"));return Boolean(t.mcpServers?.["chrome-devtools"])}catch{return!1}}function Kh(e){let t;try{t=Qd(`ps -ax -o pid,command | grep "${Gh}" | grep -v grep | awk '{print $1}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return}if(!t)return;let r=t.split(`
|
|
957
|
+
`).filter(Boolean);e(`Found ${r.length} orphan chrome-devtools-mcp Chrome process(es), killing`);for(let n of r)try{Qd(`kill ${n}`,{stdio:"pipe"})}catch{}}function Qo(e){let t=e.browserMode??"vision";if(t==="auto")return"vision";return t}async function el(e){let{suite:t,prompt:r,dappDir:n,logFile:s,onMessage:o=()=>{}}=e,i=(t.timeout??600)*1000,a=Qo(t);if(a==="dom"||a==="script"){if(!Hh())throw Error(`Browser mode "${a}" requires the chrome-devtools MCP server, which is not registered in ~/.claude.json.
|
|
959
958
|
|
|
960
959
|
Install it:
|
|
961
960
|
claude mcp add chrome-devtools --scope user npx chrome-devtools-mcp@latest
|
|
962
961
|
|
|
963
|
-
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");
|
|
964
|
-
`),s}function
|
|
962
|
+
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");Kh(o)}Lh(jh(s),{recursive:!0});let c=Mh(s),d=[];if(a==="vision")d.push("--chrome");if(d.push("--dangerously-skip-permissions"),t.model)d.push("--model",t.model);if(t.effort)d.push("--effort",t.effort);let u=r;if(a==="dom")u=Jh+r;else if(a==="script")u=Vh+r;return d.push("-p",u),o(`Launching Claude (mode: ${a}, model: ${t.model??"default"}, timeout: ${t.timeout??600}s)`),new Promise((p)=>{let f=Oh("claude",d,{cwd:n,stdio:["inherit","pipe","inherit"]}),g=!1;f.stdout?.on("data",(m)=>{process.stdout.write(m),c.write(m)});let h=setTimeout(()=>{g=!0,o(`Timeout: test exceeded ${t.timeout??600}s`),f.kill("SIGTERM"),setTimeout(()=>{if(!f.killed)f.kill("SIGKILL")},1e4).unref()},i);f.on("close",(m)=>{clearTimeout(h),c.end(),p({exitCode:m??1,logFile:s,timedOut:g})}),f.on("error",(m)=>{clearTimeout(h),c.end(),o(`Claude process error: ${m.message}`),p({exitCode:1,logFile:s,timedOut:!1})})})}var Gh="chrome-devtools-mcp/chrome-profile",Jh="## Browser Automation Mode: DOM (Accessibility Tree)\n\nYou have chrome-devtools MCP tools available. You MUST follow these rules:\n\n1. Use `navigate_page` to open URLs in Chrome.\n2. Use `take_snapshot` to read the page — it returns a structured accessibility tree with element UIDs. This is your primary tool for understanding page state.\n3. Use `click`, `fill`, and `type_text` with element UIDs from the snapshot to interact with the page.\n4. Use `press_key` for keyboard input (Enter, Escape, Tab, etc.).\n5. Only use `take_screenshot` for final visual verification or when the accessibility tree is insufficient.\n6. Do NOT rely on screenshots for navigation — the accessibility tree is faster and more reliable.\n7. After each interaction, take a new `take_snapshot` to verify the result.\n\n---\n\n",Vh="## Browser Automation Mode: Script (Canvas App)\n\nYou have chrome-devtools MCP tools available. This is a canvas-based app — the accessibility tree will be empty. You MUST follow these rules:\n\n1. Use `navigate_page` to open the URL in Chrome.\n2. Use `evaluate_script` to dispatch keyboard input via `window.dispatchEvent(new KeyboardEvent(...))`.\n3. Use `evaluate_script` to read DOM state (e.g., toast notifications via `document.querySelector`).\n4. Use `list_console_messages` to monitor app output (contract addresses, errors, status changes).\n5. Use `take_screenshot` at key checkpoints to verify visual state — but minimize usage (a few, not every step).\n6. Do NOT use `take_snapshot` — the accessibility tree is empty for canvas content.\n7. Between actions, use `take_screenshot` or `list_console_messages` to verify transitions — not rapid polling.\n\n---\n\n";var tl=()=>{};import{existsSync as zh,readFileSync as qh}from"node:fs";import Xh from"node:net";async function rl(e,t){let r=[];for(let n of e)try{let s=await Yh(n,t),o=n.expect==="pass"?s:!s;r.push({id:n.id,status:o?"pass":"fail",message:o?void 0:`Expected ${n.expect}, got ${s?"pass":"fail"}`})}catch(s){r.push({id:n.id,status:"fail",message:s.message})}return r}async function Yh(e,t){switch(e.type){case"balance-changed":return Zh(e,t);case"process-exit-code":return Qh(e,t);case"port-listening":return ew(e);case"agent-report-no-failure":return rw(e,t);default:throw Error(`Unsupported assertion type: "${e.type}" (available in v2)`)}}function Zh(e,t){if(t.preBalance===void 0||t.postBalance===void 0)throw Error("Balance data not available — balance:N prep step may not have run");let r=BigInt(t.preBalance),n=BigInt(t.postBalance),s=e.params.direction;if(s==="decreased")return n<r;if(s==="increased")return n>r;if(s==="unchanged")return n===r;return n!==r}function Qh(e,t){if(t.processExitCode===void 0)throw Error("Process exit code not available");let r=e.params.code;return t.processExitCode===r}function ew(e){let t=e.params.port;return new Promise((r)=>{let n=new Xh.Socket;n.setTimeout(2000),n.on("connect",()=>{n.destroy(),r(!0)}),n.on("timeout",()=>{n.destroy(),r(!1)}),n.on("error",()=>{r(!1)}),n.connect(t,"127.0.0.1")})}function rw(e,t){let r=e.params??{},n=r.logPath??t.agentLogPath;if(!n||!zh(n))return!0;let s;try{s=qh(n,"utf-8")}catch{return!0}let o=sw(s),i=r.markers??tw;for(let a of i)if(nw(o,a))return!1;return!0}function nw(e,t){if(/\s/.test(t)||/[^ -~]/.test(t))return e.toLowerCase().includes(t.toLowerCase());let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${r}\\b`,"i").test(e)}function sw(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"")}var tw;var nl=E(()=>{tw=["FAILED","❌","did not pass","test failed","overall: fail","result: fail"]});import{existsSync as ow,mkdirSync as iw,writeFileSync as aw,readFileSync as cw,readdirSync as dw}from"node:fs";import{join as ys}from"node:path";function ol(e,t){let r=ys(t,sl);iw(r,{recursive:!0});let n=`${e.suite}_${e.timestamp.replace(/[:.]/g,"-")}.json`,s=ys(r,n);return aw(s,JSON.stringify(e,null,2)+`
|
|
963
|
+
`),s}function il(e,t){let r=ei(e,t);return r.length>0?r[0]:null}function ei(e,t){let r=ys(e,sl);if(!ow(r))return[];let n=dw(r).filter((o)=>o.endsWith(".json")).filter((o)=>!t||o.startsWith(t+"_")),s=[];for(let o of n)try{let i=cw(ys(r,o),"utf-8");s.push(JSON.parse(i))}catch{}return s.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),s}var sl="tests/results";var al=()=>{};import{execSync as lw}from"node:child_process";async function ti(e,t){if(e.buildHandle)try{e.buildHandle.stop(),t?.("Stopped build process")}catch{t?.("Failed to stop build process (may have already exited)")}if(e.serveHandle)try{await e.serveHandle.stop(),t?.("Stopped mn serve")}catch{t?.("Failed to stop mn serve")}for(let r of e.cleanups.reverse())try{await r()}catch{}if(e.buildHandle?.port)uw(e.buildHandle.port,t)}function uw(e,t){try{lw(`osascript -e 'tell application "Google Chrome"
|
|
965
964
|
repeat with theWindow in every window
|
|
966
965
|
repeat with theTab in every tab of theWindow
|
|
967
966
|
if URL of theTab contains "localhost:${e}" then
|
|
@@ -969,7 +968,7 @@ Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision
|
|
|
969
968
|
end if
|
|
970
969
|
end repeat
|
|
971
970
|
end repeat
|
|
972
|
-
end tell'`,{timeout:5000,stdio:"pipe"}),t?.(`Closed Chrome tabs for localhost:${e}`)}catch{}}var
|
|
971
|
+
end tell'`,{timeout:5000,stdio:"pipe"}),t?.(`Closed Chrome tabs for localhost:${e}`)}catch{}}var cl=()=>{};function dl(e){switch(e["type-name"]){case"Uint":return 0;case"Bytes":{let t=e.length??32;return Array.from({length:t},()=>0)}case"Boolean":return!1;case"String":return"test";case"Opaque":return e.tsType==="string"?"test":null;case"Vector":return[];case"Map":return{};case"Set":return[];case"Option":return null;case"Tuple":return(e.types??[]).map(dl);default:return null}}function ri(e){let t={};for(let r of e.arguments)t[r.name]=dl(r.type);return t}function ni(e,t){if((t.strategy??"cli")==="browser"){if(!t.browser)throw Error("Browser strategy requires browser options (port, buildCmd, buildDir?, url?)");return yw(t,t.browser)}return ww(e,t)}function ww(e,t){let r=t.suiteName??pw,n=t.network??ll,s=t.servePort??ul;return{dappConfig:{name:t.contractName,network:n,prep:pl},suite:{name:r,description:`Auto-generated CLI test suite for ${t.contractName}. Edit args and add ledger-field assertions to taste.`,strategy:"cli",timeout:t.timeoutSeconds??fw},actions:{actions:bw(e)},assertions:{post:[ml(s)]},prompt:null,suiteName:r}}function yw(e,t){let r=e.suiteName??mw,n=e.network??ll,s=e.servePort??ul,o=t.url??`http://localhost:${t.port}/`,i={name:e.contractName,network:n,port:t.port,buildCmd:t.buildCmd,url:o,prep:hw};if(t.buildDir)i.buildDir=t.buildDir;return{dappConfig:i,suite:{name:r,description:`Auto-generated browser test suite for ${e.contractName}. Edit prompt.md to describe the dApp-specific user flow.`,strategy:"browser",timeout:e.timeoutSeconds??gw,...t.browserMode?{browserMode:t.browserMode}:{}},actions:null,assertions:{post:[{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"},ml(s),{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}]},prompt:Sw(e.contractName,o),suiteName:r}}function ml(e){return{id:"serve-port-listening",type:"port-listening",params:{port:e},expect:"pass"}}function Sw(e,t){return`You are running an automated E2E test of ${e}.
|
|
973
972
|
|
|
974
973
|
The UI is at ${t} — open it in Chrome.
|
|
975
974
|
mn serve is running with --approve-all so contract calls will auto-approve.
|
|
@@ -999,44 +998,44 @@ Follow these steps:
|
|
|
999
998
|
|
|
1000
999
|
If any step fails, report exactly what you see on screen and stop.
|
|
1001
1000
|
Take screenshots at each major step to document the test.
|
|
1002
|
-
`}function
|
|
1001
|
+
`}function bw(e){let t=[{id:"deploy",type:"contract-deploy"},{id:"check-initial",type:"contract-state"}],r=e.filter((n)=>!n.pure);for(let n of r){let s={id:`call-${n.name}`,type:"contract-call",circuit:n.name};if(n.arguments.length>0)s.args=ri(n);t.push(s)}return t.push({id:"check-final",type:"contract-state"}),t}var ll="undeployed",pw="cli-default",mw="ui-default",fw=300,gw=600,ul=9932,pl,hw;var si=E(()=>{pl=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],hw=[...pl,"build-and-serve"]});import{existsSync as gl,mkdirSync as vw,readFileSync as kw,writeFileSync as fl}from"node:fs";import{join as cr}from"node:path";function hl(e,t){let{dappDir:r,force:n=!1}=t,s=cr(r,"tests","suites",e.suiteName),o=cr(r,"dapp.test.json"),i=[{path:cr(s,"suite.json"),kind:"json",body:e.suite},{path:cr(s,"assertions.json"),kind:"json",body:e.assertions}];if(e.actions)i.push({path:cr(s,"actions.json"),kind:"json",body:e.actions});if(e.prompt)i.push({path:cr(s,"prompt.md"),kind:"text",body:e.prompt});if(!n){let u=i.filter((p)=>gl(p.path)).map((p)=>p.path);if(u.length>0)throw Error(`Suite "${e.suiteName}" already exists at ${s}.
|
|
1003
1002
|
Pick a different suite name (--suite <name>) or pass --force to overwrite.
|
|
1004
1003
|
Existing files:
|
|
1005
1004
|
`+u.map((p)=>` - ${p}`).join(`
|
|
1006
|
-
`))}let a=
|
|
1005
|
+
`))}let a=Cw(o,e,n);vw(s,{recursive:!0});let c=[],d=[];if(a.action==="write")fl(o,JSON.stringify(e.dappConfig,null,2)+`
|
|
1007
1006
|
`),c.push(o);else d.push(o);for(let u of i){let p=u.kind==="json"?JSON.stringify(u.body,null,2)+`
|
|
1008
|
-
`:u.body
|
|
1009
|
-
Fix or remove it (or pass --force to overwrite).`)}if(n.name!==t.dappConfig.name)throw Error(`${e} exists with name "${String(n.name)}" but this scaffold targets "${t.dappConfig.name}". Use --force to overwrite, or run from the right project directory.`);return{action:"preserve"}}var
|
|
1007
|
+
`:u.body;fl(u.path,p),c.push(u.path)}return{written:c,preserved:d}}function Cw(e,t,r){if(r||!gl(e))return{action:"write"};let n;try{n=JSON.parse(kw(e,"utf-8"))}catch(s){let o=s instanceof Error?s.message:String(s);throw Error(`${e} exists but is not valid JSON: ${o}
|
|
1008
|
+
Fix or remove it (or pass --force to overwrite).`)}if(n.name!==t.dappConfig.name)throw Error(`${e} exists with name "${String(n.name)}" but this scaffold targets "${t.dappConfig.name}". Use --force to overwrite, or run from the right project directory.`);return{action:"preserve"}}var wl=()=>{};import{existsSync as Sl,readdirSync as Aw,readFileSync as xw,statSync as Ew}from"node:fs";import{basename as Tw,extname as Nw,join as bl,relative as Rw}from"node:path";function vl(e){let t=new Map;for(let r of $w){let n=bl(e,r);if(!Sl(n))continue;oi(n,e,t)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function kl(e,t=e){if(!Sl(e))return[];let r=new Map;return oi(e,t,r),[...r.values()].sort((n,s)=>n.name.localeCompare(s.name))}function oi(e,t,r){let n;try{n=Aw(e)}catch{return}for(let s of n){let o=bl(e,s),i;try{i=Ew(o)}catch{continue}if(i.isDirectory()){if(Iw.has(s.toLowerCase()))continue;oi(o,t,r);continue}if(Nw(s)!==yl)continue;if(s.endsWith(".test.tsx")||s.endsWith(".spec.tsx"))continue;let a=Tw(s,yl);if(!_w(a,o))continue;let c=Pw(a);if(r.has(c))continue;r.set(c,{name:c,component:a,path:o,relativePath:Rw(t,o)})}}function _w(e,t){if(!/^[A-Z][A-Za-z0-9]*$/.test(e))return!1;let r;try{r=xw(t,"utf-8")}catch{return!1}return Dw.test(r)}function Pw(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}var $w,yl=".tsx",Iw,Dw;var ii=E(()=>{$w=["src/components","src/pages","src/screens","src/views"];Iw=new Set(["layout","layouts","shared","common","ui","icons","styles"]);Dw=/\bexport\s+(default\b|const\s+[A-Z]|function\s+[A-Z])/});import{existsSync as Ow,statSync as Mw}from"node:fs";import*as Cl from"node:readline";function Al(){return process.stdin.isTTY===!0}function Ye(e,t){let r=Cl.createInterface({input:process.stdin,output:process.stderr}),n=t!==void 0?l(` [${t}]`):"";return new Promise((s)=>{r.question(` ${e}${n}: `,(o)=>{r.close();let i=o.trim();s(i===""&&t!==void 0?t:i)})})}async function xl(){process.stderr.write(`
|
|
1010
1009
|
`+L("Test scaffold setup")+`
|
|
1011
1010
|
`);for(;;){let e=(await Ye("Strategy? cli or ui","cli")).toLowerCase();if(e==="cli")return"cli";if(e==="ui"||e==="browser")return"browser";process.stderr.write(l(` Unknown strategy "${e}". Pick "cli" or "ui".
|
|
1012
|
-
`))}}async function
|
|
1011
|
+
`))}}async function El(e={}){process.stderr.write(`
|
|
1013
1012
|
`+l("Browser test scaffold needs your dApp UI details:")+`
|
|
1014
|
-
`);let t=e.port!==void 0?String(e.port):await Ye("Dev server port","4173"),r=parseInt(t,10);if(!Number.isFinite(r)||r<=0||r>65535)throw Error(`Invalid port "${t}" — must be a number between 1 and 65535.`);let n=e.buildCmd??await Ye("Build command","npm run dev");if(!n)throw Error("Build command is required for browser strategy.");let s=e.buildDir!==void 0?e.buildDir:await Ye("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await Ye("URL",`http://localhost:${r}/`),a=e.browserMode??await
|
|
1013
|
+
`);let t=e.port!==void 0?String(e.port):await Ye("Dev server port","4173"),r=parseInt(t,10);if(!Number.isFinite(r)||r<=0||r>65535)throw Error(`Invalid port "${t}" — must be a number between 1 and 65535.`);let n=e.buildCmd??await Ye("Build command","npm run dev");if(!n)throw Error("Build command is required for browser strategy.");let s=e.buildDir!==void 0?e.buildDir:await Ye("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await Ye("URL",`http://localhost:${r}/`),a=e.browserMode??await Fw();return{port:r,buildCmd:n,buildDir:o,url:i,browserMode:a}}async function Fw(){process.stderr.write(`
|
|
1015
1014
|
`+L("Browser mode — how should Claude perceive the page?")+`
|
|
1016
1015
|
`),process.stderr.write(` ${l("1.")} dom ${l("— accessibility tree (text). Fast. HTML / React / Vue UIs.")}
|
|
1017
1016
|
`),process.stderr.write(` ${l("2.")} vision ${l("— screenshots. Slow. Canvas games (no DOM).")}
|
|
1018
1017
|
`),process.stderr.write(` ${l("3.")} script ${l("— direct JS. Fastest. Needs dApp-side hooks (advanced).")}
|
|
1019
1018
|
`),process.stderr.write(l(` dom and script need chrome-devtools-mcp installed.
|
|
1020
1019
|
`));for(;;){let e=(await Ye("Mode","dom")).toLowerCase().trim();if(e==="1"||e==="dom")return"dom";if(e==="2"||e==="vision")return"vision";if(e==="3"||e==="script")return"script";process.stderr.write(M(` Pick 1 (dom), 2 (vision), or 3 (script).
|
|
1021
|
-
`))}}async function
|
|
1020
|
+
`))}}async function Tl(e){let t=e.filter((r)=>!r.pure);if(t.length===0){process.stderr.write(l(` No impure circuits in this contract — nothing to test as a write path.
|
|
1022
1021
|
`));return}process.stderr.write(`
|
|
1023
1022
|
`+L("Pick the circuit this suite will exercise:")+`
|
|
1024
1023
|
`);for(let r=0;r<t.length;r++)process.stderr.write(` ${l(`${r+1}.`)} ${t[r].name}
|
|
1025
1024
|
`);process.stderr.write(l(` (or type "skip" to scaffold all circuits without AI)
|
|
1026
1025
|
`));for(;;){let r=(await Ye("Circuit","1")).trim();if(r.toLowerCase()==="skip")return;let n=parseInt(r,10);if(Number.isFinite(n)&&n>=1&&n<=t.length)return t[n-1];let s=t.find((o)=>o.name===r);if(s)return s;process.stderr.write(l(` Pick a number 1–${t.length}, the circuit name, or "skip".
|
|
1027
|
-
`))}}async function
|
|
1026
|
+
`))}}async function ai(e){if(e.length===0)return Lw();process.stderr.write(`
|
|
1028
1027
|
`+L("Pick the screen this suite will test:")+`
|
|
1029
1028
|
`);for(let t=0;t<e.length;t++)process.stderr.write(` ${l(`${t+1}.`)} ${e[t].name} ${l(`(${e[t].relativePath})`)}
|
|
1030
1029
|
`);process.stderr.write(l(` (or type "skip" to scaffold a generic prompt.md without AI)
|
|
1031
1030
|
`));for(;;){let t=(await Ye("Screen","1")).trim();if(t.toLowerCase()==="skip")return;let r=parseInt(t,10);if(Number.isFinite(r)&&r>=1&&r<=e.length)return e[r-1];let n=e.find((s)=>s.name===t||s.component===t);if(n)return n;process.stderr.write(l(` Pick a number 1–${e.length}, the screen name, or "skip".
|
|
1032
|
-
`))}}async function
|
|
1031
|
+
`))}}async function Lw(){process.stderr.write(l(`
|
|
1033
1032
|
Could not auto-discover screens (no src/components, src/pages, or src/screens under the build dir).
|
|
1034
|
-
`));for(;;){let e=(await Ye('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!
|
|
1035
|
-
`));continue}let t;try{t=
|
|
1036
|
-
`));continue}if(t.isDirectory()){let r=
|
|
1037
|
-
`));continue}return
|
|
1038
|
-
`));continue}return
|
|
1039
|
-
`))}}function
|
|
1033
|
+
`));for(;;){let e=(await Ye('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!Ow(e)){process.stderr.write(l(` No such path: ${e}
|
|
1034
|
+
`));continue}let t;try{t=Mw(e)}catch{process.stderr.write(l(` Cannot stat: ${e}
|
|
1035
|
+
`));continue}if(t.isDirectory()){let r=kl(e);if(r.length===0){process.stderr.write(l(` No PascalCase .tsx components in ${e}
|
|
1036
|
+
`));continue}return ai(r)}if(!e.endsWith(".tsx")){process.stderr.write(l(` Not a .tsx file: ${e}
|
|
1037
|
+
`));continue}return jw(e)}}async function Nl(){let e=(await Ye("What does success look like? (one line, optional)")).trim();return e===""?void 0:e}async function ci(e){for(;;){let t=(await Ye("Suite name",e)).trim();if(Uw(t))return t;process.stderr.write(M(` Suite names must be kebab-case (a–z, 0–9, dashes, underscores). Try again.
|
|
1038
|
+
`))}}function Uw(e){return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e)}function jw(e){let r=(e.split("/").pop()??e).replace(/\.tsx$/,"");return{name:r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase(),component:r,path:e,relativePath:e}}var Rl=E(()=>{ii()});function _l(e){let{contractName:t,contractSummary:r,contractSource:n,targetCircuit:s,goal:o,witnessDependentCircuits:i}=e,a=i&&i.size>0?`
|
|
1040
1039
|
## Circuits NOT testable from a CLI suite
|
|
1041
1040
|
|
|
1042
1041
|
These circuits call witnesses that read from private state. In a
|
|
@@ -1141,9 +1140,9 @@ Args coercion the runner applies (so JSON arg values can be):
|
|
|
1141
1140
|
- [0..255] int array → Uint8Array for Bytes<N>
|
|
1142
1141
|
- object → recurses into Struct fields
|
|
1143
1142
|
|
|
1144
|
-
${
|
|
1143
|
+
${Il}
|
|
1145
1144
|
|
|
1146
|
-
Now produce the JSON.`}function
|
|
1145
|
+
Now produce the JSON.`}function Dl(e){let{contractName:t,contractSummary:r,screenComponent:n,screenSource:s,relatedSources:o,url:i,goal:a}=e,c=(o??[]).map((p)=>`
|
|
1147
1146
|
--- ${p.path} ---
|
|
1148
1147
|
${p.source}
|
|
1149
1148
|
--- end ${p.path} ---`).join(`
|
|
@@ -1220,82 +1219,82 @@ A JSON object with three keys:
|
|
|
1220
1219
|
chain (e.g. ledger-field on a contract-state read).
|
|
1221
1220
|
- description: one short sentence summarising what this suite verifies.
|
|
1222
1221
|
|
|
1223
|
-
${
|
|
1222
|
+
${Il}
|
|
1224
1223
|
|
|
1225
|
-
Now produce the JSON.`}function
|
|
1226
|
-
`)}var
|
|
1224
|
+
Now produce the JSON.`}function di(e){let{name:t,circuits:r,witnesses:n}=e,s=[`Contract: ${t}`];if(r.length>0){s.push("","Circuits:");for(let o of r){let i=o.arguments.length===0?"()":"("+o.arguments.map((a)=>`${a.name}: ${a.type["type-name"]}`).join(", ")+")";s.push(` ${o.pure?"pure ":"impure"} ${o.name}${i}`)}}if(n.length>0){s.push("","Witnesses:");for(let o of n){let i=o.arguments.length===0?"()":"("+o.arguments.map((a)=>`${a.name}: ${a.type["type-name"]}`).join(", ")+")";s.push(` ${o.name}${i}`)}}return s.join(`
|
|
1225
|
+
`)}var $l="```json",Il;var Pl=E(()=>{Il=`Output rules:
|
|
1227
1226
|
- Reply with EXACTLY one ${"```json"} ... \`\`\` fenced code block.
|
|
1228
1227
|
- Inside the fence: valid JSON, nothing else (no comments, no trailing text).
|
|
1229
1228
|
- Fields you don't know about: omit them. Don't invent fields.
|
|
1230
1229
|
- Use only the circuit / ledger field names that appear in the inputs below.
|
|
1231
|
-
- Be concise — fewer, well-named actions beat many vague ones.`});var zl={};W(zl,{analyzeWitnessDependencies:()=>Zr});function Zr(e,t){if(t.length===0)return{byCircuit:new Map};let r=by(e),n=vy(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,u]of n){o.set(d,new Set),i.set(d,new Set);for(let p of Cy(u.body,u.argNames))if(s.has(p))o.get(d).add(p);else if(n.has(p))i.get(d).add(p)}let a=!0;while(a){a=!1;for(let[d,u]of i){let p=o.get(d);for(let f of u)for(let g of o.get(f)??[])if(!p.has(g))p.add(g),a=!0}}let c=new Map;for(let[d,u]of n){if(!u.isCircuit)continue;let p=o.get(d);if(p&&p.size>0)c.set(d,[...p].sort())}return{byCircuit:c}}function by(e){return e.replace(Sy,"").replace(yy,"")}function vy(e){let t=new Map,r=/\b(circuit|function)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gms,n;while((n=r.exec(e))!==null){let s=n[1],o=n[2],i=n[3],a=n.index+n[0].length,c=e.indexOf("{",a);if(c<0)continue;let d=1,u=c+1;for(;u<e.length&&d>0;u++){let g=e[u];if(g==="{")d++;else if(g==="}")d--}if(d!==0)continue;let p=e.slice(c+1,u-1),f=ky(i);t.set(o,{body:p,argNames:f,isCircuit:s==="circuit"})}return t}function ky(e){let t=new Set;for(let r of e.split(",")){let n=r.trim();if(!n)continue;let s=n.indexOf(":"),o=s>-1?n.slice(0,s).trim():n;if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))t.add(o)}return t}function Cy(e,t){let r=new Set,n=/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g,s;while((s=n.exec(e))!==null){let o=s[1];if(Ay.has(o)||t.has(o))continue;r.add(o)}return r}var yy,Sy,Ay;var Ns=x(()=>{yy=/\/\/[^\n]*/g,Sy=/\/\*[\s\S]*?\*\//g;Ay=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var su={};W(su,{claudeSubprocessRunner:()=>Ji,findContractSourcePath:()=>Vi,generateCliScaffoldWithAI:()=>My,generateUiScaffoldWithAI:()=>Fy,isClaudeAvailable:()=>Iy});import{execFileSync as Ey,spawn as xy}from"node:child_process";import{existsSync as Ki,readdirSync as Ty,readFileSync as Yl}from"node:fs";import{dirname as hr,join as Rs}from"node:path";function Iy(){try{return Ey("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function tu(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${Hl} ... \`\`\` fenced block. First 200 chars: ${e.slice(0,200)}`);try{return JSON.parse(r[1])}catch(n){let s=n instanceof Error?n.message:String(n);throw Error(`JSON inside the fence failed to parse: ${s}`)}}function _y(e,t){if(!e||typeof e!=="object")throw Error("AI response must be an object");if(typeof e.description!=="string"||!e.description)throw Error("AI response missing string `description`");if(!e.assertions||!Array.isArray(e.assertions.post))throw Error("AI response missing `assertions.post` array");let r=Py(e);if(!r)throw Error("AI response missing actions — expected either `actions: [...]` (top-level array) "+"or `actions: { actions: [...] }` (wrapped). Got: "+JSON.stringify(e.actions??null).slice(0,200));let n=new Map(t.circuits.map((s)=>[s.name,s]));for(let s of r){if(s.type!=="contract-call"||!s.circuit)continue;let o=n.get(s.circuit);if(!o)throw Error(`AI response references unknown circuit "${s.circuit}". Valid circuits: ${[...n.keys()].join(", ")||"(none)"}`);Dy(s,o)}return{actions:r}}function Dy(e,t){if(t.arguments.length===0)return;let r=e.args??{};for(let n of t.arguments){let s=r[n.name];if(s===void 0)throw Error(`Action "${e.id}" (circuit ${t.name}) is missing required arg "${n.name}" of type ${n.type["type-name"]}. Declared args: ${t.arguments.map((i)=>`${i.name}: ${i.type["type-name"]}`).join(", ")}`);let o=n.type["type-name"];if((o==="Struct"||o==="Alias")&&(s===null||typeof s!=="object"||Array.isArray(s)))throw Error(`Action "${e.id}" (circuit ${t.name}) arg "${n.name}" must be an object for ${o} type; got ${s===null?"null":typeof s}. Read the contract source to find the inner field names.`)}}function Py(e){if(Array.isArray(e.actions))return e.actions;let t=e.actions;if(t&&Array.isArray(t.actions))return t.actions;return null}function Oy(e){if(!e||typeof e!=="object")throw Error("AI response must be an object");if(typeof e.description!=="string"||!e.description)throw Error("AI response missing string `description`");if(typeof e.prompt!=="string"||!e.prompt.trim())throw Error("AI response missing non-empty `prompt`");if(!e.assertions||!Array.isArray(e.assertions.post))throw Error("AI response missing `assertions.post` array")}async function My(e,t=Ji){let r=e.contractSourcePath&&Ki(e.contractSourcePath)?Yl(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?Zr(r,n).byCircuit:new Map,o=e.targetCircuit?Ts(e.targetCircuit):void 0,i=Kl({contractName:e.contract.name,contractSummary:Gi({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),contractSource:r,targetCircuit:e.targetCircuit,startingArgs:o,witnessDependentCircuits:s,goal:e.goal}),a=await t(i),c=tu(a),d=_y(c,e.contract),u=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${nu(e.goal)??"ai"}`),p=e.network??Zl,f=e.servePort??Ql,g={name:e.contract.name,network:p,prep:eu},h={name:u,description:c.description,strategy:"cli",timeout:Ny},m=Ly(c.assertions,f),w=[...s.entries()].filter(([y])=>y!==e.targetCircuit?.name).map(([y,S])=>({name:y,reason:`uses witness ${S.join(", ")} (private state — UI-only)`}));return{dappConfig:g,suite:h,actions:d,assertions:m,prompt:null,suiteName:u,excludedCircuits:w.length>0?w:void 0}}async function Fy(e,t=Ji){let r=e.screen?Yl(e.screen.path,"utf-8"):void 0,n=Jl({contractName:e.contract.name,contractSummary:Gi({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),screenComponent:e.screen?.component,screenSource:r,relatedSources:e.relatedSources,url:e.url,goal:e.goal}),s=await t(n),o=tu(s);Oy(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${nu(e.goal)??"ai"}`),a=e.network??Zl,c=e.servePort??Ql,d=e.url,u={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:$y};if(e.buildDir)u.buildDir=e.buildDir;let p={name:i,description:o.description,strategy:"browser",timeout:Ry,...e.browserMode?{browserMode:e.browserMode}:{}},f=Uy(o.assertions,c);return{dappConfig:u,suite:p,actions:null,assertions:f,prompt:o.prompt,suiteName:i}}function ru(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function Ly(e,t){if(e.post.some((n)=>n.type==="port-listening"&&ru(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function Uy(e,t){let r=e.post;if(!r.some((i)=>i.type==="process-exit-code"))r=[...r,{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"}];if(!r.some((i)=>i.type==="port-listening"&&ru(i)===t))r=[...r,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}];if(!r.some((i)=>i.type==="agent-report-no-failure"))r=[...r,{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}];return{...e,post:r}}function nu(e){if(!e)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32);return t.length>=2?t:void 0}function Vi(e){let t=e.split("/").pop(),r=[hr(e),Rs(hr(e),"src"),hr(hr(e)),Rs(hr(hr(e)),"src")];for(let n of r){if(!Ki(n))continue;if(t){let i=Rs(n,`${t}.compact`);if(Ki(i))return i}let s;try{s=Ty(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return Rs(n,o)}return}var Zl="undeployed",Ql=9932,Ny=300,Ry=600,eu,$y,ql=300000,Xl=4194304,Ji=(e)=>new Promise((t,r)=>{let n=xy("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${ql/1000}s`))},ql);n.stdout?.on("data",(d)=>{if(i+=d.length,i>Xl){a=!0,n.kill("SIGTERM");return}s+=d.toString()}),n.stderr?.on("data",(d)=>{o+=d.toString()}),n.on("error",(d)=>{if(clearTimeout(c),d.code==="ENOENT"){r(Error("claude CLI not found on PATH. Install Claude Code (npm install -g @anthropic-ai/claude-code) or run mn test create without --goal / --screen for the deterministic scaffolder."));return}r(d)}),n.on("exit",(d,u)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${Xl/1024/1024}MB; aborted.`));return}if(u==="SIGTERM")return;if(d!==0){let p=o.trim().slice(0,300)||`(no stderr; exit ${d})`;r(Error(`claude --print exited with code ${d}: ${p}`));return}t(s)}),n.stdin?.write(e),n.stdin?.end()});var zi=x(()=>{Vl();ji();Ns();eu=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],$y=[...eu,"build-and-serve"]});var du={};W(du,{diffState:()=>qy,runActions:()=>By});import{existsSync as ou,readFileSync as iu,writeFileSync as jy,mkdirSync as Wy}from"node:fs";import{join as au}from"node:path";async function By(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:u}=e,p=[],f=r.network??"undeployed",g;if(!a)g=Xy(n,s,f);let{info:h}=At(n),m=zy(h),w;for(let y of t){c?.(y);let S=Date.now();if(w&&(y.type==="contract-call"||y.type==="contract-state")){let b={id:y.id,type:y.type,status:"skip",duration:0,message:`cascaded skip — depends on ${w}`};p.push(b),d?.(y,b);continue}try{let b=await Hy(y,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:g,witnessDeps:m,onMessage:u});if(b.contractAddress){if(g=b.contractAddress,Yy(n,s,f,g),y.type==="contract-deploy")w=void 0}let v=Date.now()-S,R={...b,duration:v};if(p.push(R),d?.(y,R),b.status==="skip"&&y.type==="contract-call")w=`skipped action "${y.id}"`}catch(b){let v=Date.now()-S,R={id:y.id,type:y.type,status:"fail",duration:v,message:b.message};p.push(R),d?.(y,R);break}}return p}async function Hy(e,t){switch(e.type){case"contract-deploy":return Gy(e,t);case"contract-call":return Ky(e,t);case"contract-state":return Jy(e,t);case"wallet-cmd":return Vy(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function Gy(e,t){if(t.contractAddress)return{id:e.id,type:e.type,status:"pass",duration:0,contractAddress:t.contractAddress,message:`Reusing cached contract ${t.contractAddress.slice(0,16)}...`};let r=await Ii({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,servePort:t.servePort,onMessage:t.onMessage});return{id:e.id,type:e.type,status:"pass",duration:0,contractAddress:r.contractAddress,message:`Deployed at ${r.contractAddress.slice(0,16)}...`}}async function Ky(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);if(!e.circuit)throw Error(`Action "${e.id}": missing circuit name.`);let r=t.witnessDeps.get(e.circuit);if(r&&r.length>0)return{id:e.id,type:e.type,status:"skip",duration:0,message:"not CLI-testable — circuit reads private state via witness "+`${r.join(", ")}. Cover with mn test create --strategy ui.`};let n;try{n=await zr({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:()=>{}})}catch{}let s=e.args?Object.values(e.args):[];await _i({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,circuit:e.circuit,args:s,servePort:t.servePort,onMessage:t.onMessage});let o;try{o=await zr({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:()=>{}})}catch{}return{id:e.id,type:e.type,status:"pass",duration:0,message:`${e.circuit} called`,stateBefore:n,stateAfter:o}}async function Jy(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await zr({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:t.onMessage});if(e.assert){let n=[];for(let[s,o]of Object.entries(e.assert)){let i=r.fields[s];if(i===void 0){let a=r.maps[s];if(a)qi(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);qi(s,a,o,n)}catch{qi(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1230
|
+
- Be concise — fewer, well-named actions beat many vague ones.`});function dr(e,t){if(t.length===0)return{byCircuit:new Map};let r=Hw(e),n=Gw(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,u]of n){o.set(d,new Set),i.set(d,new Set);for(let p of Jw(u.body,u.argNames))if(s.has(p))o.get(d).add(p);else if(n.has(p))i.get(d).add(p)}let a=!0;while(a){a=!1;for(let[d,u]of i){let p=o.get(d);for(let f of u)for(let g of o.get(f)??[])if(!p.has(g))p.add(g),a=!0}}let c=new Map;for(let[d,u]of n){if(!u.isCircuit)continue;let p=o.get(d);if(p&&p.size>0)c.set(d,[...p].sort())}return{byCircuit:c}}function Hw(e){return e.replace(Bw,"").replace(Ww,"")}function Gw(e){let t=new Map,r=/\b(circuit|function)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gms,n;while((n=r.exec(e))!==null){let s=n[1],o=n[2],i=n[3],a=n.index+n[0].length,c=e.indexOf("{",a);if(c<0)continue;let d=1,u=c+1;for(;u<e.length&&d>0;u++){let g=e[u];if(g==="{")d++;else if(g==="}")d--}if(d!==0)continue;let p=e.slice(c+1,u-1),f=Kw(i);t.set(o,{body:p,argNames:f,isCircuit:s==="circuit"})}return t}function Kw(e){let t=new Set;for(let r of e.split(",")){let n=r.trim();if(!n)continue;let s=n.indexOf(":"),o=s>-1?n.slice(0,s).trim():n;if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))t.add(o)}return t}function Jw(e,t){let r=new Set,n=/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g,s;while((s=n.exec(e))!==null){let o=s[1];if(Vw.has(o)||t.has(o))continue;r.add(o)}return r}var Ww,Bw,Vw;var Ss=E(()=>{Ww=/\/\/[^\n]*/g,Bw=/\/\*[\s\S]*?\*\//g;Vw=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var Gl={};fe(Gl,{claudeSubprocessRunner:()=>ui,findContractSourcePath:()=>pi,generateCliScaffoldWithAI:()=>oy,generateUiScaffoldWithAI:()=>iy,isClaudeAvailable:()=>ey});import{execFileSync as zw,spawn as qw}from"node:child_process";import{existsSync as li,readdirSync as Xw,readFileSync as Fl}from"node:fs";import{dirname as lr,join as bs}from"node:path";function ey(){try{return zw("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function Wl(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${$l} ... \`\`\` fenced block. First 200 chars: ${e.slice(0,200)}`);try{return JSON.parse(r[1])}catch(n){let s=n instanceof Error?n.message:String(n);throw Error(`JSON inside the fence failed to parse: ${s}`)}}function ty(e,t){if(!e||typeof e!=="object")throw Error("AI response must be an object");if(typeof e.description!=="string"||!e.description)throw Error("AI response missing string `description`");if(!e.assertions||!Array.isArray(e.assertions.post))throw Error("AI response missing `assertions.post` array");let r=ny(e);if(!r)throw Error("AI response missing actions — expected either `actions: [...]` (top-level array) "+"or `actions: { actions: [...] }` (wrapped). Got: "+JSON.stringify(e.actions??null).slice(0,200));let n=new Map(t.circuits.map((s)=>[s.name,s]));for(let s of r){if(s.type!=="contract-call"||!s.circuit)continue;let o=n.get(s.circuit);if(!o)throw Error(`AI response references unknown circuit "${s.circuit}". Valid circuits: ${[...n.keys()].join(", ")||"(none)"}`);ry(s,o)}return{actions:r}}function ry(e,t){if(t.arguments.length===0)return;let r=e.args??{};for(let n of t.arguments){let s=r[n.name];if(s===void 0)throw Error(`Action "${e.id}" (circuit ${t.name}) is missing required arg "${n.name}" of type ${n.type["type-name"]}. Declared args: ${t.arguments.map((i)=>`${i.name}: ${i.type["type-name"]}`).join(", ")}`);let o=n.type["type-name"];if((o==="Struct"||o==="Alias")&&(s===null||typeof s!=="object"||Array.isArray(s)))throw Error(`Action "${e.id}" (circuit ${t.name}) arg "${n.name}" must be an object for ${o} type; got ${s===null?"null":typeof s}. Read the contract source to find the inner field names.`)}}function ny(e){if(Array.isArray(e.actions))return e.actions;let t=e.actions;if(t&&Array.isArray(t.actions))return t.actions;return null}function sy(e){if(!e||typeof e!=="object")throw Error("AI response must be an object");if(typeof e.description!=="string"||!e.description)throw Error("AI response missing string `description`");if(typeof e.prompt!=="string"||!e.prompt.trim())throw Error("AI response missing non-empty `prompt`");if(!e.assertions||!Array.isArray(e.assertions.post))throw Error("AI response missing `assertions.post` array")}async function oy(e,t=ui){let r=e.contractSourcePath&&li(e.contractSourcePath)?Fl(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?dr(r,n).byCircuit:new Map,o=e.targetCircuit?ri(e.targetCircuit):void 0,i=_l({contractName:e.contract.name,contractSummary:di({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),contractSource:r,targetCircuit:e.targetCircuit,startingArgs:o,witnessDependentCircuits:s,goal:e.goal}),a=await t(i),c=Wl(a),d=ty(c,e.contract),u=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${Hl(e.goal)??"ai"}`),p=e.network??Ll,f=e.servePort??Ul,g={name:e.contract.name,network:p,prep:jl},h={name:u,description:c.description,strategy:"cli",timeout:Yw},m=ay(c.assertions,f),w=[...s.entries()].filter(([y])=>y!==e.targetCircuit?.name).map(([y,S])=>({name:y,reason:`uses witness ${S.join(", ")} (private state — UI-only)`}));return{dappConfig:g,suite:h,actions:d,assertions:m,prompt:null,suiteName:u,excludedCircuits:w.length>0?w:void 0}}async function iy(e,t=ui){let r=e.screen?Fl(e.screen.path,"utf-8"):void 0,n=Dl({contractName:e.contract.name,contractSummary:di({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),screenComponent:e.screen?.component,screenSource:r,relatedSources:e.relatedSources,url:e.url,goal:e.goal}),s=await t(n),o=Wl(s);sy(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${Hl(e.goal)??"ai"}`),a=e.network??Ll,c=e.servePort??Ul,d=e.url,u={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:Qw};if(e.buildDir)u.buildDir=e.buildDir;let p={name:i,description:o.description,strategy:"browser",timeout:Zw,...e.browserMode?{browserMode:e.browserMode}:{}},f=cy(o.assertions,c);return{dappConfig:u,suite:p,actions:null,assertions:f,prompt:o.prompt,suiteName:i}}function Bl(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function ay(e,t){if(e.post.some((n)=>n.type==="port-listening"&&Bl(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function cy(e,t){let r=e.post;if(!r.some((i)=>i.type==="process-exit-code"))r=[...r,{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"}];if(!r.some((i)=>i.type==="port-listening"&&Bl(i)===t))r=[...r,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}];if(!r.some((i)=>i.type==="agent-report-no-failure"))r=[...r,{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}];return{...e,post:r}}function Hl(e){if(!e)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32);return t.length>=2?t:void 0}function pi(e){let t=e.split("/").pop(),r=[lr(e),bs(lr(e),"src"),lr(lr(e)),bs(lr(lr(e)),"src")];for(let n of r){if(!li(n))continue;if(t){let i=bs(n,`${t}.compact`);if(li(i))return i}let s;try{s=Xw(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return bs(n,o)}return}var Ll="undeployed",Ul=9932,Yw=300,Zw=600,jl,Qw,Ol=300000,Ml=4194304,ui=(e)=>new Promise((t,r)=>{let n=qw("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${Ol/1000}s`))},Ol);n.stdout?.on("data",(d)=>{if(i+=d.length,i>Ml){a=!0,n.kill("SIGTERM");return}s+=d.toString()}),n.stderr?.on("data",(d)=>{o+=d.toString()}),n.on("error",(d)=>{if(clearTimeout(c),d.code==="ENOENT"){r(Error("claude CLI not found on PATH. Install Claude Code (npm install -g @anthropic-ai/claude-code) or run mn test create without --goal / --screen for the deterministic scaffolder."));return}r(d)}),n.on("exit",(d,u)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${Ml/1024/1024}MB; aborted.`));return}if(u==="SIGTERM")return;if(d!==0){let p=o.trim().slice(0,300)||`(no stderr; exit ${d})`;r(Error(`claude --print exited with code ${d}: ${p}`));return}t(s)}),n.stdin?.write(e),n.stdin?.end()});var mi=E(()=>{Pl();si();Ss();jl=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Qw=[...jl,"build-and-serve"]});import{existsSync as Kl,readFileSync as Jl,writeFileSync as dy,mkdirSync as ly}from"node:fs";import{join as Vl}from"node:path";async function zl(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:u}=e,p=[],f=r.network??"undeployed",g;if(!a)g=wy(n,s,f);let{info:h}=qe(n),m=hy(h),w;for(let y of t){c?.(y);let S=Date.now();if(w&&(y.type==="contract-call"||y.type==="contract-state")){let b={id:y.id,type:y.type,status:"skip",duration:0,message:`cascaded skip — depends on ${w}`};p.push(b),d?.(y,b);continue}try{let b=await uy(y,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:g,witnessDeps:m,onMessage:u});if(b.contractAddress){if(g=b.contractAddress,yy(n,s,f,g),y.type==="contract-deploy")w=void 0}let v=Date.now()-S,R={...b,duration:v};if(p.push(R),d?.(y,R),b.status==="skip"&&y.type==="contract-call")w=`skipped action "${y.id}"`}catch(b){let v=Date.now()-S,R={id:y.id,type:y.type,status:"fail",duration:v,message:b.message};p.push(R),d?.(y,R);break}}return p}async function uy(e,t){switch(e.type){case"contract-deploy":return py(e,t);case"contract-call":return my(e,t);case"contract-state":return fy(e,t);case"wallet-cmd":return gy(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function py(e,t){if(t.contractAddress)return{id:e.id,type:e.type,status:"pass",duration:0,contractAddress:t.contractAddress,message:`Reusing cached contract ${t.contractAddress.slice(0,16)}...`};let r=await us({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,servePort:t.servePort,onMessage:t.onMessage});return{id:e.id,type:e.type,status:"pass",duration:0,contractAddress:r.contractAddress,message:`Deployed at ${r.contractAddress.slice(0,16)}...`}}async function my(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);if(!e.circuit)throw Error(`Action "${e.id}": missing circuit name.`);let r=t.witnessDeps.get(e.circuit);if(r&&r.length>0)return{id:e.id,type:e.type,status:"skip",duration:0,message:"not CLI-testable — circuit reads private state via witness "+`${r.join(", ")}. Cover with mn test create --strategy ui.`};let n;try{n=await or({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:()=>{}})}catch{}let s=e.args?Object.values(e.args):[];await ps({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,circuit:e.circuit,args:s,servePort:t.servePort,onMessage:t.onMessage});let o;try{o=await or({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:()=>{}})}catch{}return{id:e.id,type:e.type,status:"pass",duration:0,message:`${e.circuit} called`,stateBefore:n,stateAfter:o}}async function fy(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await or({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:t.onMessage});if(e.assert){let n=[];for(let[s,o]of Object.entries(e.assert)){let i=r.fields[s];if(i===void 0){let a=r.maps[s];if(a)fi(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);fi(s,a,o,n)}catch{fi(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1232
1231
|
${n.join(`
|
|
1233
|
-
`)}`)}return{id:e.id,type:e.type,status:"pass",duration:0,message:`State checked (${Object.keys(r.fields).length} fields, ${Object.keys(r.maps).length} maps)`,stateAfter:r}}function
|
|
1234
|
-
`)}var
|
|
1232
|
+
`)}`)}return{id:e.id,type:e.type,status:"pass",duration:0,message:`State checked (${Object.keys(r.fields).length} fields, ${Object.keys(r.maps).length} maps)`,stateAfter:r}}function fi(e,t,r,n){for(let[s,o]of Object.entries(r)){let i=typeof o==="number"?BigInt(o):o;if(typeof t==="bigint"&&(typeof i==="bigint"||typeof i==="number")){let a=BigInt(i);switch(s){case">":if(!(t>a))n.push(`${e}: expected > ${a}, got ${t}`);break;case">=":if(!(t>=a))n.push(`${e}: expected >= ${a}, got ${t}`);break;case"<":if(!(t<a))n.push(`${e}: expected < ${a}, got ${t}`);break;case"<=":if(!(t<=a))n.push(`${e}: expected <= ${a}, got ${t}`);break;case"==":if(t!==a)n.push(`${e}: expected == ${a}, got ${t}`);break;case"!=":if(t===a)n.push(`${e}: expected != ${a}, got ${t}`);break;default:n.push(`${e}: unknown operator "${s}"`)}}else{let a=String(i);switch(s){case"==":if(t!==a)n.push(`${e}: expected == "${a}", got "${t}"`);break;case"!=":if(t===a)n.push(`${e}: expected != "${a}", got "${t}"`);break;default:n.push(`${e}: operator "${s}" not supported for string values`)}}}}async function gy(e,t){return{id:e.id,type:e.type,status:"pass",duration:0,message:`wallet-cmd: ${e.cmd??"no command"} (not yet implemented)`}}function hy(e){if(e.witnesses.length===0)return new Map;let t=pi(e.managedDir);if(!t||!Kl(t))return new Map;let r=Jl(t,"utf-8"),n=e.witnesses.map((s)=>s.name);return dr(r,n).byCircuit}function ql(e,t){if(!e||!t)return[];let r=[],n=new Set([...Object.keys(e.fields),...Object.keys(t.fields)]);for(let o of n){let i=e.fields[o]??"(absent)",a=t.fields[o]??"(absent)";if(i!==a)r.push({field:o,before:i,after:a})}let s=new Set([...Object.keys(e.maps),...Object.keys(t.maps)]);for(let o of s){let i=e.maps[o]?.size??"0",a=t.maps[o]?.size??"0";if(i!==a)r.push({field:`${o} (entries)`,before:i,after:a})}return r}function Xl(e,t){return Vl(e,"tests","results",`.contract-cache-${t}.json`)}function wy(e,t,r){let n=Xl(e,t);if(!Kl(n))return;try{let s=JSON.parse(Jl(n,"utf-8"));if(s.network!==r)return;return s.address}catch{return}}function yy(e,t,r,n){let s=Xl(e,t);ly(Vl(e,"tests","results"),{recursive:!0});let o={address:n,network:r,timestamp:new Date().toISOString()};dy(s,JSON.stringify(o,null,2)+`
|
|
1233
|
+
`)}var Yl=E(()=>{qr();Jr();Ss();mi()});var tu={};fe(tu,{default:()=>vs});import{join as Zl}from"node:path";import{mkdirSync as Sy}from"node:fs";function by(e){return Ql.includes(e)}async function vs(e,t){let r=e.subcommand;if(!r||!by(r))throw new Z(`Usage: midnight test <${Ql.join("|")}>
|
|
1235
1234
|
|
|
1236
1235
|
create Generate dapp.test.json + a CLI test suite from the contract
|
|
1237
1236
|
run Run test suites for the current dApp
|
|
1238
1237
|
list List available test suites
|
|
1239
1238
|
results Show latest test results
|
|
1240
1239
|
|
|
1241
|
-
Run from the root of a dApp project containing dapp.test.json.`);let n=N(e,"json");switch(r){case"create":return
|
|
1242
|
-
`+
|
|
1240
|
+
Run from the root of a dApp project containing dapp.test.json.`);let n=N(e,"json");switch(r){case"create":return xy(e,n);case"run":return Ry(e,n,t);case"list":return $y(n);case"results":return Iy(e,n)}}function vy(e){let t=(e??"").toLowerCase();if(t==="")return;if(t==="cli"||t==="browser")return t;if(t==="ui")return"browser";throw new Z(`Unknown strategy "${e}". Use "cli" or "ui".`)}function ky(e){return e==="preprod"||e==="preview"||e==="undeployed"?e:void 0}function Cy(e){let t={},r=A(e,"port");if(r!==void 0){let a=parseInt(r,10);if(!Number.isFinite(a)||a<=0||a>65535)throw new Z(`Invalid --port "${r}" — must be 1–65535.`);t.port=a}let n=A(e,"build-cmd");if(n!==void 0)t.buildCmd=n;let s=A(e,"build-dir");if(s!==void 0)t.buildDir=s;let o=A(e,"url");if(o!==void 0)t.url=o;let i=A(e,"browser-mode");if(i!==void 0){if(i!=="dom"&&i!=="vision"&&i!=="script"&&i!=="auto")throw new Z(`Invalid --browser-mode "${i}" — must be dom, vision, or script.`);t.browserMode=i}return t}function Ay(e){if(e.port===void 0||e.buildCmd===void 0)throw new Z("Browser strategy needs --port and --build-cmd (and optionally --build-dir, --url) when running non-interactively.");return{port:e.port,buildCmd:e.buildCmd,buildDir:e.buildDir,url:e.url}}async function xy(e,t){let{resolve:r}=await import("node:path");await Promise.resolve().then(() => Jr());await Promise.resolve().then(() => si());await Promise.resolve().then(() => wl());let i=await Promise.resolve().then(() => (Rl(),{}));await Promise.resolve();let m=await Promise.resolve().then(() => (mi(),Gl));await Promise.resolve().then(() => ii());let y=r(A(e,"path")??process.cwd()),S=A(e,"name"),b=A(e,"suite"),v=ky(A(e,"network")),R=N(e,"force"),P=!t&&Al(),q=A(e,"goal"),U=A(e,"screen"),X=N(e,"no-ai"),F=vy(A(e,"strategy"))??(P?await xl():"cli"),Q;if(F==="browser"){let j=Cy(e);Q=P?await El(j):Ay(j)}let{info:de}=qe(y,S),I=!X&&m.isClaudeAvailable(),x=!X&&(q!==void 0||U!==void 0||P&&I),T=x?await Ey({strategy:F,info:de,dappDir:y,browser:Q,network:v,suiteName:b,goalFlag:q,screenFlag:U,interactive:P,jsonMode:t,ai:m,promptCircuit:Tl,promptScreen:ai,promptGoal:Nl,promptSuiteName:ci,discoverScreens:vl})??ni(de.circuits,{contractName:de.name,suiteName:b,strategy:F,browser:Q,network:v}):ni(de.circuits,{contractName:de.name,suiteName:b,strategy:F,browser:Q,network:v});if(P&&!b){let j=await ci(T.suiteName);if(j!==T.suiteName)T.suiteName=j,T.suite.name=j}let _=hl(T,{dappDir:y,force:R});if(t){D({subcommand:"create",contractName:de.name,suiteName:T.suiteName,strategy:F,aiAssisted:x&&T.suiteName!=="cli-default"&&T.suiteName!=="ui-default",written:_.written,excludedCircuits:T.excludedCircuits});return}process.stderr.write(`
|
|
1241
|
+
`+W(`Test scaffold: ${de.name}`)+`
|
|
1243
1242
|
|
|
1244
|
-
`);for(let j of _.written)process.stderr.write(` ${
|
|
1245
|
-
`);let
|
|
1243
|
+
`);for(let j of _.written)process.stderr.write(` ${H("✓")} ${j}
|
|
1244
|
+
`);let K=F==="browser"?{file:"prompt.md",hint:"verify the UI steps match your dApp — exact button labels, expected screens, success criteria. Claude follows these literally."}:{file:"actions.json",hint:'review args — placeholder values like 0 may violate contract assertions (e.g. "amount > 0").'};if(T.excludedCircuits&&T.excludedCircuits.length>0){process.stderr.write(`
|
|
1246
1245
|
`+l(" Skipped (not CLI-testable):")+`
|
|
1247
1246
|
`);for(let j of T.excludedCircuits)process.stderr.write(` ${M("!")} ${j.name} ${l("— "+j.reason)}
|
|
1248
1247
|
`);process.stderr.write(l(` These need the dApp UI to populate private state first.
|
|
1249
1248
|
`)),process.stderr.write(l(` Cover them with a browser-strategy suite (mn test create --strategy ui).
|
|
1250
1249
|
`))}process.stderr.write(`
|
|
1251
1250
|
`+l(" Next:")+`
|
|
1252
|
-
`),process.stderr.write(l(" Edit ")+L(`tests/suites/${T.suiteName}/${
|
|
1253
|
-
`),process.stderr.write(l(" ")+l(
|
|
1251
|
+
`),process.stderr.write(l(" Edit ")+L(`tests/suites/${T.suiteName}/${K.file}`)+`
|
|
1252
|
+
`),process.stderr.write(l(" ")+l(K.hint)+`
|
|
1254
1253
|
`),process.stderr.write(l(" Run ")+L(`mn test run --suite ${T.suiteName}`)+`
|
|
1255
1254
|
`),process.stderr.write(l(" List ")+L("mn test list")+l(" (see every suite in this project)")+`
|
|
1256
1255
|
|
|
1257
|
-
`)}async function
|
|
1256
|
+
`)}async function Ey(e){try{if(!e.ai.isClaudeAvailable())return null;let t=e.goalFlag??(e.interactive?await e.promptGoal():void 0);if(e.strategy==="cli")return await Ty(e,t);return await Ny(e,t)}catch(t){return process.stderr.write(`
|
|
1258
1257
|
${l("AI scaffold failed, falling back to deterministic:")} ${t.message}
|
|
1259
|
-
`),null}}async function
|
|
1258
|
+
`),null}}async function eu(e,t,r){if(!r)return t();let n=G(e);try{let s=await t();return n.stop(),s}catch(s){throw n.fail("AI scaffold failed"),s}}async function Ty(e,t){let r=e.interactive?await e.promptCircuit(e.info.circuits):e.info.circuits.find((s)=>!s.pure);if(!r&&!t)return null;let n=e.ai.findContractSourcePath(e.info.managedDir);if(r&&n&&e.interactive){let{readFileSync:s}=await import("node:fs");await Promise.resolve().then(() => Ss());let i=s(n,"utf-8"),a=e.info.witnesses.map((u)=>u.name),d=dr(i,a).byCircuit.get(r.name);if(d&&d.length>0)process.stderr.write(`
|
|
1260
1259
|
`+M("!")+` ${r.name} calls ${d.join(", ")} — a witness that reads private state.
|
|
1261
1260
|
`),process.stderr.write(l(` The CLI suite will deploy + run, but expect a "Cannot read properties of undefined" failure
|
|
1262
1261
|
`)+l(` unless the dApp UI populates that state first. Consider --strategy ui instead.
|
|
1263
|
-
`))}return
|
|
1264
|
-
`+
|
|
1262
|
+
`))}return eu("Asking Claude to scaffold the test suite (30–60s)...",()=>e.ai.generateCliScaffoldWithAI({contract:e.info,contractSourcePath:n,targetCircuit:r,goal:t,network:e.network,suiteName:e.suiteName}),e.interactive&&!e.jsonMode)}async function Ny(e,t){if(!e.browser)return null;let{join:r}=await import("node:path"),n=e.browser.buildDir?r(e.dappDir,e.browser.buildDir):e.dappDir,s=e.discoverScreens(n),o=e.screenFlag?s.find((i)=>i.name===e.screenFlag||i.component===e.screenFlag):e.interactive?await e.promptScreen(s):s[0];if(!o&&!t)return null;return eu("Asking Claude to scaffold the test suite (30–60s)...",()=>e.ai.generateUiScaffoldWithAI({contract:e.info,screen:o,url:e.browser.url??`http://localhost:${e.browser.port}/`,port:e.browser.port,buildCmd:e.browser.buildCmd,buildDir:e.browser.buildDir,browserMode:e.browser.browserMode,goal:t,network:e.network,suiteName:e.suiteName}),e.interactive&&!e.jsonMode)}async function Ry(e,t,r){let{config:n,dappDir:s}=hs(),o=Zo(s),i=A(e,"suite"),a;if(i){if(a=o.find((g)=>g.suite.name===i),!a){let g=o.map((h)=>h.suite.name).join(", ")||"none found";throw new Z(`Suite "${i}" not found. Available: ${g}`)}}else if(o.length>0)a=o[0];Sy(Zl(s,"tests","results"),{recursive:!0});let c=Date.now(),d=new Date().toISOString();if(!t){if(process.stderr.write(`
|
|
1263
|
+
`+W(`E2E Test: ${n.name}`)+`
|
|
1265
1264
|
|
|
1266
1265
|
`),process.stderr.write(C("Network",n.network??"undeployed")+`
|
|
1267
1266
|
`),n.port)process.stderr.write(C("Port",String(n.port))+`
|
|
1268
1267
|
`);if(a){if(process.stderr.write(C("Suite",a.suite.name)+`
|
|
1269
1268
|
`),process.stderr.write(C("Strategy",a.suite.strategy)+`
|
|
1270
|
-
`),a.suite.strategy==="browser"){let g=
|
|
1269
|
+
`),a.suite.strategy==="browser"){let g=Qo(a.suite);process.stderr.write(C("Browser Mode",g)+`
|
|
1271
1270
|
`)}}process.stderr.write(`
|
|
1272
|
-
`)}let u=
|
|
1273
|
-
`)};r?.addEventListener("abort",()=>
|
|
1274
|
-
`));let g=
|
|
1275
|
-
`);let m=0,w="";if(a){let O=a.suite;if(O.strategy==="browser"){let F=
|
|
1271
|
+
`)}let u=Hd(),p=[],f=(g)=>{if(!t)process.stderr.write(l(` [teardown] ${g}`)+`
|
|
1272
|
+
`)};r?.addEventListener("abort",()=>ti(u,f),{once:!0});try{if(!t)process.stderr.write(k(` Prep
|
|
1273
|
+
`));let g=G("Starting prep..."),h=await Yd(n,s,u,{onStepStart(O){g.update(`[prep] ${O}...`)},onStepComplete(O,F,Q,de){if(F==="pass")g.stop(`${H("✓")} ${O} (${_y(Q)})`);else g.stop(`${J("✗")} ${O}: ${de??"failed"}`);g=G("")},onMessage(O){g.update(O)}});if(g.stop(""),p.push(...h),!t)process.stderr.write(`
|
|
1274
|
+
`);let m=0,w="";if(a){let O=a.suite;if(O.strategy==="browser"){let F=Wd(a.suiteDir);if(!F)throw Error(`No prompt.md found in ${a.suiteDir} — required for browser strategy`);if(w=Zl(s,"tests","results",`${O.name}_${d.replace(/[:.]/g,"-")}_claude.log`),!t)process.stderr.write(k(` Browser Test
|
|
1276
1275
|
`)),process.stderr.write(l(` Claude will take over the terminal. Output is also logged.
|
|
1277
1276
|
|
|
1278
|
-
`));let
|
|
1279
|
-
`)}});if(m=
|
|
1280
|
-
`),
|
|
1281
|
-
`);else process.stderr.write(` ${m===0?
|
|
1282
|
-
`)}else if(O.strategy==="cli"){let F=
|
|
1277
|
+
`));let Q=await el({suite:O,prompt:F,dappDir:s,logFile:w,onMessage:(de)=>{if(!t)process.stderr.write(l(` ${de}`)+`
|
|
1278
|
+
`)}});if(m=Q.exitCode,!t)if(process.stderr.write(`
|
|
1279
|
+
`),Q.timedOut)process.stderr.write(` ${J("✗")} Browser test timed out
|
|
1280
|
+
`);else process.stderr.write(` ${m===0?H("✓"):J("✗")} Claude exited with code ${m}
|
|
1281
|
+
`)}else if(O.strategy==="cli"){let F=jd(a.suiteDir);if(!F)throw Error(`No actions.json found in ${a.suiteDir} — required for CLI strategy`);if(!t)process.stderr.write(k(` CLI Test
|
|
1283
1282
|
`)),process.stderr.write(l(` Executing ${F.actions.length} action(s)
|
|
1284
1283
|
|
|
1285
|
-
`));
|
|
1286
|
-
`)}}},onMessage:(
|
|
1287
|
-
`);let
|
|
1288
|
-
`)}u._actionResults=
|
|
1289
|
-
`));let y={processExitCode:m,agentLogPath:w},S=[];if(a){let O=
|
|
1284
|
+
`));await Promise.resolve().then(() => Yl());await Promise.resolve().then(() => pe());let x=n.network??"undeployed",{config:T}=te({args:{command:"test",subcommand:"run",positionals:[],flags:{network:x}}});await Promise.resolve();let K=u.serveHandle?.port??xt,j=N(e,"redeploy"),ee=await zl({actions:F.actions,config:n,dappDir:s,suiteName:O.name,networkConfig:T,servePort:K,redeploy:j,onActionStart:(oe)=>{if(!t){let le=G(`[${oe.id}] ${oe.type}${oe.circuit?` ${oe.circuit}`:""}...`);oe._spinner=le}},onActionComplete:(oe,le)=>{if(!t){let Me=oe._spinner;if(Me)if(le.status==="pass")Me.stop(`${H("✓")} ${oe.id}: ${le.message??"pass"}`);else if(le.status==="skip")Me.stop(`${M("⊘")} ${oe.id}: ${le.message??"skipped"}`);else Me.stop(`${J("✗")} ${oe.id}: ${le.message??"fail"}`);if(le.stateBefore&&le.stateAfter){let Fe=ql(le.stateBefore,le.stateAfter);if(Fe.length>0)for(let Ne of Fe)process.stderr.write(l(` ${Ne.field}: ${Ne.before} → `)+L(Ne.after)+`
|
|
1285
|
+
`)}}},onMessage:(oe)=>{}});if(m=ee.some((oe)=>oe.status==="fail")?1:0,!t){process.stderr.write(`
|
|
1286
|
+
`);let oe=ee.filter((Ne)=>Ne.status==="pass").length,le=ee.filter((Ne)=>Ne.status==="skip").length,Me=ee.filter((Ne)=>Ne.status==="fail").length,Fe=H(String(oe)+" passed");if(le>0)Fe+=`, ${M(String(le)+" skipped")}`;if(Me>0)Fe+=`, ${J(String(Me)+" failed")}`;process.stderr.write(` Actions: ${Fe}
|
|
1287
|
+
`)}u._actionResults=ee}}else if(!t)process.stderr.write(l(` No test suites found — only prep was run
|
|
1288
|
+
`));let y={processExitCode:m,agentLogPath:w},S=[];if(a){let O=Ud(a.suiteDir);if(O&&O.post.length>0){if(!t)process.stderr.write(`
|
|
1290
1289
|
`+k(` Assertions
|
|
1291
|
-
`));if(S=await
|
|
1292
|
-
`)}}}let b=Math.round((Date.now()-c)/1000),v=p.every((O)=>O.status==="pass"),R=S.every((O)=>O.status==="pass"),
|
|
1293
|
-
`+
|
|
1294
|
-
`),process.stderr.write(` ${
|
|
1295
|
-
`),process.stderr.write(l(` Results: ${
|
|
1290
|
+
`));if(S=await rl(O.post,y),!t)for(let F of S){let Q=F.status==="pass"?H("✓"):J("✗"),de=F.message?l(` — ${F.message}`):"";process.stderr.write(` ${Q} ${F.id}${de}
|
|
1291
|
+
`)}}}let b=Math.round((Date.now()-c)/1000),v=p.every((O)=>O.status==="pass"),R=S.every((O)=>O.status==="pass"),P=v&&R&&m===0?"pass":"fail",q=u._actionResults,U={id:`${n.name}_${d}`,dapp:n.name,suite:a?.suite.name??"prep-only",timestamp:d,duration:b,network:n.network??"undeployed",strategy:a?.suite.strategy??"none",model:a?.suite.model,status:P,prep:p,actions:q?.map((O)=>({id:O.id,type:O.type,status:O.status,duration:O.duration,message:O.message,contractAddress:O.contractAddress})),assertions:S,testOutput:w?{exitCode:m,logFile:w}:void 0},X=ol(U,s);if(t)D(U);else process.stderr.write(`
|
|
1292
|
+
`+V()+`
|
|
1293
|
+
`),process.stderr.write(` ${P==="pass"?H(k("PASS")):J(k("FAIL"))} — ${n.name} (${b}s)
|
|
1294
|
+
`),process.stderr.write(l(` Results: ${X}`)+`
|
|
1296
1295
|
|
|
1297
|
-
`);if(
|
|
1298
|
-
`+
|
|
1296
|
+
`);if(P==="fail")process.exitCode=1}finally{await ti(u,f)}}function $y(e){let{config:t,dappDir:r}=hs(),n=Zo(r);if(e){D({dapp:t.name,suites:n.map((s)=>({name:s.suite.name,description:s.suite.description,strategy:s.suite.strategy,timeout:s.suite.timeout}))});return}if(process.stderr.write(`
|
|
1297
|
+
`+W(`Tests: ${t.name}`)+`
|
|
1299
1298
|
|
|
1300
1299
|
`),n.length===0)process.stderr.write(l(` No test suites found.
|
|
1301
1300
|
`)),process.stderr.write(l(` Create tests/suites/<name>/suite.json to add one.
|
|
@@ -1304,40 +1303,40 @@ Run from the root of a dApp project containing dapp.test.json.`);let n=N(e,"json
|
|
|
1304
1303
|
`),process.stderr.write(l(` strategy: ${s.strategy}`)+(s.timeout?l(`, timeout: ${s.timeout}s`):"")+`
|
|
1305
1304
|
|
|
1306
1305
|
`);process.stderr.write(`
|
|
1307
|
-
`)}function
|
|
1308
|
-
`+
|
|
1306
|
+
`)}function Iy(e,t){let{config:r,dappDir:n}=hs(),s=N(e,"all"),o=A(e,"suite"),i=s?ei(n,o):(()=>{let a=il(n,o);return a?[a]:[]})();if(t){D(s?{dapp:r.name,results:i}:i[0]??{});return}if(process.stderr.write(`
|
|
1307
|
+
`+W(`Results: ${r.name}`)+`
|
|
1309
1308
|
|
|
1310
1309
|
`),i.length===0)process.stderr.write(l(` No test results found.
|
|
1311
1310
|
`)),process.stderr.write(l(` Run "midnight test run" to generate results.
|
|
1312
|
-
`));else for(let a of i){let c=a.status==="pass"?
|
|
1311
|
+
`));else for(let a of i){let c=a.status==="pass"?H("✓"):J("✗"),d=a.status==="pass"?H(k("PASS")):J(k("FAIL"));process.stderr.write(` ${c} ${k(a.suite)} — ${d} (${a.duration}s)
|
|
1313
1312
|
`),process.stderr.write(l(` ${a.timestamp} | ${a.network} | ${a.strategy}`)+`
|
|
1314
|
-
`);let u=a.prep.filter((f)=>f.status==="fail");if(u.length>0)process.stderr.write(
|
|
1315
|
-
`);let p=a.assertions.filter((f)=>f.status==="fail");if(p.length>0)process.stderr.write(
|
|
1313
|
+
`);let u=a.prep.filter((f)=>f.status==="fail");if(u.length>0)process.stderr.write(J(` prep: ${u.length} failed`)+`
|
|
1314
|
+
`);let p=a.assertions.filter((f)=>f.status==="fail");if(p.length>0)process.stderr.write(J(` assertions: ${p.length} failed`)+`
|
|
1316
1315
|
`);process.stderr.write(`
|
|
1317
1316
|
`)}process.stderr.write(`
|
|
1318
|
-
`)}function uS(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var pu;var Yi=x(()=>{He();ue();ze();nl();ml();hl();yl();kl();Cl();pu=["run","list","results","create"]});var ES={};import{readFileSync as gu}from"node:fs";import{fileURLToPath as yu}from"node:url";import{Server as pS}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mS}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as fS,CallToolRequestSchema as gS,ListResourcesRequestSchema as hS,ReadResourceRequestSchema as wS}from"@modelcontextprotocol/sdk/types.js";function Se(e,t,r){let n={json:!0},s=[];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;let a=o==="full"?yr:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}async function ne(e){let t=vS[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}function CS(e,t){let r=t.network??"active network",n=t.wallet??"active wallet";switch(e){case"midnight_transfer":return`Send ${t.amount} NIGHT from ${n} to ${t.to} on ${r}`;case"midnight_contract_deploy":{let s=t.args?` with args ${t.args}`:"";return`Deploy contract from ${t.path??"current directory"} as ${n} on ${r}${s}`}case"midnight_contract_call":{let s=t.args?` with args ${t.args}`:"";return`Call circuit ${t.circuit} on contract ${t.address} as ${n} on ${r}${s}`}default:return`Execute ${e} with ${JSON.stringify(t)}`}}function Qi(e){return{...e,_serverVersion:Ge}}async function wu(e,t){let r=vu.find((n)=>n.name===e);if(!r)return Zi(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(Qi(n),null,2)}]}}catch(n){return Zi(n instanceof Error?n:Error(String(n)))}}function Zi(e){let{errorCode:t}=Ar(e);return{content:[{type:"text",text:JSON.stringify(Qi({error:!0,code:t,message:Da(e.message)}))}],isError:!0}}async function AS(){await Ir();let e=new mS;await Qr.connect(e)}var Su="midnight-wallet://skill/core",bu="midnight-wallet://skill/full",yS="midnight-wallet://skill",SS,bS,vS,vu,kS,hu,Qr;var ku=x(()=>{Cn();Ys();Tr();Oa();go();SS=yu(new URL("../docs/SKILL-CORE.md",import.meta.url)),bS=yu(new URL("../docs/SKILL.md",import.meta.url));vS={generate:()=>Promise.resolve().then(() => (wo(),ho)),info:()=>Promise.resolve().then(() => (So(),yo)),balance:()=>Promise.resolve().then(() => (Ko(),Go)),address:()=>Promise.resolve().then(() => (Vo(),Jo)),"genesis-address":()=>Promise.resolve().then(() => (qo(),zo)),"inspect-cost":()=>Promise.resolve().then(() => (Yo(),Xo)),airdrop:()=>Promise.resolve().then(() => (Yn(),Xn)),transfer:()=>Promise.resolve().then(() => (Qo(),Zo)),dust:()=>Promise.resolve().then(() => (Qn(),Zn)),cache:()=>Promise.resolve().then(() => (ti(),ei)),config:()=>Promise.resolve().then(() => (ni(),ri)),localnet:()=>Promise.resolve().then(() => (li(),di)),wallet:()=>Promise.resolve().then(() => (os(),ss)),status:()=>Promise.resolve().then(() => (ud(),ld)),contract:()=>Promise.resolve().then(() => (Cs(),ks)),test:()=>Promise.resolve().then(() => (Yi(),Xi))};vu=[{name:"midnight_wallet_generate",description:"Create wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"64-char hex"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=Se("wallet",e,"generate");if(r.positionals=[t],delete r.flags.name,e.force==="true"||e.force===!0)r.flags.force=!0;let n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_list",description:"List wallets. Default: per-wallet { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the 3-network addresses + shieldedAddresses maps.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Return full per-network addresses + shieldedAddresses maps (the same shape `mn wallet list --json` emits). Default false (slim)."}}},async handler({full:e}={}){let t={json:!0};if(e)t[yr]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_use",description:"Set active wallet.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"use",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_info",description:"Show wallet details. Default: { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the per-network maps + createdAt + file path.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},full:{type:"boolean",description:"Return the full per-network addresses + shieldedAddresses maps and bookkeeping fields (matches `mn wallet info <name> --json`). Default false (slim)."}}},async handler(e){let{name:t,full:r}=e,n={json:!0};if(r)n[yr]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await ne("wallet");return q(o,s)}},{name:"midnight_wallet_remove",description:"Remove wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"remove",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return q(n,r)}},{name:"midnight_info",description:"Wallet metadata.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=Se("info",e),r=await ne("info");return q(r,t)}},{name:"midnight_balance",description:"NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string"},full:{type:"boolean",description:"Include the queried address + shieldedAddress in the response (matches `mn balance --json`). Default false (slim)."}}},async handler(e){let t=e.address,r=Se("balance",e,t);delete r.flags.address;let n=await ne("balance");return q(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64-char hex"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=Se("address",e),r=await ne("address");return q(r,t)}},{name:"midnight_genesis_address",description:"Genesis address.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]}}},async handler(e){let t=Se("genesis-address",e),r=await ne("genesis-address");return q(r,t)}},{name:"midnight_inspect_cost",description:"Block limits.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e=Se("inspect-cost",{}),t=await ne("inspect-cost");return q(t,e)}},{name:"midnight_airdrop",description:'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.',annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{amount:{type:"string",description:"NIGHT"},wallet:{type:"string",description:"Destination: wallet name, JSON path, or bech32m address"},shielded:{type:"string",description:'Set to "true" for shielded airdrop'}},required:["amount"]},async handler(e){let t=e.amount,r=Se("airdrop",e,t);delete r.flags.amount;let n=await ne("airdrop");return q(n,r)}},{name:"midnight_transfer",description:"Send NIGHT (returns pending token; see skill).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{to:{type:"string",description:"bech32m"},amount:{type:"string",description:"NIGHT"},wallet:{type:"string"}},required:["to","amount"]},async handler(e){let{to:t,amount:r}=e,n=Se("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await ne("transfer");return q(s,n)}},{name:"midnight_dust_register",description:"Register for dust.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=Se("dust",e,"register"),r=await ne("dust");return q(r,t)}},{name:"midnight_dust_status",description:"Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},"proof-server":{type:"string"},node:{type:"string"},"indexer-ws":{type:"string"},"no-cache":{type:"string"},full:{type:"boolean",description:"Include sync internals (eventsApplied, ownedUtxos, cached) in the response (matches `mn dust status --json`). Default false (slim)."}}},async handler(e){let t=Se("dust",e,"status"),r=await ne("dust");return q(r,t)}},{name:"midnight_config_get",description:"Read config.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"get",positionals:[e.key],flags:{json:!0}},n=await ne("config");return q(n,r)}},{name:"midnight_config_set",description:"Write config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"},value:{type:"string"}},required:["key","value"]},async handler(e){let{key:t,value:r}=e,n={command:"config",subcommand:"set",positionals:[t,r],flags:{json:!0}},s=await ne("config");return q(s,n)}},{name:"midnight_cache_clear",description:"Clear sync cache.",annotations:{destructiveHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]},wallet:{type:"string"}}},async handler(e){let t=Se("cache",e,"clear"),r=await ne("cache");return q(r,t)}},{name:"midnight_config_unset",description:"Reset config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"unset",positionals:[e.key],flags:{json:!0}},n=await ne("config");return q(n,r)}},{name:"midnight_localnet_up",description:"Start localnet (Docker).",annotations:{openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_stop",description:"Stop localnet (preserves state).",annotations:{idempotentHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"stop",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_down",description:"Localnet teardown (volumes + undeployed cache).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"down",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_status",description:"Localnet status.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"status",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_clean",description:"Remove stray containers.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"clean",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_contract_inspect",description:"Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed/<name>/compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path)"},name:{type:"string",description:"Specific contract name to inspect when the project has multiple (see siblings field)"}}},async handler(e){let t=Se("contract",e,"inspect"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_state",description:"Read the current ledger state of a deployed contract. Returns the ledger fields as a JSON object.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},path:{type:"string",description:"dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address"]},async handler(e){let t=Se("contract",e,"state"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_deploy",description:"Deploy a compiled Compact contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of constructor arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}}},async handler(e){let t=Se("contract",e,"deploy"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_call",description:"Call a circuit on a deployed contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},circuit:{type:"string",description:"Circuit name to invoke"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of circuit arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address","circuit"]},async handler(e){let t=Se("contract",e,"call"),r=await ne("contract");return q(r,t)}},{name:"midnight_test_create",description:"Generate a test scaffold for the contract. Two paths: (1) AI-assisted — pass `goal` (and optionally `screen` for UI strategy) and the scaffold is generated by Claude reading the contract + screen source, producing a focused suite with realistic args / on-screen labels. (2) Deterministic — pass `no-ai: true` (or omit goal/screen in non-interactive mode) for boilerplate scaffolds that the user reviews. CLI strategy emits dapp.test.json + tests/suites/<name>/{suite,actions,assertions}.json. Browser strategy emits prompt.md instead of actions.json plus the browser fields in dapp.test.json — required: port, build-cmd. Use force:true to overwrite.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"dApp directory (defaults to cwd)"},name:{type:"string",description:"Specific contract name when the project has multiple"},suite:{type:"string",description:"Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)"},strategy:{type:"string",enum:["cli","browser"],description:"cli (default): drive contracts via actions.json. browser: drive a real UI via Claude + Chrome via prompt.md."},network:{type:"string",enum:["preprod","preview","undeployed"]},goal:{type:"string",description:'AI mode: one-line success criterion this suite should verify (e.g. "round goes from 0 to 1 after increment"). Triggers AI scaffolding.'},screen:{type:"string",description:'AI mode + browser strategy: name of the screen component to focus on (e.g. "loan-request-form" or "LoanRequestForm"). Auto-discovered from src/components, src/pages, src/screens.'},"no-ai":{type:"boolean",description:"Force deterministic scaffolder even when claude CLI is available."},port:{type:"string",description:'Browser strategy only — dev server port (e.g. "4173").'},"build-cmd":{type:"string",description:'Browser strategy only — shell command that builds + serves the UI (e.g. "npm run dev").'},"build-dir":{type:"string",description:"Browser strategy only — subdir the build runs in (monorepo case)."},url:{type:"string",description:"Browser strategy only — full URL Claude opens (default http://localhost:<port>/)."},"browser-mode":{type:"string",enum:["dom","vision","script"],description:"Browser strategy only — how Claude perceives the page. dom (HTML/React UIs, fast, needs chrome-devtools-mcp), vision (canvas games, slow), script (advanced, needs hooks). Default: dom for AI scaffolds."},force:{type:"boolean",description:"Overwrite existing files instead of aborting on collision"}}},async handler(e){let t=Se("test",e,"create"),r=await ne("test");return q(r,t)}},{name:"midnight_localnet_logs",description:"Snapshot of recent localnet logs (last N lines per service, no streaming). Returns { tail, lines: string[] }.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{tail:{type:"string",description:"Number of lines to retrieve (default 200)"}}},async handler(e){let t=Se("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await ne("localnet");return q(r,t)}},{name:"midnight_confirm_operation",description:"Redeem a pending token (confirm step).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{token:{type:"string"}},required:["token"]},async handler(){throw Error("midnight_confirm_operation reached the inner handler — this is an MCP wiring bug")}}],kS=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),hu=Pa();Qr=new pS({name:"midnight-wallet-cli",version:Ge},{capabilities:{tools:{},resources:{}}});Qr.setRequestHandler(hS,async()=>({resources:[{uri:Su,name:"midnight-wallet skill (core)",description:"Read this first. Intent routing table + non-negotiable safety rules. ~830 tokens. Fetch /full on demand for canonical flows, error recovery, and concept primers.",mimeType:"text/markdown"},{uri:bu,name:"midnight-wallet skill (full)",description:"Canonical multi-step flows, error-recovery recipes, concept primers (NIGHT/DUST/shielded), network selection. Fetch on demand when you hit an error, start a multi-step flow, or need to explain a concept.",mimeType:"text/markdown"}]}));Qr.setRequestHandler(wS,async(e)=>{let t=e.params.uri;if(t===Su){let r=gu(SS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===bu||t===yS){let r=gu(bS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Qr.setRequestHandler(fS,async()=>({tools:vu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Qr.setRequestHandler(gS,async(e)=>{let{name:t,arguments:r}=e.params,n=r??{};if(t==="midnight_confirm_operation"){let s=typeof n.token==="string"?n.token:"",o=hu.redeem(s);if(!o)return Zi(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return wu(o.tool,o.args)}if(kS.has(t)){let s=hu.create({tool:t,args:n,description:CS(t,n)});return{content:[{type:"text",text:JSON.stringify(Qi({pending:!0,token:s.token,description:s.description,tool:s.tool,expiresAt:new Date(s.expiresAt).toISOString(),nextStep:"Show the description to the user, get explicit consent, then call midnight_confirm_operation with this token."}),null,2)}]}}return wu(t,n)});AS().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1319
|
-
`),process.exit(1)})});function
|
|
1320
|
-
`),n=Math.floor(e*100);if(t>=1)return
|
|
1321
|
-
`);return r.map((s,o)=>Array.from(s).map((i,a)=>{if(i===" ")return" ";let c=(o*131+a*997)%100/100;return t>=c?i:
|
|
1322
|
-
`)}var
|
|
1323
|
-
`),
|
|
1324
|
-
`),o=s.length,i=36,a=Math.max(o,t?.length??0),c=3,d=r?.animated??!0;if(!
|
|
1317
|
+
`)}function _y(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var Ql;var gi=E(()=>{Be();ue();Ve();Bd();Zd();tl();nl();al();cl();Ql=["run","list","results","create"]});import{readFileSync as ru}from"node:fs";import{fileURLToPath as ou}from"node:url";import{Server as Dy}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Py}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as Oy,CallToolRequestSchema as My,ListResourcesRequestSchema as Fy,ReadResourceRequestSchema as Ly}from"@modelcontextprotocol/sdk/types.js";function we(e,t,r){let n={json:!0},s=[];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;let a=o==="full"?mr:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}async function ne(e){let t=By[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}function Gy(e,t){let r=t.network??"active network",n=t.wallet??"active wallet";switch(e){case"midnight_transfer":return`Send ${t.amount} NIGHT from ${n} to ${t.to} on ${r}`;case"midnight_contract_deploy":{let s=t.args?` with args ${t.args}`:"";return`Deploy contract from ${t.path??"current directory"} as ${n} on ${r}${s}`}case"midnight_contract_call":{let s=t.args?` with args ${t.args}`:"";return`Call circuit ${t.circuit} on contract ${t.address} as ${n} on ${r}${s}`}default:return`Execute ${e} with ${JSON.stringify(t)}`}}function wi(e){return{...e,_serverVersion:He}}async function su(e,t){let r=cu.find((n)=>n.name===e);if(!r)return hi(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(wi(n),null,2)}]}}catch(n){return hi(n instanceof Error?n:Error(String(n)))}}function hi(e){let{errorCode:t}=br(e);return{content:[{type:"text",text:JSON.stringify(wi({error:!0,code:t,message:ba(e.message)}))}],isError:!0}}async function Ky(){await _r();let e=new Py;await Zr.connect(e)}var iu="midnight-wallet://skill/core",au="midnight-wallet://skill/full",Uy="midnight-wallet://skill",jy,Wy,By,cu,Hy,nu,Zr;var du=E(()=>{dn();Os();Cr();ka();qs();jy=ou(new URL("../docs/SKILL-CORE.md",import.meta.url)),Wy=ou(new URL("../docs/SKILL.md",import.meta.url));By={generate:()=>Promise.resolve().then(() => (Xs(),Ea)),info:()=>Promise.resolve().then(() => (Ys(),Ta)),balance:()=>Promise.resolve().then(() => (xo(),gc)),address:()=>Promise.resolve().then(() => (Eo(),hc)),"genesis-address":()=>Promise.resolve().then(() => (To(),wc)),"inspect-cost":()=>Promise.resolve().then(() => (No(),Sc)),airdrop:()=>Promise.resolve().then(() => (Fn(),kc)),transfer:()=>Promise.resolve().then(() => (Ro(),xc)),dust:()=>Promise.resolve().then(() => (Un(),Nc)),cache:()=>Promise.resolve().then(() => ($o(),Rc)),config:()=>Promise.resolve().then(() => (Io(),$c)),localnet:()=>Promise.resolve().then(() => (Fo(),Hc)),wallet:()=>Promise.resolve().then(() => (Vn(),Jc)),status:()=>Promise.resolve().then(() => (Zc(),Yc)),contract:()=>Promise.resolve().then(() => (gs(),Pd)),test:()=>Promise.resolve().then(() => (gi(),tu))};cu=[{name:"midnight_wallet_generate",description:"Create wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"64-char hex"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=we("wallet",e,"generate");if(r.positionals=[t],delete r.flags.name,e.force==="true"||e.force===!0)r.flags.force=!0;let n=await ne("wallet");return z(n,r)}},{name:"midnight_wallet_list",description:"List wallets. Default: per-wallet { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the 3-network addresses + shieldedAddresses maps.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Return full per-network addresses + shieldedAddresses maps (the same shape `mn wallet list --json` emits). Default false (slim)."}}},async handler({full:e}={}){let t={json:!0};if(e)t[mr]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await ne("wallet");return z(n,r)}},{name:"midnight_wallet_use",description:"Set active wallet.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"use",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return z(n,r)}},{name:"midnight_wallet_info",description:"Show wallet details. Default: { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the per-network maps + createdAt + file path.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},full:{type:"boolean",description:"Return the full per-network addresses + shieldedAddresses maps and bookkeeping fields (matches `mn wallet info <name> --json`). Default false (slim)."}}},async handler(e){let{name:t,full:r}=e,n={json:!0};if(r)n[mr]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await ne("wallet");return z(o,s)}},{name:"midnight_wallet_remove",description:"Remove wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"remove",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return z(n,r)}},{name:"midnight_info",description:"Wallet metadata.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=we("info",e),r=await ne("info");return z(r,t)}},{name:"midnight_balance",description:"NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string"},full:{type:"boolean",description:"Include the queried address + shieldedAddress in the response (matches `mn balance --json`). Default false (slim)."}}},async handler(e){let t=e.address,r=we("balance",e,t);delete r.flags.address;let n=await ne("balance");return z(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64-char hex"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=we("address",e),r=await ne("address");return z(r,t)}},{name:"midnight_genesis_address",description:"Genesis address.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]}}},async handler(e){let t=we("genesis-address",e),r=await ne("genesis-address");return z(r,t)}},{name:"midnight_inspect_cost",description:"Block limits.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e=we("inspect-cost",{}),t=await ne("inspect-cost");return z(t,e)}},{name:"midnight_airdrop",description:'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.',annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{amount:{type:"string",description:"NIGHT"},wallet:{type:"string",description:"Destination: wallet name, JSON path, or bech32m address"},shielded:{type:"string",description:'Set to "true" for shielded airdrop'}},required:["amount"]},async handler(e){let t=e.amount,r=we("airdrop",e,t);delete r.flags.amount;let n=await ne("airdrop");return z(n,r)}},{name:"midnight_transfer",description:"Send NIGHT (returns pending token; see skill).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{to:{type:"string",description:"bech32m"},amount:{type:"string",description:"NIGHT"},wallet:{type:"string"}},required:["to","amount"]},async handler(e){let{to:t,amount:r}=e,n=we("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await ne("transfer");return z(s,n)}},{name:"midnight_dust_register",description:"Register for dust.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=we("dust",e,"register"),r=await ne("dust");return z(r,t)}},{name:"midnight_dust_status",description:"Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},"proof-server":{type:"string"},node:{type:"string"},"indexer-ws":{type:"string"},"no-cache":{type:"string"},full:{type:"boolean",description:"Include sync internals (eventsApplied, ownedUtxos, cached) in the response (matches `mn dust status --json`). Default false (slim)."}}},async handler(e){let t=we("dust",e,"status"),r=await ne("dust");return z(r,t)}},{name:"midnight_config_get",description:"Read config.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"get",positionals:[e.key],flags:{json:!0}},n=await ne("config");return z(n,r)}},{name:"midnight_config_set",description:"Write config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"},value:{type:"string"}},required:["key","value"]},async handler(e){let{key:t,value:r}=e,n={command:"config",subcommand:"set",positionals:[t,r],flags:{json:!0}},s=await ne("config");return z(s,n)}},{name:"midnight_cache_clear",description:"Clear sync cache.",annotations:{destructiveHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]},wallet:{type:"string"}}},async handler(e){let t=we("cache",e,"clear"),r=await ne("cache");return z(r,t)}},{name:"midnight_config_unset",description:"Reset config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"unset",positionals:[e.key],flags:{json:!0}},n=await ne("config");return z(n,r)}},{name:"midnight_localnet_up",description:"Start localnet (Docker).",annotations:{openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},t=await ne("localnet");return z(t,e)}},{name:"midnight_localnet_stop",description:"Stop localnet (preserves state).",annotations:{idempotentHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"stop",positionals:[],flags:{json:!0}},t=await ne("localnet");return z(t,e)}},{name:"midnight_localnet_down",description:"Localnet teardown (volumes + undeployed cache).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"down",positionals:[],flags:{json:!0}},t=await ne("localnet");return z(t,e)}},{name:"midnight_localnet_status",description:"Localnet status.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"status",positionals:[],flags:{json:!0}},t=await ne("localnet");return z(t,e)}},{name:"midnight_localnet_clean",description:"Remove stray containers.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"clean",positionals:[],flags:{json:!0}},t=await ne("localnet");return z(t,e)}},{name:"midnight_contract_inspect",description:"Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed/<name>/compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path)"},name:{type:"string",description:"Specific contract name to inspect when the project has multiple (see siblings field)"}}},async handler(e){let t=we("contract",e,"inspect"),r=await ne("contract");return z(r,t)}},{name:"midnight_contract_state",description:"Read the current ledger state of a deployed contract. Returns the ledger fields as a JSON object.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},path:{type:"string",description:"dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address"]},async handler(e){let t=we("contract",e,"state"),r=await ne("contract");return z(r,t)}},{name:"midnight_contract_deploy",description:"Deploy a compiled Compact contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of constructor arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}}},async handler(e){let t=we("contract",e,"deploy"),r=await ne("contract");return z(r,t)}},{name:"midnight_contract_call",description:"Call a circuit on a deployed contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},circuit:{type:"string",description:"Circuit name to invoke"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of circuit arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address","circuit"]},async handler(e){let t=we("contract",e,"call"),r=await ne("contract");return z(r,t)}},{name:"midnight_test_create",description:"Generate a test scaffold for the contract. Two paths: (1) AI-assisted — pass `goal` (and optionally `screen` for UI strategy) and the scaffold is generated by Claude reading the contract + screen source, producing a focused suite with realistic args / on-screen labels. (2) Deterministic — pass `no-ai: true` (or omit goal/screen in non-interactive mode) for boilerplate scaffolds that the user reviews. CLI strategy emits dapp.test.json + tests/suites/<name>/{suite,actions,assertions}.json. Browser strategy emits prompt.md instead of actions.json plus the browser fields in dapp.test.json — required: port, build-cmd. Use force:true to overwrite.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"dApp directory (defaults to cwd)"},name:{type:"string",description:"Specific contract name when the project has multiple"},suite:{type:"string",description:"Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)"},strategy:{type:"string",enum:["cli","browser"],description:"cli (default): drive contracts via actions.json. browser: drive a real UI via Claude + Chrome via prompt.md."},network:{type:"string",enum:["preprod","preview","undeployed"]},goal:{type:"string",description:'AI mode: one-line success criterion this suite should verify (e.g. "round goes from 0 to 1 after increment"). Triggers AI scaffolding.'},screen:{type:"string",description:'AI mode + browser strategy: name of the screen component to focus on (e.g. "loan-request-form" or "LoanRequestForm"). Auto-discovered from src/components, src/pages, src/screens.'},"no-ai":{type:"boolean",description:"Force deterministic scaffolder even when claude CLI is available."},port:{type:"string",description:'Browser strategy only — dev server port (e.g. "4173").'},"build-cmd":{type:"string",description:'Browser strategy only — shell command that builds + serves the UI (e.g. "npm run dev").'},"build-dir":{type:"string",description:"Browser strategy only — subdir the build runs in (monorepo case)."},url:{type:"string",description:"Browser strategy only — full URL Claude opens (default http://localhost:<port>/)."},"browser-mode":{type:"string",enum:["dom","vision","script"],description:"Browser strategy only — how Claude perceives the page. dom (HTML/React UIs, fast, needs chrome-devtools-mcp), vision (canvas games, slow), script (advanced, needs hooks). Default: dom for AI scaffolds."},force:{type:"boolean",description:"Overwrite existing files instead of aborting on collision"}}},async handler(e){let t=we("test",e,"create"),r=await ne("test");return z(r,t)}},{name:"midnight_localnet_logs",description:"Snapshot of recent localnet logs (last N lines per service, no streaming). Returns { tail, lines: string[] }.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{tail:{type:"string",description:"Number of lines to retrieve (default 200)"}}},async handler(e){let t=we("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await ne("localnet");return z(r,t)}},{name:"midnight_confirm_operation",description:"Redeem a pending token (confirm step).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{token:{type:"string"}},required:["token"]},async handler(){throw Error("midnight_confirm_operation reached the inner handler — this is an MCP wiring bug")}}],Hy=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),nu=va();Zr=new Dy({name:"midnight-wallet-cli",version:He},{capabilities:{tools:{},resources:{}}});Zr.setRequestHandler(Fy,async()=>({resources:[{uri:iu,name:"midnight-wallet skill (core)",description:"Read this first. Intent routing table + non-negotiable safety rules. ~830 tokens. Fetch /full on demand for canonical flows, error recovery, and concept primers.",mimeType:"text/markdown"},{uri:au,name:"midnight-wallet skill (full)",description:"Canonical multi-step flows, error-recovery recipes, concept primers (NIGHT/DUST/shielded), network selection. Fetch on demand when you hit an error, start a multi-step flow, or need to explain a concept.",mimeType:"text/markdown"}]}));Zr.setRequestHandler(Ly,async(e)=>{let t=e.params.uri;if(t===iu){let r=ru(jy,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===au||t===Uy){let r=ru(Wy,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Zr.setRequestHandler(Oy,async()=>({tools:cu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Zr.setRequestHandler(My,async(e)=>{let{name:t,arguments:r}=e.params,n=r??{};if(t==="midnight_confirm_operation"){let s=typeof n.token==="string"?n.token:"",o=nu.redeem(s);if(!o)return hi(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return su(o.tool,o.args)}if(Hy.has(t)){let s=nu.create({tool:t,args:n,description:Gy(t,n)});return{content:[{type:"text",text:JSON.stringify(wi({pending:!0,token:s.token,description:s.description,tool:s.tool,expiresAt:new Date(s.expiresAt).toISOString(),nextStep:"Show the description to the user, get explicit consent, then call midnight_confirm_operation with this token."}),null,2)}]}}return su(t,n)});Ky().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1318
|
+
`),process.exit(1)})});function uu(e){let t=Math.max(0,Math.min(1,e)),r=ur[0].length,n=Math.floor(t*r);return ur.map((s)=>s.slice(0,n).padEnd(r))}function pu(e){let t=Math.max(0,Math.min(1,e)),r=Math.floor(e*100);if(t>=1)return ur;return ur.map((n,s)=>Array.from(n).map((o,i)=>{if(o===" ")return" ";if(t<=0)return Cs(s+20,i,0);let a=((s+20)*131+i*997)%100/100;return t>=a?o:Cs(s+20,i,r)}).join(""))}function Cs(e,t,r){let n=(e*131+t*997+r*7919)%65537/65537;return lu[Math.floor(n*lu.length)]}function mu(e){let t=Math.max(0,Math.min(1,e)),r=ks.split(`
|
|
1319
|
+
`),n=Math.floor(e*100);if(t>=1)return ks;if(t<=0)return r.map((s,o)=>Array.from(s).map((i,a)=>Cs(o,a,0)).join("")).join(`
|
|
1320
|
+
`);return r.map((s,o)=>Array.from(s).map((i,a)=>{if(i===" ")return" ";let c=(o*131+a*997)%100/100;return t>=c?i:Cs(o,a,n)}).join("")).join(`
|
|
1321
|
+
`)}var ks,ur,yi,lu;var Si=E(()=>{ks=[" ████████████ "," ███ ███ "," ███ ██ ███ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ███ ███ "," ███ ███ "," ████████████ "].join(`
|
|
1322
|
+
`),ur=["█▄ ▄█ █ █▀▄ █▄ █ █ █▀▀ █ █ ▀█▀","█ █ █ █ █ █ █ ██ █ █ █ █▀█ █ ","▀ ▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀▀ ▀ ▀ ▀ "];yi=[["wallet","Manage named wallets"],["info","Display wallet metadata"],["balance","Check balance"],["address","Derive address from seed"],["genesis-address","Show genesis address"],["inspect-cost","Display block limits"],["airdrop","Fund from genesis wallet"],["transfer","Send NIGHT tokens"],["dust","Manage dust (fee tokens)"],["contract","Inspect, deploy, call contracts"],["dev","Contract dev loop (watch + deploy)"],["config","Manage CLI config"],["cache","Manage wallet cache"],["localnet","Manage local network"],["serve","DApp Connector server"],["test","Run dApp E2E tests"],["help","Show command usage"],["manual","Full reference manual"]],lu=["░","▒","▓","█","·"," "]});function vi(e,t){return new Promise((r,n)=>{if(t?.aborted){r();return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),r()},{once:!0})})}async function fu(e,t,r){let s=ks.split(`
|
|
1323
|
+
`),o=s.length,i=36,a=Math.max(o,t?.length??0),c=3,d=r?.animated??!0;if(!ut()||!d){let m=ut();for(let w=0;w<a;w++){let y=w<o?s[w]:"",S=m?We(y).padEnd(45):y.padEnd(35),b=t?.[w]??"",v=m&&w<3&&b?k(We(b)):b;if(m)process.stderr.write(y?We(y)+"\x1B[36G"+v+`
|
|
1325
1324
|
`:"\x1B[36G"+v+`
|
|
1326
1325
|
`);else process.stderr.write(S+v+`
|
|
1327
|
-
`)}return}function u(m,w){for(let y=0;y<a;y++){let S=y<m.length?
|
|
1326
|
+
`)}return}function u(m,w){for(let y=0;y<a;y++){let S=y<m.length?We(m[y]):"",b=w[y]??"";if(b)process.stderr.write(S+"\x1B[36G"+b+`\x1B[K
|
|
1328
1327
|
`);else process.stderr.write(S+`\x1B[K
|
|
1329
|
-
`)}}function p(){process.stderr.write(`\x1B[${a}A`)}for(let m=0;m<=20;m++){if(e?.aborted)break;let w=m/20,S=
|
|
1330
|
-
`);if(m>0)p();u(S,[]),await
|
|
1328
|
+
`)}}function p(){process.stderr.write(`\x1B[${a}A`)}for(let m=0;m<=20;m++){if(e?.aborted)break;let w=m/20,S=mu(w).split(`
|
|
1329
|
+
`);if(m>0)p();u(S,[]),await vi(bi,e)}let f=20;for(let m=0;m<=f;m++){if(e?.aborted)break;let w=m/f,y=uu(w);p();let S=Array(a).fill(null);for(let b=0;b<y.length;b++)S[b]=k(We(y[b]));u(s,S),await vi(bi,e)}let g=12;for(let m=0;m<=g;m++){if(e?.aborted)break;let w=m/g,y=pu(w);p();let S=Array(a).fill(null);for(let b=0;b<y.length;b++)S[b]=k(We(y[b]));u(s,S),await vi(bi,e)}p();let h=Array(a).fill(null);if(t)for(let m=0;m<t.length;m++)if(m<3)h[m]=k(We(t[m]));else h[m]=t[m];u(s,h)}var bi=80;var gu=E(()=>{Si()});import{existsSync as Jy,writeFileSync as Vy}from"node:fs";import{join as zy}from"node:path";import{tmpdir as qy}from"node:os";function Xy(){return(process.env.TERM_SESSION_ID??process.env.ITERM_SESSION_ID??`pid-${process.ppid}`).replace(/[^a-zA-Z0-9-]/g,"_").slice(0,64)}function hu(){return zy(qy(),`mn-intro-${Xy()}`)}function wu(){return Jy(hu())}function yu(){try{Vy(hu(),String(Date.now()))}catch{}}var Su=()=>{};function Yy(){let e=[];for(let t of ur)e.push(t);e.push(""),e.push(k("Commands"));for(let[t,r]of yi)e.push(`${L(t.padEnd(18))}${r}`);return e.push(""),e.push(l("midnight (or mn) help <command>")),e.push(l("--json flag available on all commands")),e.push(l("midnight help --agent")+l(" AI & MCP reference")),e}function Zy(){process.stderr.write(`
|
|
1331
1330
|
Commands:
|
|
1332
1331
|
|
|
1333
|
-
`);for(let[e,t]of
|
|
1332
|
+
`);for(let[e,t]of yi)process.stderr.write(` ${e.padEnd(18)}${t}
|
|
1334
1333
|
`);process.stderr.write(`
|
|
1335
1334
|
Usage: midnight <command> (or: mn <command>)
|
|
1336
1335
|
`),process.stderr.write(` --json flag available on all commands
|
|
1337
1336
|
`),process.stderr.write(` midnight help --agent AI & MCP reference
|
|
1338
1337
|
|
|
1339
|
-
`)}function
|
|
1340
|
-
`+
|
|
1338
|
+
`)}function Qy(e){if(process.stdout.write(`
|
|
1339
|
+
`+W(e.name)+`
|
|
1341
1340
|
|
|
1342
1341
|
`),process.stdout.write(` ${e.description}
|
|
1343
1342
|
|
|
@@ -1350,11 +1349,11 @@ Commands:
|
|
|
1350
1349
|
`)}if(e.examples&&e.examples.length>0){process.stdout.write(nt("Examples:")+`
|
|
1351
1350
|
`);for(let t of e.examples)process.stdout.write(` ${l("$")} ${t}
|
|
1352
1351
|
`);process.stdout.write(`
|
|
1353
|
-
`)}}function
|
|
1352
|
+
`)}}function eS(){let e={cli:{name:kr,version:He,description:na,bin:["midnight","mn"]},globalFlags:[{name:"--json",description:"Output structured JSON to stdout (suppresses all stderr)"},{name:"--wallet <name|file>",description:"Wallet name or path"},{name:"--network <name>",description:"Override network (preprod, preview, undeployed)"},{name:"--version, -v",description:"Print CLI version"},{name:"--help, -h",description:"Show help"}],commands:pr.map((t)=>({name:t.name,description:t.description,usage:t.usage,flags:t.flags,examples:t.examples,jsonFields:t.jsonFields}))};D(e)}function tS(){let e=`
|
|
1354
1353
|
MIDNIGHT CLI — AI Agent & MCP Reference
|
|
1355
1354
|
========================================
|
|
1356
1355
|
|
|
1357
|
-
Version: ${
|
|
1356
|
+
Version: ${He}
|
|
1358
1357
|
|
|
1359
1358
|
OVERVIEW
|
|
1360
1359
|
────────
|
|
@@ -1387,7 +1386,7 @@ examples, and JSON field schemas.
|
|
|
1387
1386
|
|
|
1388
1387
|
COMMANDS & JSON SCHEMAS
|
|
1389
1388
|
───────────────────────
|
|
1390
|
-
${
|
|
1389
|
+
${pr.filter((t)=>t.jsonFields).map((t)=>{let r=Object.entries(t.jsonFields).map(([n,s])=>` ${n.padEnd(20)}${s}`).join(`
|
|
1391
1390
|
`);return`
|
|
1392
1391
|
${t.name}
|
|
1393
1392
|
${t.usage}
|
|
@@ -1454,7 +1453,9 @@ can connect to it — no browser extension needed.
|
|
|
1454
1453
|
|
|
1455
1454
|
- Port default: 9932, localhost only
|
|
1456
1455
|
- Read operations: auto-approved
|
|
1457
|
-
- Write operations
|
|
1456
|
+
- Write operations, balancing included (balanceUnsealedTransaction /
|
|
1457
|
+
balanceSealedTransaction sign and return a finished transaction):
|
|
1458
|
+
terminal approval prompt (or --approve-all)
|
|
1458
1459
|
- --no-auto-approve-reads: require approval for everything
|
|
1459
1460
|
|
|
1460
1461
|
DApp developers connect via the midnight-wallet-connector npm package:
|
|
@@ -1739,54 +1740,55 @@ EXAMPLE CLI COMMANDS
|
|
|
1739
1740
|
# Start DApp connector
|
|
1740
1741
|
midnight serve --network preview --approve-all
|
|
1741
1742
|
# DApps connect at ws://localhost:9932
|
|
1742
|
-
`;process.stdout.write(e)}async function
|
|
1743
|
-
Available commands: ${jt.map((c)=>c.name).join(", ")}`);DS(a);return}if(!process.stderr.isTTY){_S();return}let r=IS(),n=N(e,"intro"),s=N(e,"no-intro"),o=$u(),i=n||!s&&!o;if(await Tu(void 0,r,{animated:i}),i)Iu()}var jt;var sa=x(()=>{ue();Nu();ta();_u();He();Tr();jt=[{name:"wallet",description:"Manage named wallets (generate, list, use, info, remove, seed)",usage:"midnight wallet <generate|list|use|info|remove|seed> [args]",flags:["generate <name> Create a new named wallet and set it as active","list Show all wallets with active marker","use <name> Set active wallet","info [name] Show wallet details (active wallet if no name)","remove <name> Delete a wallet (refuses active or last wallet)","seed [name] Reveal the seed + mnemonic (prompts for confirmation)","","generate flags:","--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--force Overwrite existing wallet file","","seed flags:","--entropy Also output the 32-byte BIP-39 entropy alongside the"," 64-byte PBKDF2 seed (use when another tool expects"," the shorter entropy format — NB: the two derive"," DIFFERENT Midnight wallets from the same mnemonic)","--json Print JSON (skips interactive confirmation)"],examples:["midnight wallet generate alice --network preprod","midnight wallet list","midnight wallet use alice","midnight wallet info alice","midnight wallet remove bob","midnight wallet seed alice --entropy"],jsonFields:{name:"Wallet name",address:"Wallet address (bech32m)",network:"Network name",active:"Whether this is the active wallet",wallets:"Array of wallet info objects (list only)"}},{name:"generate",description:'(Deprecated — use "midnight wallet generate <name>" instead)',usage:'midnight generate [--network <name>] [--seed <hex>] [--mnemonic "..."] [--output <file>] [--force]',flags:["--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--output <file> Custom output path (default: ~/.midnight/wallet.json)","--force Overwrite existing wallet file"],examples:["midnight generate --network preprod"],jsonFields:{address:"Generated wallet address (bech32m)",network:"Network name",seed:"Hex-encoded 32-byte seed",mnemonic:"BIP-39 mnemonic (24 words, only if generated or provided)",file:"Path where wallet file was saved",createdAt:"ISO 8601 creation timestamp"}},{name:"info",description:"Display wallet address, network, creation date (no secrets shown)",usage:"midnight info [--wallet <name|file>]",flags:["--wallet <name|file> Wallet name or path"],examples:["midnight info","midnight info --wallet my-wallet.json"],jsonFields:{addresses:"Per-network unshielded addresses { preprod, preview, undeployed }",shieldedAddresses:"Per-network shielded addresses { preprod, preview, undeployed }",activeNetwork:"Currently active network",activeAddress:"Unshielded address for active network (also written to stdout)",createdAt:"ISO 8601 creation timestamp",file:"Wallet file path"}},{name:"balance",description:"Check unshielded + shielded balance (full wallet sync)",usage:"midnight balance [address] [--network <name>] [--indexer-ws <url>]",flags:["<address> Check a specific address (unshielded only, no wallet sync)","--shielded Include shielded balance — needs the seed, so the address must be one of your wallets","--force-shielded Sync shielded even on preview/preprod (skipped by default — no faucet there)","--no-cache Bypass wallet state cache (force a fresh sync)","--network <name> Override network","--indexer-ws <url> Custom indexer WebSocket URL"],examples:["midnight balance","midnight balance mn_addr_preprod1...","midnight balance --wallet alice --shielded"],jsonFields:{address:"Unshielded address (bech32m)",shieldedAddress:"Shielded address",network:"Network name",unshielded:"{ NIGHT, utxoCount }",shielded:"{ NIGHT, availableCoins, pendingCoins }"}},{name:"address",description:"Derive and display an unshielded address from a seed",usage:"midnight address --seed <hex> [--network <name>] [--index <n>]",flags:["--seed <hex> Seed to derive from (required, 64-char hex)","--network <name> Network for address prefix (default: resolved)","--index <n> Key derivation index (default: 0)"],examples:["midnight address --seed 0123456789abcdef... --network preprod","midnight address --seed 0123456789abcdef... --index 1"],jsonFields:{address:"Derived address (bech32m)",network:"Network name",index:"Key derivation index",path:"BIP-44 derivation path"}},{name:"genesis-address",description:"Display the genesis wallet address (seed 0x01) for a network",usage:"midnight genesis-address [--network <name>]",flags:["--network <name> Network for address prefix (default: resolved)"],examples:["midnight genesis-address --network undeployed","midnight genesis-address --network preprod"],jsonFields:{address:"Genesis wallet address (bech32m)",network:"Network name"}},{name:"inspect-cost",description:"Display current block limits derived from LedgerParameters",usage:"midnight inspect-cost",examples:["midnight inspect-cost"],jsonFields:{readTime:"Read time limit (picoseconds)",computeTime:"Compute time limit (picoseconds)",blockUsage:"Block usage limit (bytes)",bytesWritten:"Bytes written limit (bytes)",bytesChurned:"Bytes churned limit (bytes)"}},{name:"airdrop",description:"Fund a wallet from the genesis wallet (undeployed network only)",usage:"midnight airdrop <amount> [--shielded] [--wallet <name|file|address>]",flags:["<amount> Amount in NIGHT to airdrop","--shielded Airdrop shielded NIGHT (from genesis shielded balance)","--wallet <…> Destination — a wallet name, a wallet JSON path, or"," a raw bech32m address (mn_addr_… / mn_shield-addr_…)."," Defaults to the active wallet when omitted."],examples:["midnight airdrop 1000","midnight airdrop 1000 --wallet alice","midnight airdrop 10000 --wallet mn_addr_undeployed1...","midnight airdrop 100 --shielded","midnight airdrop 100 --shielded --wallet mn_shield-addr_undeployed1..."],jsonFields:{txHash:"Transaction hash",amount:"Amount airdropped (NIGHT string)",recipient:"Recipient address (unshielded airdrop)",shieldedAddress:"Shielded address (--shielded airdrop)",network:"Network name"}},{name:"transfer",description:"Send NIGHT tokens to another address (unshielded or --shielded)",usage:"midnight transfer <to> <amount> [--shielded] [--wallet <name|file>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>]",flags:["<to> Recipient bech32m address (unshielded or shielded)","<amount> Amount in NIGHT to send","--shielded Send from shielded balance to a shielded address","--force-shielded Allow --shielded on preview/preprod (blocked by default — no faucet there)","--wallet <name|file> Wallet name or path","--proof-server <url> Override proof server URL","--node <url> Override substrate node RPC URL","--indexer-ws <url> Override indexer WebSocket URL"],examples:["midnight transfer mn_addr_undeployed1... 100","midnight transfer mn_shield-addr_undeployed1... 50 --shielded"],jsonFields:{txHash:"Transaction hash",amount:"Amount transferred (NIGHT string)",recipient:"Recipient address (bech32m)",network:"Network name"}},{name:"dust",description:"Register UTXOs for dust (fee token) generation, check status, or export a restorable snapshot",usage:"midnight dust <register|status|export> [--wallet <name|file>] [--seed <hex> (export only)] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--no-cache (status only)]",flags:["register Register NIGHT UTXOs for dust generation","status Check dust registration; if registered, also shows dust balance","export Fast-sync dust and emit a restorable snapshot (dustSerializedState)","--wallet <name|file> Wallet name or path","--seed <hex> 32-byte hex seed (export only; or set MN_SEED env to keep it off argv)","--proof-server <url> Override proof server URL (register only)","--node <url> Override substrate node RPC URL (register only)","--indexer-ws <url> Override indexer WebSocket URL","--no-cache Bypass wallet state cache (status only)","MN_DUST_SYNC_BIN=<path> (env) Use this native dust-sync sidecar binary instead of auto-detecting it","MN_DISABLE_NATIVE_DUST=1 (env) Disable the native sidecar; fall back to the WASM dust sync"],examples:["midnight dust register","midnight dust status","midnight dust export --network preview --json","midnight dust export --seed <64-hex> --network preview --json"],jsonFields:{subcommand:"register, status, or export",registered:"true if at least one NIGHT UTXO is registered for dust generation (status only)",registeredUtxos:"Number of registered UTXOs (status only)",unregisteredUtxos:"Number of unregistered UTXOs (status only)",dustBalance:"Dust balance (raw bigint string; status when registered, register, and export)",nightBalance:"NIGHT balance (raw bigint string; status only when registered)",dustAvailable:"Whether dust tokens are available (status only when registered)",txHash:"Registration transaction hash (register only, if submitted)",dustPublicKey:"Dust public key hex the snapshot belongs to (export only)",offset:"Last dust event id the snapshot covers, -1 if none (export only)",snapshot:"Facade-restorable dust snapshot JSON — pass as the SDK dustSerializedState (export only)"}},{name:"config",description:"Manage persistent config (default network, endpoints, etc.)",usage:"midnight config <get|set|unset> <key> [value]",flags:["get <key> Read a config value","set <key> <value> Write a config value","unset <key> Reset a config value to its default","","Keys: network, wallet, proof-server, node, indexer-ws","","Endpoint keys (proof-server, node, indexer-ws) are scoped to the","network configured at set time — a preprod node URL never applies","to --network undeployed runs. get/unset use the current network's value."],examples:["midnight config get network","midnight config set network preprod","midnight config set wallet alice","midnight config set proof-server http://localhost:6300","midnight config set node wss://rpc.preprod.midnight.network",`midnight config set indexer-ws wss://indexer.preprod.midnight.network${gt}`,"midnight config unset proof-server"],jsonFields:{action:"get, set, or unset",key:"Config key name",value:"Config value"}},{name:"cache",description:"Manage wallet state cache (clear cached sync data)",usage:"midnight cache clear [--network <name>] [--wallet <name|file>]",flags:["clear Clear cached wallet state","--network <name> Only clear cache for this network","--wallet <name|file> Only clear cache for this wallet"],examples:["midnight cache clear","midnight cache clear --network preprod","midnight cache clear --wallet alice"],jsonFields:{action:"clear",scope:"all, network, or wallet",network:"Network name (when scoped)",wallet:"Wallet name (when scoped)"}},{name:"serve",description:"Start DApp Connector server over WebSocket JSON-RPC",usage:"midnight serve [--port <n>] [--wallet <name|file>] [--network <name>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--approve-all] [--no-auto-approve-reads] [--json]",flags:["--port <n> Server port (default: 9932)","--wallet <name|file> Wallet name or path","--network <name> Override network detection","--proof-server <url> Override proof server URL","--node <url> Override substrate node RPC URL","--indexer-ws <url> Override indexer WebSocket URL","--approve-all Auto-approve all requests (reads + writes)","--no-auto-approve-reads Prompt for read methods too"],examples:["midnight serve","midnight serve --port 8080","midnight serve --approve-all"],jsonFields:{port:"Server port number",network:"Network name",address:"Wallet address (bech32m)",status:"Server status (listening)"}},{name:"test",description:"Generate and run E2E test suites for Midnight dApps",usage:"midnight test <create|run|list|results> [options]",flags:["create Generate a test scaffold from the contract (CLI or browser strategy)","run Run test suites for the current dApp","list List available test suites","results Show latest test results","--suite <name> Select a specific test suite (run, create)","--all Show all results (with results subcommand)","--strategy cli|ui Scaffold strategy (create — interactive prompt if omitted)","--name <contract> Specific contract name in multi-contract projects (create)","--path <dir> dApp directory (default: cwd)","--network <name> Network for the generated suite (default: undeployed)","--port <n> Browser strategy: dev server port (create --strategy ui)","--build-cmd <cmd> Browser strategy: build/serve command","--build-dir <subdir> Browser strategy: subdirectory the build runs in (monorepo case)","--url <url> Browser strategy: full URL Claude opens (default http://localhost:<port>/)","--browser-mode <m> Browser strategy: dom (HTML UIs, fast — default), vision (canvas games), script (advanced)","--force Overwrite existing scaffold files (create)","--json Output structured JSON"],examples:["midnight test create","midnight test create --strategy cli --force",'midnight test create --strategy ui --port 4173 --build-cmd "npm run dev"',"midnight test run","midnight test run --suite e2e-gameplay","midnight test list","midnight test results --all --json"],jsonFields:{dapp:"DApp name from dapp.test.json",suite:"Test suite name",status:"Overall result: pass, fail, timeout, or error",duration:"Total duration in seconds",prep:"Array of prep step results",assertions:"Array of assertion results"}},{name:"dev",description:"Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy)",usage:"midnight dev [path]",flags:["[path] Project directory (default: cwd)","","Keystrokes (while running):"," d Deploy the current compiled artifact (dev-alice on undeployed)"," t Run the project's npm test script (test:dev preferred, then test)"," q Quit cleanly"," Ctrl+C Quit cleanly"],examples:["midnight dev","midnight dev ./contract"]},{name:"contract",description:"Inspect, deploy, call, and query Midnight smart contracts",usage:"midnight contract <inspect|deploy|call|state> [options]",flags:["inspect Show circuits, witnesses, and types","deploy Deploy a contract to the network","call Call a circuit on a deployed contract","state Read ledger state of a deployed contract","--address <addr> Contract address (call, state)","--circuit <name> Circuit to call (call)",`--args '<json>' JSON arguments — constructor args (deploy) or circuit args (call). Numbers auto-coerce to BigInt; "123n" strings parse as BigInt; arrays of 0–255 ints become Uint8Array`,"--network <name> Override network (default: undeployed)","--path <dir> dApp directory (all subcommands; default: cwd)","--managed <dir> Direct path to managed/<name>/ directory (all subcommands)","--name <contract> Specific contract when the project ships multiple (all subcommands)","--wallet <name> Wallet to use for the operation (deploy, call, state)","--secret-key <64-hex> Seed a caller-chosen initial private-state secret (deploy). For contracts whose constructor derives its owner from public_key(secret_key()); passed to the deploy subprocess via env, never written to disk","--json Output structured JSON"],examples:["midnight contract inspect","midnight contract deploy",`midnight contract deploy --args '{"deadlineSecs": 300}'`,`midnight contract call --address 0x123 --circuit submit_score --args '{"score": 100, "alias": "TEST"}'`,"midnight contract state --address 0x123","midnight contract deploy --json"],jsonFields:{name:"Contract name",address:"Deployed contract address (deploy, call)",compilerVersion:"Compact compiler version (inspect)",circuits:"Array of circuit definitions (inspect)",witnesses:"Array of witness definitions (inspect)",state:"Contract ledger state (state)"}},{name:"localnet",description:"Manage a local Midnight network via Docker Compose",usage:"midnight localnet <up|stop|down|status|logs|clean>",flags:["up Start the local network (node, indexer, proof server)","stop Stop containers (preserves state for fast restart)","down Full teardown: containers, networks, volumes, + undeployed wallet cache","status Show service status and ports","logs Stream service logs (Ctrl+C to stop)","clean Remove conflicting containers from other setups"],examples:["midnight localnet up","midnight localnet stop","midnight localnet status","midnight localnet down","midnight localnet clean"],jsonFields:{subcommand:"up, stop, down, status, or clean",services:"Array of { name, state, port, health? } (up/status only)",status:"Operation result message (stop/down/clean)",removed:"Array of removed container names (clean only)"}},{name:"help",description:"Show usage for all commands or a specific command",usage:"midnight help [command]",examples:["midnight help","midnight help balance"],jsonFields:{cli:"CLI metadata (name, version, description)",globalFlags:"Array of global flag descriptions",commands:"Array of command specs with jsonFields"}},{name:"manual",description:"Full reference manual (long form, paged through $PAGER)",usage:"midnight manual [--no-pager] [--raw] [--json]",flags:["--no-pager Print straight to stdout, do not pipe through less","--raw Strip ANSI colors (useful for piping to a file)","--json Emit the manual text wrapped in a JSON object"],examples:["midnight manual","midnight manual --no-pager | grep -i dust","midnight manual --raw > MANUAL.txt"],jsonFields:{name:"CLI package name",version:"CLI version",manual:"Manual text (with ANSI colors)"}}]});var Lu={};W(Lu,{buildManual:()=>_s,default:()=>Fu});import{spawn as MS}from"node:child_process";function FS(e){return`${k(Ou)}
|
|
1744
|
-
${k(
|
|
1745
|
-
${k(
|
|
1746
|
-
`}function
|
|
1747
|
-
${l(
|
|
1748
|
-
${k(
|
|
1749
|
-
${l(
|
|
1750
|
-
`}function
|
|
1751
|
-
`)}function
|
|
1752
|
-
`)}function
|
|
1753
|
-
`+
|
|
1743
|
+
`;process.stdout.write(e)}async function ki(e){if(N(e,"agent")){tS();return}if(N(e,"json")){eS();return}let t=e.subcommand;if(t){let a=pr.find((c)=>c.name===t);if(!a)throw new Z(`Unknown command: "${t}"
|
|
1744
|
+
Available commands: ${pr.map((c)=>c.name).join(", ")}`);Qy(a);return}if(!process.stderr.isTTY){Zy();return}let r=Yy(),n=N(e,"intro"),s=N(e,"no-intro"),o=wu(),i=n||!s&&!o;if(await fu(void 0,r,{animated:i}),i)yu()}var pr;var Ci=E(()=>{ue();gu();Si();Su();Be();Cr();pr=[{name:"wallet",description:"Manage named wallets (generate, list, use, info, remove, seed)",usage:"midnight wallet <generate|list|use|info|remove|seed> [args]",flags:["generate <name> Create a new named wallet and set it as active","list Show all wallets with active marker","use <name> Set active wallet","info [name] Show wallet details (active wallet if no name)","remove <name> Delete a wallet (refuses active or last wallet)","seed [name] Reveal the seed + mnemonic (prompts for confirmation)","","generate flags:","--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--force Overwrite existing wallet file","","seed flags:","--entropy Also output the 32-byte BIP-39 entropy alongside the"," 64-byte PBKDF2 seed (use when another tool expects"," the shorter entropy format — NB: the two derive"," DIFFERENT Midnight wallets from the same mnemonic)","--json Print JSON (skips interactive confirmation)"],examples:["midnight wallet generate alice --network preprod","midnight wallet list","midnight wallet use alice","midnight wallet info alice","midnight wallet remove bob","midnight wallet seed alice --entropy"],jsonFields:{name:"Wallet name",address:"Wallet address (bech32m)",network:"Network name",active:"Whether this is the active wallet",wallets:"Array of wallet info objects (list only)"}},{name:"generate",description:'(Deprecated — use "midnight wallet generate <name>" instead)',usage:'midnight generate [--network <name>] [--seed <hex>] [--mnemonic "..."] [--output <file>] [--force]',flags:["--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--output <file> Custom output path (default: ~/.midnight/wallet.json)","--force Overwrite existing wallet file"],examples:["midnight generate --network preprod"],jsonFields:{address:"Generated wallet address (bech32m)",network:"Network name",seed:"Hex-encoded 32-byte seed",mnemonic:"BIP-39 mnemonic (24 words, only if generated or provided)",file:"Path where wallet file was saved",createdAt:"ISO 8601 creation timestamp"}},{name:"info",description:"Display wallet address, network, creation date (no secrets shown)",usage:"midnight info [--wallet <name|file>]",flags:["--wallet <name|file> Wallet name or path"],examples:["midnight info","midnight info --wallet my-wallet.json"],jsonFields:{addresses:"Per-network unshielded addresses { preprod, preview, undeployed }",shieldedAddresses:"Per-network shielded addresses { preprod, preview, undeployed }",activeNetwork:"Currently active network",activeAddress:"Unshielded address for active network (also written to stdout)",createdAt:"ISO 8601 creation timestamp",file:"Wallet file path"}},{name:"balance",description:"Check unshielded + shielded balance (full wallet sync)",usage:"midnight balance [address] [--network <name>] [--indexer-ws <url>]",flags:["<address> Check a specific address (unshielded only, no wallet sync)","--shielded Include shielded balance — needs the seed, so the address must be one of your wallets","--force-shielded Sync shielded even on preview/preprod (skipped by default — no faucet there)","--no-cache Bypass wallet state cache (force a fresh sync)","--network <name> Override network","--indexer-ws <url> Custom indexer WebSocket URL"],examples:["midnight balance","midnight balance mn_addr_preprod1...","midnight balance --wallet alice --shielded"],jsonFields:{address:"Unshielded address (bech32m)",shieldedAddress:"Shielded address",network:"Network name",unshielded:"{ NIGHT, utxoCount }",shielded:"{ NIGHT, availableCoins, pendingCoins }"}},{name:"address",description:"Derive and display an unshielded address from a seed",usage:"midnight address --seed <hex> [--network <name>] [--index <n>]",flags:["--seed <hex> Seed to derive from (required, 64-char hex)","--network <name> Network for address prefix (default: resolved)","--index <n> Key derivation index (default: 0)"],examples:["midnight address --seed 0123456789abcdef... --network preprod","midnight address --seed 0123456789abcdef... --index 1"],jsonFields:{address:"Derived address (bech32m)",network:"Network name",index:"Key derivation index",path:"BIP-44 derivation path"}},{name:"genesis-address",description:"Display the genesis wallet address (seed 0x01) for a network",usage:"midnight genesis-address [--network <name>]",flags:["--network <name> Network for address prefix (default: resolved)"],examples:["midnight genesis-address --network undeployed","midnight genesis-address --network preprod"],jsonFields:{address:"Genesis wallet address (bech32m)",network:"Network name"}},{name:"inspect-cost",description:"Display current block limits derived from LedgerParameters",usage:"midnight inspect-cost",examples:["midnight inspect-cost"],jsonFields:{readTime:"Read time limit (picoseconds)",computeTime:"Compute time limit (picoseconds)",blockUsage:"Block usage limit (bytes)",bytesWritten:"Bytes written limit (bytes)",bytesChurned:"Bytes churned limit (bytes)"}},{name:"airdrop",description:"Fund a wallet from the genesis wallet (undeployed network only)",usage:"midnight airdrop <amount> [--shielded] [--wallet <name|file|address>]",flags:["<amount> Amount in NIGHT to airdrop","--shielded Airdrop shielded NIGHT (from genesis shielded balance)","--wallet <…> Destination — a wallet name, a wallet JSON path, or"," a raw bech32m address (mn_addr_… / mn_shield-addr_…)."," Defaults to the active wallet when omitted."],examples:["midnight airdrop 1000","midnight airdrop 1000 --wallet alice","midnight airdrop 10000 --wallet mn_addr_undeployed1...","midnight airdrop 100 --shielded","midnight airdrop 100 --shielded --wallet mn_shield-addr_undeployed1..."],jsonFields:{txHash:"Transaction hash",amount:"Amount airdropped (NIGHT string)",recipient:"Recipient address (unshielded airdrop)",shieldedAddress:"Shielded address (--shielded airdrop)",network:"Network name"}},{name:"transfer",description:"Send NIGHT tokens to another address (unshielded or --shielded)",usage:"midnight transfer <to> <amount> [--shielded] [--wallet <name|file>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>]",flags:["<to> Recipient bech32m address (unshielded or shielded)","<amount> Amount in NIGHT to send","--shielded Send from shielded balance to a shielded address","--force-shielded Allow --shielded on preview/preprod (blocked by default — no faucet there)","--wallet <name|file> Wallet name or path","--proof-server <url> Override proof server URL","--node <url> Override substrate node RPC URL","--indexer-ws <url> Override indexer WebSocket URL"],examples:["midnight transfer mn_addr_undeployed1... 100","midnight transfer mn_shield-addr_undeployed1... 50 --shielded"],jsonFields:{txHash:"Transaction hash",amount:"Amount transferred (NIGHT string)",recipient:"Recipient address (bech32m)",network:"Network name"}},{name:"dust",description:"Register UTXOs for dust (fee token) generation, check status, or export a restorable snapshot",usage:"midnight dust <register|status|export> [--wallet <name|file>] [--seed <hex> (export only)] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--no-cache (status only)]",flags:["register Register NIGHT UTXOs for dust generation","status Check dust registration; if registered, also shows dust balance","export Fast-sync dust and emit a restorable snapshot (dustSerializedState)","--wallet <name|file> Wallet name or path","--seed <hex> 32-byte hex seed (export only; or set MN_SEED env to keep it off argv)","--proof-server <url> Override proof server URL (register only)","--node <url> Override substrate node RPC URL (register only)","--indexer-ws <url> Override indexer WebSocket URL","--no-cache Bypass wallet state cache (status only)","MN_DUST_SYNC_BIN=<path> (env) Use this native dust-sync sidecar binary instead of auto-detecting it","MN_DISABLE_NATIVE_DUST=1 (env) Disable the native sidecar; fall back to the WASM dust sync"],examples:["midnight dust register","midnight dust status","midnight dust export --network preview --json","midnight dust export --seed <64-hex> --network preview --json"],jsonFields:{subcommand:"register, status, or export",registered:"true if at least one NIGHT UTXO is registered for dust generation (status only)",registeredUtxos:"Number of registered UTXOs (status only)",unregisteredUtxos:"Number of unregistered UTXOs (status only)",dustBalance:"Dust balance (raw bigint string; status when registered, register, and export)",nightBalance:"NIGHT balance (raw bigint string; status only when registered)",dustAvailable:"Whether dust tokens are available (status only when registered)",txHash:"Registration transaction hash (register only, if submitted)",dustPublicKey:"Dust public key hex the snapshot belongs to (export only)",offset:"Last dust event id the snapshot covers, -1 if none (export only)",snapshot:"Facade-restorable dust snapshot JSON — pass as the SDK dustSerializedState (export only)"}},{name:"config",description:"Manage persistent config (default network, endpoints, etc.)",usage:"midnight config <get|set|unset> <key> [value]",flags:["get <key> Read a config value","set <key> <value> Write a config value","unset <key> Reset a config value to its default","","Keys: network, wallet, proof-server, node, indexer-ws","","Endpoint keys (proof-server, node, indexer-ws) are scoped to the","network configured at set time — a preprod node URL never applies","to --network undeployed runs. get/unset use the current network's value."],examples:["midnight config get network","midnight config set network preprod","midnight config set wallet alice","midnight config set proof-server http://localhost:6300","midnight config set node wss://rpc.preprod.midnight.network",`midnight config set indexer-ws wss://indexer.preprod.midnight.network${Ct}`,"midnight config unset proof-server"],jsonFields:{action:"get, set, or unset",key:"Config key name",value:"Config value"}},{name:"cache",description:"Manage wallet state cache (clear cached sync data)",usage:"midnight cache clear [--network <name>] [--wallet <name|file>]",flags:["clear Clear cached wallet state","--network <name> Only clear cache for this network","--wallet <name|file> Only clear cache for this wallet"],examples:["midnight cache clear","midnight cache clear --network preprod","midnight cache clear --wallet alice"],jsonFields:{action:"clear",scope:"all, network, or wallet",network:"Network name (when scoped)",wallet:"Wallet name (when scoped)"}},{name:"serve",description:"Start DApp Connector server over WebSocket JSON-RPC",usage:"midnight serve [--port <n>] [--wallet <name|file>] [--network <name>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--approve-all] [--no-auto-approve-reads] [--json]",flags:["--port <n> Server port (default: 9932)","--wallet <name|file> Wallet name or path","--network <name> Override network detection","--proof-server <url> Override proof server URL","--node <url> Override substrate node RPC URL","--indexer-ws <url> Override indexer WebSocket URL","--approve-all Auto-approve all requests (reads + writes)","--no-auto-approve-reads Prompt for read methods too"],examples:["midnight serve","midnight serve --port 8080","midnight serve --approve-all"],jsonFields:{port:"Server port number",network:"Network name",address:"Wallet address (bech32m)",status:"Server status (listening)"}},{name:"test",description:"Generate and run E2E test suites for Midnight dApps",usage:"midnight test <create|run|list|results> [options]",flags:["create Generate a test scaffold from the contract (CLI or browser strategy)","run Run test suites for the current dApp","list List available test suites","results Show latest test results","--suite <name> Select a specific test suite (run, create)","--all Show all results (with results subcommand)","--strategy cli|ui Scaffold strategy (create — interactive prompt if omitted)","--name <contract> Specific contract name in multi-contract projects (create)","--path <dir> dApp directory (default: cwd)","--network <name> Network for the generated suite (default: undeployed)","--port <n> Browser strategy: dev server port (create --strategy ui)","--build-cmd <cmd> Browser strategy: build/serve command","--build-dir <subdir> Browser strategy: subdirectory the build runs in (monorepo case)","--url <url> Browser strategy: full URL Claude opens (default http://localhost:<port>/)","--browser-mode <m> Browser strategy: dom (HTML UIs, fast — default), vision (canvas games), script (advanced)","--force Overwrite existing scaffold files (create)","--json Output structured JSON"],examples:["midnight test create","midnight test create --strategy cli --force",'midnight test create --strategy ui --port 4173 --build-cmd "npm run dev"',"midnight test run","midnight test run --suite e2e-gameplay","midnight test list","midnight test results --all --json"],jsonFields:{dapp:"DApp name from dapp.test.json",suite:"Test suite name",status:"Overall result: pass, fail, timeout, or error",duration:"Total duration in seconds",prep:"Array of prep step results",assertions:"Array of assertion results"}},{name:"dev",description:"Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy)",usage:"midnight dev [path]",flags:["[path] Project directory (default: cwd)","","Keystrokes (while running):"," d Deploy the current compiled artifact (dev-alice on undeployed)"," t Run the project's npm test script (test:dev preferred, then test)"," q Quit cleanly"," Ctrl+C Quit cleanly"],examples:["midnight dev","midnight dev ./contract"]},{name:"contract",description:"Inspect, deploy, call, and query Midnight smart contracts",usage:"midnight contract <inspect|deploy|call|state> [options]",flags:["inspect Show circuits, witnesses, and types","deploy Deploy a contract to the network","call Call a circuit on a deployed contract","state Read ledger state of a deployed contract","--address <addr> Contract address (call, state)","--circuit <name> Circuit to call (call)",`--args '<json>' JSON arguments — constructor args (deploy) or circuit args (call). Numbers auto-coerce to BigInt; "123n" strings parse as BigInt; arrays of 0–255 ints become Uint8Array`,"--network <name> Override network (default: undeployed)","--path <dir> dApp directory (all subcommands; default: cwd)","--managed <dir> Direct path to managed/<name>/ directory (all subcommands)","--name <contract> Specific contract when the project ships multiple (all subcommands)","--wallet <name> Wallet to use for the operation (deploy, call, state)","--secret-key <64-hex> Seed a caller-chosen initial private-state secret (deploy). For contracts whose constructor derives its owner from public_key(secret_key()); passed to the deploy subprocess via env, never written to disk","--json Output structured JSON"],examples:["midnight contract inspect","midnight contract deploy",`midnight contract deploy --args '{"deadlineSecs": 300}'`,`midnight contract call --address 0x123 --circuit submit_score --args '{"score": 100, "alias": "TEST"}'`,"midnight contract state --address 0x123","midnight contract deploy --json"],jsonFields:{name:"Contract name",address:"Deployed contract address (deploy, call)",compilerVersion:"Compact compiler version (inspect)",circuits:"Array of circuit definitions (inspect)",witnesses:"Array of witness definitions (inspect)",state:"Contract ledger state (state)"}},{name:"localnet",description:"Manage a local Midnight network via Docker Compose",usage:"midnight localnet <up|stop|down|status|logs|clean>",flags:["up Start the local network (node, indexer, proof server)","stop Stop containers (preserves state for fast restart)","down Full teardown: containers, networks, volumes, + undeployed wallet cache","status Show service status and ports","logs Stream service logs (Ctrl+C to stop)","clean Remove conflicting containers from other setups"],examples:["midnight localnet up","midnight localnet stop","midnight localnet status","midnight localnet down","midnight localnet clean"],jsonFields:{subcommand:"up, stop, down, status, or clean",services:"Array of { name, state, port, health? } (up/status only)",status:"Operation result message (stop/down/clean)",removed:"Array of removed container names (clean only)"}},{name:"help",description:"Show usage for all commands or a specific command",usage:"midnight help [command]",examples:["midnight help","midnight help balance"],jsonFields:{cli:"CLI metadata (name, version, description)",globalFlags:"Array of global flag descriptions",commands:"Array of command specs with jsonFields"}},{name:"manual",description:"Full reference manual (long form, paged through $PAGER)",usage:"midnight manual [--no-pager] [--raw] [--json]",flags:["--no-pager Print straight to stdout, do not pipe through less","--raw Strip ANSI colors (useful for piping to a file)","--json Emit the manual text wrapped in a JSON object"],examples:["midnight manual","midnight manual --no-pager | grep -i dust","midnight manual --raw > MANUAL.txt"],jsonFields:{name:"CLI package name",version:"CLI version",manual:"Manual text (with ANSI colors)"}}]});import{spawn as rS}from"node:child_process";function nS(e){return`${k(bu)}
|
|
1745
|
+
${k(We(e))}
|
|
1746
|
+
${k(bu)}
|
|
1747
|
+
`}function vt(e){return`
|
|
1748
|
+
${l(vu)}
|
|
1749
|
+
${k(We(e))}
|
|
1750
|
+
${l(vu)}
|
|
1751
|
+
`}function sS(e){let t=[];if(t.push(`${L(k("▸ "+e.name))}${" ".repeat(Math.max(2,22-e.name.length))}${e.description}`),t.push(""),t.push(` ${k("USAGE")}`),t.push(` ${e.usage}`),e.flags&&e.flags.length>0){t.push(""),t.push(` ${k("FLAGS")}`);for(let r of e.flags){let n=r.match(/^(\s*)(--[\w-]+(?:\s<[^>]+>)?)(\s+)(.*)$/);if(n)t.push(` ${M(n[2])}${n[3]}${n[4]}`);else if(/^[A-Za-z][\w -]*:/.test(r))t.push(` ${l(r)}`);else if(r.trim()==="")t.push("");else t.push(` ${r}`)}}if(e.examples&&e.examples.length>0){t.push(""),t.push(` ${k("EXAMPLES")}`);for(let r of e.examples)t.push(` ${l("$")} ${l(r)}`)}return t.join(`
|
|
1752
|
+
`)}function Ai(){let e=[];e.push(nS(`${kr} manual v${He}`)),e.push(""),e.push(`${k("NAME")}`),e.push(" midnight (mn) — wallet and development CLI for the Midnight blockchain"),e.push(""),e.push(`${k("SYNOPSIS")}`),e.push(" mn <command> [subcommand] [options]"),e.push(" midnight <command> [subcommand] [options]"),e.push(""),e.push(`${k("DESCRIPTION")}`),e.push(" midnight-wallet-cli is a standalone CLI that handles wallet"),e.push(" operations, contract deployment, and a development loop, on three"),e.push(" networks (undeployed, preprod, preview). Every command speaks"),e.push(" JSON via --json for use with AI agents and scripts. An MCP"),e.push(" server ships with the package."),e.push(""),e.push(`${k("INSTALLATION")}`),e.push(` ${l("$")} ${l("npm install -g midnight-wallet-cli")}`),e.push(""),e.push(" Optional dependencies:"),e.push(" Compact toolchain: https://docs.midnight.network/develop"),e.push(" Docker: for the local development network"),e.push(vt("CONCEPTS")),e.push(` ${k("Networks")}`),e.push(` ${L("undeployed")} Local Docker network. Free dev tokens, fast iteration.`),e.push(` ${L("preprod")} Public testnet. Persistent, real ZK proofs.`),e.push(` ${L("preview")} Public testnet, smaller scale.`),e.push(""),e.push(` ${k("Tokens")}`),e.push(` ${M("NIGHT")} Native asset. Used for transfers and contract value.`),e.push(` ${M("DUST")} Fee token. Generated from registered NIGHT UTXOs.`),e.push(""),e.push(` ${k("Wallets")}`),e.push(` Stored at ${l("~/.midnight/wallets/<name>.json")}`),e.push(" Three networks share one seed; each gets its own derived address."),e.push(" A tip-aware cache makes repeated reads finish in seconds."),e.push(""),e.push(` ${k("Shielded vs Unshielded")}`),e.push(` ${M("Unshielded")} addresses (mn_addr_*) are like UTXOs.`),e.push(` ${M("Shielded")} addresses (mn_shield-addr_*) hide amount and recipient.`),e.push(vt("COMMANDS"));for(let t of pr)e.push(sS(t)),e.push("");return e.push(vt("COMMON FLOWS")),e.push(` ${k("First wallet on undeployed")}`),e.push(` ${l("$")} ${l("mn localnet up")}`),e.push(` ${l("$")} ${l("mn wallet generate alice")}`),e.push(` ${l("$")} ${l("mn airdrop 1000 --wallet alice")}`),e.push(` ${l("$")} ${l("mn dust register --wallet alice")}`),e.push(` ${l("$")} ${l("mn balance --wallet alice")}`),e.push(""),e.push(` ${k("First wallet on preprod")}`),e.push(` ${l("$")} ${l("mn wallet generate alice --network preprod")}`),e.push(` ${l("# fund from the preprod faucet:")}`),e.push(` ${l("# https://faucet.preprod.midnight.network/")}`),e.push(` ${l("$")} ${l("mn dust register --wallet alice --network preprod")}`),e.push(` ${l("$")} ${l("mn balance --wallet alice --network preprod")}`),e.push(""),e.push(` ${k("Deploy and call a contract on undeployed")}`),e.push(" Prerequisite: a compiled artifact at ./src/managed/<name>/"),e.push(""),e.push(` ${l("$")} ${l("mn contract deploy --wallet alice")}`),e.push(` ${l(" → Address: 64da9d71cb…")}`),e.push(` ${l("$")} ${l("mn contract state --address 64da9d71cb… --wallet alice")}`),e.push(` ${l(' → { "round": 0 }')}`),e.push(` ${l("$")} ${l("mn contract call --address 64da9d71cb… --circuit increment --wallet alice")}`),e.push(` ${l("$")} ${l("mn contract state --address 64da9d71cb… --wallet alice")}`),e.push(` ${l(' → { "round": 1 }')}`),e.push(""),e.push(" Same artifact on preprod — swap one flag:"),e.push(` ${l("$")} ${l("mn contract deploy --network preprod --wallet alice")}`),e.push(""),e.push(` ${k("Transfer NIGHT between wallets")}`),e.push(` ${l("$")} ${l("mn transfer bob 100 --wallet alice")}`),e.push(` ${l(" shielded variant:")}`),e.push(` ${l("$")} ${l("mn transfer bob 100 --shielded --wallet alice")}`),e.push(vt("CONFIGURATION")),e.push(` ${k("Files")}`),e.push(` ${l("~/.midnight/config.json")} Persistent CLI settings`),e.push(` ${l("~/.midnight/wallets/")} Per-wallet JSON files (mode 0600)`),e.push(` ${l("~/.midnight/cache/<network>/")} Wallet sync cache, per network`),e.push(""),e.push(` ${k("Config keys")}`),e.push(` ${M("network")} Default network when --network is omitted`),e.push(` ${M("wallet")} Default wallet when --wallet is omitted`),e.push(` ${M("proof-server")} Override proof server URL`),e.push(` ${M("node")} Override substrate RPC URL`),e.push(` ${M("indexer-ws")} Override indexer WebSocket URL`),e.push(""),e.push(` ${k("Compatibility alias")}`),e.push(` ${M("network-id")} Resolves transparently to ${M("network")}.`),e.push(""),e.push(` ${k("Examples")}`),e.push(` ${l("$")} ${l("mn config set network preprod")}`),e.push(` ${l("$")} ${l("mn config get network")}`),e.push(` ${l("$")} ${l("mn config unset proof-server")}`),e.push(vt("JSON OUTPUT")),e.push(` Every command accepts ${M("--json")} for structured output on stdout.`),e.push(" Stderr keeps the chrome (spinners, headers); stdout stays parseable."),e.push(""),e.push(` ${l("$")} ${l("mn balance <addr> --json | jq -r .NIGHT")}`),e.push(` ${l("$")} ${l("mn wallet info alice --json")}`),e.push(""),e.push(` Stable JSON shapes are documented in ${l("docs/JSON_CONTRACT.md")}.`),e.push(" We promise not to break those without a major version bump."),e.push(vt("EXIT CODES")),e.push(` ${oS("0")} Success`),e.push(` ${l("1")} Unknown error`),e.push(` ${iS("2")} Invalid arguments (usage error, see yellow box on stderr)`),e.push(` ${l("3")} Wallet not found`),e.push(` ${l("4")} Network error`),e.push(` ${l("5")} Insufficient balance / DUST_REQUIRED`),e.push(` ${l("6")} Transaction rejected / STALE_UTXO / PROOF_TIMEOUT`),e.push(` ${l("7")} Cancelled by user`),e.push(""),e.push(` ${k("Stable error code strings")} (in JSON ${M("--json")} error output):`),e.push(` ${M("DUST_REQUIRED")} No dust available to pay fees`),e.push(` ${M("STALE_UTXO")} UTXO consumed concurrently, retry`),e.push(` ${M("PROOF_TIMEOUT")} Proof generation exceeded deadline`),e.push(` ${M("PROOF_FAILURE")} Proof server rejected the proof`),e.push(` ${M("INVALID_DUST_PROOF")} Stale commitment tree, run ${l("mn cache clear")}`),e.push(` ${M("STALE_CACHE")} Local cache out of sync, run ${l("mn cache clear")}`),e.push(` ${M("SYNC_TIMEOUT")} Wallet sync exceeded its deadline`),e.push(vt("TROUBLESHOOTING")),e.push(` ${k('Sync hangs forever or "applied > highest" error')}`),e.push(" Stale cache after a chain reset. Recover with:"),e.push(` ${l("$")} ${l("mn cache clear --wallet <name>")}`),e.push(""),e.push(` ${k('"DUST_REQUIRED" or "no dust available" on transfer')}`),e.push(" Wallet has NIGHT but no fee token. Register dust:"),e.push(` ${l("$")} ${l("mn dust register --wallet <name>")}`),e.push(" Then wait until status shows availability:"),e.push(` ${l("$")} ${l("mn dust status --wallet <name>")}`),e.push(""),e.push(` ${k('"Cannot find package @midnight-ntwrk/..." on contract deploy')}`),e.push(" The CLI bundles its own SDK. Reinstall to pick up the bundle:"),e.push(` ${l("$")} ${l("npm install -g midnight-wallet-cli@latest")}`),e.push(""),e.push(` ${k('"witnesses module not found" on contract deploy')}`),e.push(" Your contract declares witnesses but witnesses.js isn't built."),e.push(" Build the TypeScript source first:"),e.push(` ${l("$")} ${l("npm run build")}`),e.push(""),e.push(` ${k('"mn serve already running on port 9932 for network X"')}`),e.push(" A leftover serve from a previous network is in the way."),e.push(` ${l("$")} ${l("pkill -f 'mn serve'")}`),e.push(vt("SEE ALSO")),e.push(` ${L("mn help")} Brief command list`),e.push(` ${L("mn help <command>")} Help for one command (flags and examples)`),e.push(` ${L("mn help --agent")} Comprehensive AI / MCP reference`),e.push(""),e.push(` Repository: ${l("github.com/nel349/midnight-wallet-cli")}`),e.push(` JSON contract: ${l("docs/JSON_CONTRACT.md")}`),e.push(""),e.join(`
|
|
1753
|
+
`)}function oS(e){return`\x1B[32m${e}\x1B[0m`}function iS(e){return`\x1B[33m${e}\x1B[0m`}async function aS(e,t){if(!t||!process.stdout.isTTY){process.stdout.write(e);return}let r=process.env.PAGER??"less -R",[n,...s]=r.split(/\s+/);if(!n){process.stdout.write(e);return}await new Promise((o)=>{let i=rS(n,s,{stdio:["pipe","inherit","inherit"]});i.stdin.on("error",()=>{}),i.on("close",()=>o()),i.on("error",()=>{process.stdout.write(e),o()}),i.stdin.write(e),i.stdin.end()})}async function xi(e){let t=!N(e,"no-pager");if(N(e,"json")){await Promise.resolve();D({name:kr,version:He,manual:Ai()});return}if(N(e,"raw")){process.stdout.write(Ai().replace(/\x1b\[[0-9;]*m/g,""));return}await aS(Ai(),t)}var bu,vu;var ku=E(()=>{Ci();Cr();bu="═".repeat(63),vu="─".repeat(64)});async function Ri(e,t){lt(e);let r=A(e,"port"),n=r?parseInt(r,10):xt;if(Number.isNaN(n)||n<1||n>65535)throw Error(`Invalid port: "${r}" — must be 1-65535`);let s=N(e,"approve-all"),o=s||!N(e,"no-auto-approve-reads"),i=N(e,"json"),a=ce(ie(A(e,"wallet"))),c=Buffer.from(a.seed,"hex"),{name:d,config:u}=te({args:e}),p=a.addresses[d];Le(u,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},d),process.stderr.write(`
|
|
1754
|
+
`+W("DApp Connector Server")+`
|
|
1754
1755
|
|
|
1755
1756
|
`),process.stderr.write(C("Network",d)+`
|
|
1756
1757
|
`),process.stderr.write(C("Address",re(p,!0))+`
|
|
1757
1758
|
`),process.stderr.write(C("Port",String(n))+`
|
|
1758
1759
|
`),process.stderr.write(C("Auto-approve reads",s||o?"yes":"no")+`
|
|
1760
|
+
`),process.stderr.write(C("Auto-approve balancing",s?"yes":"no")+`
|
|
1759
1761
|
`),process.stderr.write(C("Auto-approve writes",s?"yes":"no")+`
|
|
1760
1762
|
`),process.stderr.write(`
|
|
1761
|
-
`);let f=
|
|
1762
|
-
`)}),g=
|
|
1763
|
-
`)},onDisconnect:(U)=>{process.stderr.write(l(` [${
|
|
1764
|
-
`),v?.revertPendingTxs(U.id).catch(()=>{})},onRequest:(U,
|
|
1765
|
-
`)},onResponse:(U,
|
|
1766
|
-
`),
|
|
1767
|
-
`)}else{let
|
|
1768
|
-
`);let _=F?.txHash;if(
|
|
1763
|
+
`);let f=he((m,w)=>{let y=pc();if(y)y.log(l(` SDK: ${w}`));else process.stderr.write(l(` SDK: ${w}`)+`
|
|
1764
|
+
`)}),g=Ce();if(Re(e))De();let h=G("Syncing wallet...");await me().withFacade(c,u,async({bundle:m})=>{h.stop("Wallet synced");let w=G("Waiting for dust..."),S=(await Vt(m)).dust?.availableCoins?.length>0;w.stop(S?"Dust ready":"Dust not yet available (writes may fail)");try{await je(p,d,m.facade)}catch{}if(t?.aborted)throw Error("Operation cancelled");let b,v;try{let R={approve:"Waiting for approval...",building:"Building transaction...",signing:"Signing...",proving:"Proving (ZK)...",submitting:"Submitting..."},P;if(v=ns({bundle:m,networkConfig:u,approvalOptions:{approveAll:s,autoApproveReads:o},callbacks:{onPhaseStart:(U,X,O)=>{if(O==="approve")return;let F=R[O]??`${O}...`;if(P)P.update(F);else P=G(F)},onPhaseComplete:(U,X,O,F)=>{if(O==="approve")return;if(O==="proving"||O==="submitting")P?.stop(`${O} ${Ni(F)}`),P=void 0}}}),b=Qn({port:n,handlers:v.handlers,onConnect:(U)=>{process.stderr.write(l(` [${Ei()}] `)+H("connected")+l(` ${U.id}`)+`
|
|
1765
|
+
`)},onDisconnect:(U)=>{process.stderr.write(l(` [${Ei()}] `)+J("disconnected")+l(` ${U.id}`)+`
|
|
1766
|
+
`),v?.revertPendingTxs(U.id).catch(()=>{})},onRequest:(U,X)=>{process.stderr.write(l(` [${Ei()}] ${U.id} #${U.requestCount} → ${X.method}`)+`
|
|
1767
|
+
`)},onResponse:(U,X,O,F,Q,de)=>{if(Q&&P)P.fail("Failed"),P=void 0;let I=Ni(O);if(Q){let x=Q.code==="Rejected"?"rejected by operator":Q.message;if(process.stderr.write(` ${J("✗")} ${l(`${U.id} ← ${X.method} (${I})`)} ${J(x)}
|
|
1768
|
+
`),Q.code!=="Rejected"&&Q.message)process.stderr.write(` ${l(" error:")} ${Q.message}
|
|
1769
|
+
`)}else{let x=de?.phases,T=x&&x.length>0?": "+x.map((K)=>`${K.phase} ${Ni(K.durationMs)}`).join(", "):"";process.stderr.write(` ${H("✓")} ${l(`${U.id} ← ${X.method} (${I}${T})`)}
|
|
1770
|
+
`);let _=F?.txHash;if(X.method==="submitTransaction"&&_)process.stderr.write(` ${l(" tx:")} ${L(String(_))}
|
|
1769
1771
|
`)}}}),process.stderr.write(`
|
|
1770
|
-
`+
|
|
1772
|
+
`+V()+`
|
|
1771
1773
|
`),process.stderr.write(" "+k(L(`Server ready — listening on ws://localhost:${n}`))+`
|
|
1772
1774
|
`),process.stderr.write(l(" Press Ctrl+C to stop")+`
|
|
1773
1775
|
|
|
1774
|
-
`),i)
|
|
1776
|
+
`),i)D({port:n,network:d,address:p,status:"listening"});if(await new Promise((U)=>{if(t)if(t.aborted)U();else t.addEventListener("abort",()=>U(),{once:!0})}),process.stderr.write(`
|
|
1775
1777
|
`+l(" Shutting down...")+`
|
|
1776
|
-
`),!v.hasPendingTxs())try{await
|
|
1778
|
+
`),!v.hasPendingTxs())try{await je(p,d,m.facade)}catch{}try{await b.close()}catch{}v.dispose(),v=void 0,b=void 0,process.stderr.write(l(" Server stopped.")+`
|
|
1777
1779
|
|
|
1778
|
-
`)}catch(R){if(h.fail("Failed"),b)try{await b.close()}catch{}throw v?.dispose(),R}},{syncMode:
|
|
1779
|
-
Run "mn dev" from a Midnight project directory (expected .compact files in ./, ./src, ./contract, or ./contract/src).`);let s=
|
|
1780
|
+
`)}catch(R){if(h.fail("Failed"),b)try{await b.close()}catch{}throw v?.dispose(),R}},{syncMode:Gt(d,N(e,"force-shielded"))?"full":"lite",requireStrictSync:!0,skipAutoSave:!0,signal:t,onStatus:(m)=>h.update(m),onSyncProgress:(m,w)=>{if(w>0){let y=Math.min(Math.round(m/w*100),100);h.update(y>=100?"Syncing wallet...":`Syncing wallet... ${y}%`)}},onSyncDetail:(m)=>h.update(`Syncing wallet... (waiting on: ${m})`)}).finally(()=>{g(),f()})}function Ei(){let e=new Date;return`${Ti(e.getHours())}:${Ti(e.getMinutes())}:${Ti(e.getSeconds())}`}function Ti(e){return e<10?"0"+e:String(e)}function Ni(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var Cu=E(()=>{ot();ke();pe();Ie();Ke();yt();at();bt();Vo();es();hn();ue();Ve()});import{existsSync as Eu,readFileSync as cS,readdirSync as dS,statSync as lS}from"node:fs";import{dirname as uS,join as $i,resolve as Au}from"node:path";function Tu(e){let t=Au(e),r=new Set,n=new Set;for(let p of fS){let f=Au(t,p);if(!Eu(f))continue;Iu(f,0,r,n)}if(r.size===0)throw Error(`No .compact source files found under ${t}
|
|
1781
|
+
Run "mn dev" from a Midnight project directory (expected .compact files in ./, ./src, ./contract, or ./contract/src).`);let s=yS([...n],t),o=s?.dir??t,i=s?.packageJson??Ru($i(t,"package.json")),a=s?.script??Nu(i),c=[...r].filter((p)=>xu(p,o)).sort(),d=[...n].filter((p)=>xu(p,o)).sort(),u=wS(i);return{projectRoot:o,sourceFiles:c.length>0?c:[...r].sort(),sourceDirs:d.length>0?d:[...n].sort(),compileScript:a,hasNpmCompileScript:a!==null,testScript:u,packageJson:i}}function wS(e){for(let t of mS)if($u(e,t))return t;return null}function xu(e,t){if(e===t)return!0;let r=t.endsWith("/")?t:t+"/";return e.startsWith(r)}function yS(e,t){for(let r of e){let n=r;while(!0){let s=$i(n,"package.json"),o=Ru(s),i=Nu(o);if(o&&i)return{dir:n,packageJson:o,script:i};if(n===t)break;let a=uS(n);if(a===n)break;n=a}}return null}function Nu(e){for(let t of pS)if($u(e,t))return t;return null}function Ru(e){if(!Eu(e))return null;try{let t=JSON.parse(cS(e,"utf-8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function $u(e,t){if(!e)return!1;let r=e.scripts;if(!r||typeof r!=="object")return!1;return typeof r[t]==="string"}function Iu(e,t,r,n){if(t>gS)return;let s;try{s=dS(e)}catch{return}for(let o of s){if(o.startsWith(".")||hS.has(o))continue;let i=$i(e,o),a=!1;try{a=lS(i).isDirectory()}catch{continue}if(a)Iu(i,t+1,r,n);else if(o.endsWith(".compact"))r.add(i),n.add(e)}}var pS,mS,fS,gS=4,hS;var _u=E(()=>{pS=["compact","compile"],mS=["test:dev","test"],fS=[".","contract/src","contract","src"],hS=new Set(["node_modules",".git","dist","build","managed","target"])});import{spawn as SS}from"node:child_process";async function Du(e){let{bin:t,args:r,label:n}=bS(e),s=Date.now();return new Promise((o,i)=>{let a=SS(t,r,{cwd:e.project.projectRoot,env:process.env,stdio:["ignore","pipe","pipe"]}),c="",d="";a.stdout?.on("data",(p)=>{c+=p.toString()}),a.stderr?.on("data",(p)=>{d+=p.toString()});let u=()=>{a.kill("SIGTERM")};if(e.signal)if(e.signal.aborted)u();else e.signal.addEventListener("abort",u,{once:!0});a.on("error",(p)=>{e.signal?.removeEventListener("abort",u),i(Error(`Failed to spawn "${n}": ${p.message}`))}),a.on("close",(p)=>{e.signal?.removeEventListener("abort",u),o({success:p===0,durationMs:Date.now()-s,command:n,stdout:c,stderr:d,exitCode:p??-1})})})}function bS(e){if(e.commandOverride){let{bin:t,args:r}=e.commandOverride;return{bin:t,args:r,label:[t,...r].join(" ")}}if(e.project.compileScript){let t=e.project.compileScript;return{bin:"npm",args:["run",t,"--silent"],label:`npm run ${t}`}}throw Error(`No compile script found in package.json.
|
|
1780
1782
|
Add one of:
|
|
1781
1783
|
"compact": "compact compile src/<your>.compact src/managed/<your>"
|
|
1782
1784
|
"compile": "compact compile src/<your>.compact src/managed/<your>"
|
|
1783
|
-
create-mn-app and midnight-starship templates ship with this script already wired.`)}var
|
|
1785
|
+
create-mn-app and midnight-starship templates ship with this script already wired.`)}var Pu=()=>{};import{spawn as vS}from"node:child_process";async function Ou(e){let{bin:t,args:r,label:n}=kS(e),s=Date.now();return new Promise((o,i)=>{let a=vS(t,r,{cwd:e.project.projectRoot,env:process.env,stdio:["ignore","inherit","inherit"]}),c=()=>{a.kill("SIGTERM")};if(e.signal)if(e.signal.aborted)c();else e.signal.addEventListener("abort",c,{once:!0});a.on("error",(d)=>{e.signal?.removeEventListener("abort",c),i(Error(`Failed to spawn "${n}": ${d.message}`))}),a.on("close",(d)=>{e.signal?.removeEventListener("abort",c),o({success:d===0,durationMs:Date.now()-s,command:n,exitCode:d??-1})})})}function kS(e){if(e.commandOverride){let{bin:r,args:n}=e.commandOverride;return{bin:r,args:n,label:[r,...n].join(" ")}}if(!e.project.testScript)throw Error(`No test script found in package.json.
|
|
1784
1786
|
Add a "test:dev" or "test" script that runs your contract tests
|
|
1785
|
-
(e.g. "test": "vitest run"), then press t again.`);let t=e.project.testScript;return{bin:"npm",args:["run",t,"--silent"],label:`npm run ${t}`}}var
|
|
1786
|
-
`)})};return t.on("data",s),{stop(){if(n)return;n=!0,t.off("data",s);try{t.setRawMode(r)}catch{}}}}var
|
|
1787
|
-
`+
|
|
1787
|
+
(e.g. "test": "vitest run"), then press t again.`);let t=e.project.testScript;return{bin:"npm",args:["run",t,"--silent"],label:`npm run ${t}`}}var Mu=()=>{};import{watch as CS}from"node:fs";import{join as AS}from"node:path";function Fu(e){let t=e.debounceMs??300,r=[],n=new Set,s=null,o=()=>{if(s=null,n.size===0)return;let i=[...n];n.clear();try{Promise.resolve(e.onChange(i)).catch((a)=>{e.onError?.(a instanceof Error?a:Error(String(a)))})}catch(a){e.onError?.(a instanceof Error?a:Error(String(a)))}};for(let i of e.dirs)try{let a=CS(i,{persistent:!0},(c,d)=>{if(!d)return;if(!d.endsWith(e.extension))return;if(n.add(AS(i,d)),s)clearTimeout(s);s=setTimeout(o,t)});a.on("error",(c)=>{e.onError?.(c instanceof Error?c:Error(String(c)))}),r.push(a)}catch(a){e.onError?.(a instanceof Error?a:Error(String(a)))}return{stop:()=>{if(s)clearTimeout(s),s=null;for(let i of r)try{i.close()}catch{}}}}var Lu=()=>{};async function Uu(e){if(ES())return e?.("Localnet already running"),{state:"already-running"};return e?.("Writing compose file"),tr(),e?.("Starting localnet containers"),ze("up -d"),e?.("Waiting for services to be healthy"),{state:rr(120000)?"started":"started-unhealthy"}}function xS(){try{return ct()}catch{return[]}}function ES(){let e=xS(),t=new Map(e.map((r)=>[r.name,r]));for(let r of Mo){let n=t.get(r);if(!n)return!1;if(n.state!=="running")return!1;if(n.health&&n.health!=="healthy")return!1}return!0}var ju=E(()=>{Kn()});import{existsSync as TS}from"node:fs";import{join as NS}from"node:path";import{homedir as RS}from"node:os";async function Hu(e){let t=[],r=$S();try{for(let n of e.names){if(e.signal?.throwIfAborted(),Gu(n)){e.onProgress?.(n,"done","reused"),t.push({name:n,state:"reused"});continue}e.onProgress?.(n,"creating","created"),await _S(n,e.signal),e.onProgress?.(n,"funding","created"),await DS(n,e.amountNight,e.signal),e.onProgress?.(n,"dust","created"),await PS(n,e.signal),e.onProgress?.(n,"done","created"),t.push({name:n,state:"created"})}}finally{IS(r)}return t}function $S(){try{return ft()}catch{return null}}function IS(e){if(!e)return;if(!Gu(e))return;try{Ir(e)}catch{}}function Gu(e){let t=NS(RS(),ae,Lt,`${e}.json`);return TS(t)}async function _S(e,t){let r={command:"wallet",subcommand:"generate",positionals:[e],flags:{network:"undeployed"}};await Promise.resolve().then(() => Vn());await z(nr,r,t)}async function DS(e,t,r){let n={command:"airdrop",subcommand:String(t),positionals:[],flags:{wallet:e,network:"undeployed"}};await Promise.resolve().then(() => Fn());await z(Qt,n,r)}async function PS(e,t){let r={command:"dust",subcommand:"register",positionals:[],flags:{wallet:e,network:"undeployed"}};await Promise.resolve().then(() => Un());await z(er,r,t)}var Wu,Bu=1000;var Ku=E(()=>{dn();ke();Wu=["dev-alice","dev-bob","dev-carol"]});function Ju(e){if(!OS)return{stop(){}};let t=process.stdin,r=t.isRaw;t.setRawMode(!0),t.resume(),t.setEncoding("utf8");let n=!1,s=(o)=>{if(n)return;if(o==="\x03"){e.onInterrupt();return}let i=o.toLowerCase(),a=e.actions[i];if(!a){e.onUnknown?.(o);return}Promise.resolve().then(a).catch((c)=>{let d=c instanceof Error?c:Error(String(c));if(e.onError)e.onError(i,d);else process.stderr.write(`key handler error (${i}): ${d.message}
|
|
1788
|
+
`)})};return t.on("data",s),{stop(){if(n)return;n=!0,t.off("data",s);try{t.setRawMode(r)}catch{}}}}var OS;var Vu=E(()=>{OS=typeof process.stdin.isTTY==="boolean"&&process.stdin.isTTY===!0});import{resolve as MS,relative as zu}from"node:path";async function Ii(e,t){let r=MS(e.positionals[0]??process.cwd());process.stderr.write(`
|
|
1789
|
+
`+W("mn dev")+`
|
|
1788
1790
|
|
|
1789
|
-
`);let n=
|
|
1791
|
+
`);let n=Tu(r);if(!n.compileScript)throw Error(`No compile script found in ${n.projectRoot}/package.json.
|
|
1790
1792
|
mn dev looks for a "compact" or "compile" npm script that invokes the
|
|
1791
1793
|
Compact toolchain. Add one of:
|
|
1792
1794
|
"scripts": { "compact": "compact compile src/my.compact src/managed/my" }
|
|
@@ -1795,50 +1797,50 @@ create-mn-app and midnight-starship templates ship with this already wired.`);pr
|
|
|
1795
1797
|
`),process.stderr.write(C("Sources",`${n.sourceFiles.length} .compact file(s)`)+`
|
|
1796
1798
|
`),process.stderr.write(C("Compile",`npm run ${n.compileScript}`)+`
|
|
1797
1799
|
|
|
1798
|
-
`);let s=
|
|
1800
|
+
`);let s=G("Checking localnet...");try{let S=await Uu((v)=>s.update(v)),b={"already-running":"Localnet already running",started:"Localnet started","started-unhealthy":"Localnet started (some services not yet healthy)"}[S.state];s.stop(b)}catch(S){throw s.fail("Localnet setup failed"),S}let o=G("Provisioning dev wallets...");try{let S=await Hu({names:Wu,amountNight:Bu,signal:t,onProgress:(P,q)=>{let U={creating:"generating",funding:"airdropping",dust:"registering dust",done:"ready"}[q];o.update(`${P}: ${U}`)}}),b=S.filter((P)=>P.state==="created").length,v=S.length-b,R=[b?`${b} created`:"",v?`${v} reused`:""].filter(Boolean).join(", ");o.stop(`Dev wallets: ${S.map((P)=>P.name).join(", ")} (${R})`)}catch(S){throw o.fail("Wallet provisioning failed"),S}let i=null,a=!1,c=!1,d=!1,u=!1;if(i=await Yu(n,t),!i.success)process.stderr.write(l(`
|
|
1799
1801
|
Fix the errors above and save — mn dev will recompile automatically.
|
|
1800
|
-
`));let p=async()=>{if(a||c)return;if(d){u=!0;return}d=!0;try{i=await
|
|
1802
|
+
`));let p=async()=>{if(a||c)return;if(d){u=!0;return}d=!0;try{i=await Yu(n,t)}finally{if(d=!1,u)u=!1,p()}},f=Fu({dirs:n.sourceDirs,extension:".compact",onChange:async(S)=>{let b=S.map((v)=>zu(n.projectRoot,v)).join(", ");process.stderr.write(`
|
|
1801
1803
|
`+l(` Changed: ${b}`)+`
|
|
1802
|
-
`),await p()},onError:(S)=>{process.stderr.write(
|
|
1804
|
+
`),await p()},onError:(S)=>{process.stderr.write(J(" watch error: ")+S.message+`
|
|
1803
1805
|
`)}});process.stderr.write(`
|
|
1804
|
-
`+
|
|
1805
|
-
`);let g=n.sourceDirs.map((S)=>
|
|
1806
|
+
`+V()+`
|
|
1807
|
+
`);let g=n.sourceDirs.map((S)=>zu(n.projectRoot,S)||".").join(", ");process.stderr.write(l(" Watching ")+L(g)+l(" — save to recompile.")+`
|
|
1806
1808
|
`);let h=n.testScript?k("[t]")+l(` test (${n.testScript}) `):"";process.stderr.write(l(" ")+k("[d]")+l(" deploy ")+h+k("[q]")+l(` quit
|
|
1807
1809
|
|
|
1808
|
-
`));let m=new AbortController,w=()=>{if(!m.signal.aborted)m.abort()},y=
|
|
1810
|
+
`));let m=new AbortController,w=()=>{if(!m.signal.aborted)m.abort()},y=Ju({actions:{d:async()=>{if(a){process.stderr.write(l(` Deploy already in flight — ignoring key press.
|
|
1809
1811
|
`));return}if(c){process.stderr.write(l(` Tests are running — wait for them to finish before deploying.
|
|
1810
1812
|
`));return}if(!i?.success){process.stderr.write(M(` Cannot deploy — last compile did not succeed. Fix and save first.
|
|
1811
|
-
`));return}a=!0;try{await
|
|
1813
|
+
`));return}a=!0;try{await FS(n)}finally{a=!1}},t:async()=>{if(c){process.stderr.write(l(` Tests already in flight — ignoring key press.
|
|
1812
1814
|
`));return}if(a){process.stderr.write(l(` Deploy in flight — wait for it to finish before running tests.
|
|
1813
1815
|
`));return}if(!n.testScript){process.stderr.write(M(` No test script found. Add "test:dev" or "test" to package.json.
|
|
1814
1816
|
`));return}if(!i?.success){process.stderr.write(M(` Cannot run tests — last compile did not succeed. Fix and save first.
|
|
1815
|
-
`));return}c=!0;try{await
|
|
1817
|
+
`));return}c=!0;try{await LS(n,m.signal)}finally{c=!1}},q:()=>w()},onInterrupt:w});await new Promise((S)=>{let b=()=>{y.stop(),f.stop(),process.stderr.write(`
|
|
1816
1818
|
`+l(" mn dev stopped.")+`
|
|
1817
|
-
`),S()};if(m.signal.aborted){b();return}if(m.signal.addEventListener("abort",b,{once:!0}),t?.aborted){w();return}t?.addEventListener("abort",w,{once:!0})})}async function
|
|
1819
|
+
`),S()};if(m.signal.aborted){b();return}if(m.signal.addEventListener("abort",b,{once:!0}),t?.aborted){w();return}t?.addEventListener("abort",w,{once:!0})})}async function FS(e){let t=process.cwd();if(t!==e.projectRoot)try{process.chdir(e.projectRoot)}catch{}try{let r=await US(e.projectRoot);if(r.length>0&&!is(e.projectRoot)){let s=as({projectRoot:e.projectRoot,witnessNames:r});process.stderr.write(M(` ✗ Cannot auto-deploy:
|
|
1818
1820
|
`));for(let o of s.split(`
|
|
1819
1821
|
`))process.stderr.write(l(` ${o}
|
|
1820
|
-
`));return}let n=
|
|
1821
|
-
`)}catch(s){n.fail("Deploy failed");let o=s instanceof Error?s.message:String(s);process.stderr.write(
|
|
1822
|
-
`)}}finally{if(process.cwd()!==t)try{process.chdir(t)}catch{}}}async function
|
|
1822
|
+
`));return}let n=G(`Deploying with ${qu} on ${Xu}...`);try{await Promise.resolve().then(() => gs());let o=await z(ir,{command:"contract",subcommand:"deploy",positionals:[],flags:{wallet:qu,network:Xu}});n.stop("Deployed");let i=typeof o.address==="string"?o.address:"(unknown)";process.stderr.write(` ${l("address")} ${L(i)}
|
|
1823
|
+
`)}catch(s){n.fail("Deploy failed");let o=s instanceof Error?s.message:String(s);process.stderr.write(J(" "+o)+`
|
|
1824
|
+
`)}}finally{if(process.cwd()!==t)try{process.chdir(t)}catch{}}}async function LS(e,t){process.stderr.write(l(`
|
|
1823
1825
|
Running npm run ${e.testScript}...
|
|
1824
|
-
`));try{let r=await
|
|
1825
|
-
`);else process.stderr.write(` ${l("─")} ${
|
|
1826
|
-
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(
|
|
1827
|
-
`)}}async function
|
|
1828
|
-
`),process.stderr.write(M(
|
|
1829
|
-
`);return n}catch(n){r.fail("Compile error");let s=n instanceof Error?n.message:String(n);return process.stderr.write(
|
|
1830
|
-
`),{success:!1,durationMs:0,command:"",stdout:"",stderr:s,exitCode:-1}}}function
|
|
1826
|
+
`));try{let r=await Ou({project:e,signal:t});if(r.success)process.stderr.write(` ${l("─")} Tests passed ${l(`(${As(r.durationMs)})`)}
|
|
1827
|
+
`);else process.stderr.write(` ${l("─")} ${J("Tests failed")} ${l(`(exit ${r.exitCode}, ${As(r.durationMs)})`)}
|
|
1828
|
+
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(J(" Test runner error: ")+n+`
|
|
1829
|
+
`)}}async function US(e){try{await Promise.resolve().then(() => Jr());let{info:r}=qe(e);return r.witnesses.map((n)=>n.name)}catch{return[]}}async function Yu(e,t){let r=G("Compiling...");try{let n=await Du({project:e,signal:t});if(n.success)r.stop(`Compiled ${l(`(${As(n.durationMs)})`)}`);else if(r.fail(`Compile failed ${l(`(${As(n.durationMs)})`)}`),n.stderr.trim())process.stderr.write(l(" ─ stderr ─")+`
|
|
1830
|
+
`),process.stderr.write(M(jS(n.stderr.trim()," "))+`
|
|
1831
|
+
`);return n}catch(n){r.fail("Compile error");let s=n instanceof Error?n.message:String(n);return process.stderr.write(J(" "+s)+`
|
|
1832
|
+
`),{success:!1,durationMs:0,command:"",stdout:"",stderr:s,exitCode:-1}}}function As(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(2)}s`}function jS(e,t){return e.split(`
|
|
1831
1833
|
`).map((r)=>t+r).join(`
|
|
1832
|
-
`)}var
|
|
1833
|
-
`),process.exit(0);if(N(e,"help")||N(e,"h"))e.command="help";let r=e.command??"help";if(
|
|
1834
|
+
`)}var qu="dev-alice",Xu="undeployed";var Zu=E(()=>{_u();Pu();Mu();Lu();ju();Ku();Vu();cs();dn();ue();Ve()});ue();Os();Be();Cr();ke();qs();var Qu=new Set(["airdrop","transfer","dust","balance","serve","test","contract","dev"]);if(process.argv.includes("--mcp"))await _r(),await Promise.resolve().then(() => (du(),{}));else{let o=function(){n.abort(),setTimeout(()=>process.exit(130),5000).unref()},e=_i(),t=N(e,"json");if(N(e,"version")||N(e,"v"))process.stdout.write(He+`
|
|
1835
|
+
`),process.exit(0);if(N(e,"help")||N(e,"h"))e.command="help";let r=e.command??"help";if(Qu.has(r))await _r();ya();let n=new AbortController,{signal:s}=n;process.on("SIGINT",o),process.on("SIGTERM",o);async function i(){switch(r){case"help":{await Promise.resolve().then(() => Ci());return ki(e)}case"manual":{await Promise.resolve().then(() => ku());return xi(e)}case"wallet":{await Promise.resolve().then(() => Vn());return nr(e)}case"generate":{process.stderr.write(`
|
|
1834
1836
|
Note: "midnight generate" is deprecated.
|
|
1835
1837
|
Use "midnight wallet generate <name>" instead.
|
|
1836
1838
|
|
|
1837
|
-
`);
|
|
1838
|
-
Run "midnight help" to see available commands.`)}}i().then(()=>{if(
|
|
1839
|
-
`+
|
|
1839
|
+
`);await Promise.resolve().then(() => Xs());return un(e)}case"info":{await Promise.resolve().then(() => Ys());return pn(e)}case"balance":{await Promise.resolve().then(() => xo());return Dn(e)}case"address":{await Promise.resolve().then(() => Eo());return Pn(e)}case"genesis-address":{await Promise.resolve().then(() => To());return On(e)}case"inspect-cost":{await Promise.resolve().then(() => No());return Mn(e)}case"config":{await Promise.resolve().then(() => Io());return Wn(e)}case"cache":{await Promise.resolve().then(() => $o());return jn(e)}case"airdrop":{await Promise.resolve().then(() => Fn());return Qt(e,s)}case"transfer":{await Promise.resolve().then(() => Ro());return Ln(e,s)}case"dust":{await Promise.resolve().then(() => Un());return er(e,s)}case"localnet":{await Promise.resolve().then(() => Fo());return Jn(e)}case"status":throw Error('The "status" command is currently being reworked. Check back soon.');case"serve":{await Promise.resolve().then(() => Cu());return Ri(e,s)}case"test":{await Promise.resolve().then(() => gi());return vs(e,s)}case"contract":{await Promise.resolve().then(() => gs());return ir(e,s)}case"dev":{await Promise.resolve().then(() => Zu());return Ii(e,s)}default:throw new Z(`Unknown command: "${r}"
|
|
1840
|
+
Run "midnight help" to see available commands.`)}}i().then(()=>{if(Qu.has(r))process.exit(0)}).catch((a)=>{let c=ea(a.message);if(ta(a)){if(t)Fs(a,"INVALID_ARGS",Ps);else process.stderr.write(`
|
|
1841
|
+
`+Qi(c,'Run "midnight manual" for the full reference, or "midnight help <command>" for one command.')+`
|
|
1840
1842
|
|
|
1841
|
-
`);process.exit(
|
|
1842
|
-
`+
|
|
1843
|
+
`);process.exit(Ps)}else if(t){let{exitCode:d,errorCode:u}=br(a);Fs(a,u,d),process.exit(d)}else{process.stderr.write(`
|
|
1844
|
+
`+Zi(c,'Run "midnight help" for usage information.')+`
|
|
1843
1845
|
|
|
1844
|
-
`);let{exitCode:d}=
|
|
1846
|
+
`);let{exitCode:d}=br(a);process.exit(d)}})}
|