midnight-wallet-cli 0.5.5 → 0.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/mcp-server.js +212 -212
- package/dist/wallet.js +284 -283
- package/package.json +7 -7
package/dist/wallet.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as kp}from"node:module";var Sp=Object.defineProperty;var bp=(e)=>e;function vp(e,t){this[e]=bp.bind(null,t)}var fe=(e,t)=>{for(var r in t)Sp(e,r,{get:t[r],enumerable:!0,configurable:!0,set:vp.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 Is=kp(import.meta.url);function Hi(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 x(e,t){let r=e.flags[t];if(r===void 0||r===!0)return;return r}function T(e,t){return t in e.flags}function Ie(e){return T(e,"verbose")}function ct(e){return T(e,rn)&&!T(e,fr)}function dt(e){if(T(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 nn(e,t,r){let n=
|
|
5
|
-
`);for(let g of f)o.push(...
|
|
6
|
-
`)}function
|
|
4
|
+
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function nn(e,t,r){let n=x(e,t);if(n===void 0)throw Error(`Missing required flag: --${t} <${r}>`);return n}var rn="_minimal",fr="_full";function Ct(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 tt="0000000000000000000000000000000000000000000000000000000000000001",gr="0000000000000000000000000000000000000000000000000000000000000000",vt="/api/v4/graphql",kt="/api/v4/graphql/ws",$s=6,Ds=1e6,Gi=300000000000000n,Ki=5,hr=800000000000000n,Ji=5000000000n,Vi=8267n,zi=10800n,qi=300000,_s=30000,Xi=1e4,Ps=120000,sn=300000,Os=60000,Yi=16384,Zi=0.7,Qi=512,wr=10,ea=3,ta=600000,Ms=15000,ra=115,ce=".midnight",on="wallet.json",na="config.json",ye=448,Se=384,sa="localnet",Fs=1,$e="cache",Lt="wallets",yr="default",Sr=10,Ls=3000,oa=120000,At=9932,an="https://midnight-comp-tracker.vercel.app";function lt(){return!("NO_COLOR"in process.env)}function Ut(e,t){if(!lt())return e;return`\x1B[38;5;${t}m${e}\x1B[0m`}function k(e){if(!lt())return e;return`\x1B[1m${e}\x1B[0m`}function u(e){if(!lt())return e;return`\x1B[2m${e}\x1B[0m`}function U(e){return Ut(e,38)}function V(e){return Ut(e,196)}function H(e){return Ut(e,40)}function F(e){return Ut(e,226)}function je(e){return Ut(e,15)}function rt(e){return Ut(e,245)}function j(e,t=aa){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 z(e=aa){return u("─".repeat(e))}function A(e,t,r=16){let n=(e+":").padEnd(r);return` ${rt(n)}${t}`}function Et(e){let t=e<0n,r=t?-e:e,n=BigInt(10**$s),s=r/n,i=(r%n).toString().padStart($s,"0");return`${t?"-":""}${s}.${i}`}function cn(e){return`${Et(e)} NIGHT`}function Wt(e){let t=e<0n,r=t?-e:e,n=10n**BigInt(ia),s=r/n,a=(r%n).toString().padStart(ia,"0").replace(/0+$/,"").padEnd(6,"0");return`${t?"-":""}${s}.${a}`}function br(e){return`${Wt(e)} DUST`}function ne(e,t=!1){let r=t&&e.length>20?e.slice(0,10)+"…"+e.slice(-8):e;return U(r)}function Cp(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 Ap(e,t){if(jt(e).length<=t)return[e];let n=e.split(/(\s+)/).flatMap((a)=>jt(a).length>t?Cp(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 ca(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(...Ap(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,l=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,...l,d].join(`
|
|
6
|
+
`)}function da(e,t){let n=e.split(`
|
|
7
7
|
`).map((s,o)=>o===0?V(k("Error: "))+V(s):V(s));if(t)n.push(""),n.push(u("Suggestion: ")+t);return n.join(`
|
|
8
|
-
`)}function
|
|
8
|
+
`)}function la(e,t){let s=e.replace(/^Usage:\s*/i,"").split(`
|
|
9
9
|
`).map((o,i)=>i===0?F(k("Usage: "))+F(o):F(o));if(t)s.push(""),s.push(u("Hint: ")+t);return s.join(`
|
|
10
10
|
`)}function ut(e,t){let n=[`${H("✓")} ${e}`];if(t)n.push(A("Transaction",U(t)));return n.join(`
|
|
11
|
-
`)}var
|
|
12
|
-
`;if(kr)kr(t);else process.stdout.write(t)}function
|
|
13
|
-
`;if(kr)kr(n);else process.stdout.write(n)}var kr=null;var dn;var
|
|
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
|
|
15
|
-
`,{mode:Se})}function
|
|
16
|
-
Valid keys: ${ln.join(", ")}`)}function
|
|
17
|
-
Valid networks: preprod, preview, undeployed`);
|
|
18
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(Nr.has(n)){if(
|
|
11
|
+
`)}var aa=60,ia=15,jt=(e)=>e.replace(/\x1b\[[0-9;]*m/g,"");var ue=()=>{};function vr(e){if(e.code===be.UNSUPPORTED_NODE)return{exitCode:1,errorCode:be.UNSUPPORTED_NODE};let t=(e.message??"").toLowerCase();if(t.includes("operation cancelled")||t.includes("operation aborted")||t==="cancelled"||t==="aborted")return{exitCode:7,errorCode:be.CANCELLED};if(t.includes("wallet file not found")||t.includes("wallet")&&t.includes("not found"))return{exitCode:3,errorCode:be.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:be.INVALID_ARGS};if(t.includes("proof")&&t.includes("timeout"))return{exitCode:6,errorCode:be.PROOF_TIMEOUT};if(t.includes("stale utxo")||t.includes("error code 115")||t.includes("errorcode: 115"))return{exitCode:6,errorCode:be.STALE_UTXO};if(t.includes("error 170")||t.includes("errorcode: 170")||t.includes("invaliddustspendproof"))return{exitCode:6,errorCode:be.INVALID_DUST_PROOF};if(t.includes("stale cache")||t.includes("chain reset")||t.includes("chainid mismatch")||t.includes("applied > highest"))return{exitCode:6,errorCode:be.STALE_CACHE};if(t.includes("failed to prove"))return{exitCode:6,errorCode:be.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:be.SYNC_TIMEOUT};if(t.includes("no dust")||t.includes("dust")&&(t.includes("required")||t.includes("available")||t.includes("insufficient")))return{exitCode:5,errorCode:be.DUST_REQUIRED};if(t.includes("insufficient")||t.includes("not enough"))return{exitCode:5,errorCode:be.INSUFFICIENT_BALANCE};if(t.includes("rejected")||t.includes("transaction failed"))return{exitCode:6,errorCode:be.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:be.NETWORK_ERROR};return{exitCode:1,errorCode:be.UNKNOWN}}function ua(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 Us=2,be;var js=E(()=>{be={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",UNSUPPORTED_NODE:"UNSUPPORTED_NODE",UNKNOWN:"UNKNOWN"}});function pa(e){return e instanceof Y}var Y;var We=E(()=>{Y=class Y extends Error{constructor(e){super(e);this.name="UsageError",Object.setPrototypeOf(this,Y.prototype)}}});function Ws(e){kr=e}function P(e){let t=JSON.stringify(e)+`
|
|
12
|
+
`;if(kr)kr(t);else process.stdout.write(t)}function Bs(e,t,r){let n=JSON.stringify({error:!0,code:t,message:e.message,exitCode:r})+`
|
|
13
|
+
`;if(kr)kr(n);else process.stdout.write(n)}var kr=null;var dn;var ma=E(()=>{dn={name:"midnight-wallet-cli",version:"0.5.6",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:">=22",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","@midnight-ntwrk/wallet-sdk-utilities":"1.1.1","@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.6","@nel349/dust-sync-darwin-x64":"0.5.6","@nel349/dust-sync-linux-x64":"0.5.6","@nel349/dust-sync-linux-arm64":"0.5.6","@nel349/dust-sync-win32-x64":"0.5.6"}}});var Cr,Be,fa;var Ar=E(()=>{ma();Cr=dn.name,Be=dn.version,fa=dn.description});import{execSync as xp}from"child_process";function xe(e){return ga.includes(e)}function Er(e){return{...Tp[e]}}function xr(){return ga}function Np(){try{let e=xp('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 ha(e){let t=Er(e);if(e==="undeployed"){let r=Np();if(r.indexerPort)t.indexer=`http://localhost:${r.indexerPort}${vt}`,t.indexerWS=`ws://localhost:${r.indexerPort}${kt}`;if(r.nodePort)t.node=`ws://localhost:${r.nodePort}`;if(r.proofServerPort)t.proofServer=`http://localhost:${r.proofServerPort}`}return t}function Me(e,t,r,n){let s=Te(n),o=Hs(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 Tp,ga;var De=E(()=>{Bt();Tp={preprod:{indexer:`https://indexer.preprod.midnight.network${vt}`,indexerWS:`wss://indexer.preprod.midnight.network${kt}`,node:"wss://rpc.preprod.midnight.network",proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:`https://indexer.preview.midnight.network${vt}`,indexerWS:`wss://indexer.preview.midnight.network${kt}`,node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:`http://localhost:8088${vt}`,indexerWS:`ws://localhost:8088${kt}`,node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},ga=["preprod","preview","undeployed"]});import*as nt from"fs";import*as Gs from"path";import{homedir as Rp}from"os";function Ks(e){return Ip[e]??e}function $p(e){return/^(https?|wss?):\/\/\S+/.test(e)}function wa(e){return e??Gs.join(Rp(),ce)}function ya(e){return Gs.join(wa(e),na)}function Dp(e){let t=wa(e);if(!nt.existsSync(t))nt.mkdirSync(t,{recursive:!0,mode:ye})}function Te(e){let t=ya(e);if(!nt.existsSync(t))return{...Tr};let r;try{r=nt.readFileSync(t,"utf-8")}catch{return{...Tr}}let n;try{n=JSON.parse(r)}catch{return{...Tr}}let s={network:n.network&&xe(n.network)?n.network:Tr.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 Nr){let l=a[d];if(l&&typeof l==="string")c[d]=l}if(Object.keys(c).length>0)o[i]=c}if(Object.keys(o).length>0)s.networks=o}return s}function Hs(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 Rr(e,t){Dp(t);let r=ya(t);nt.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
15
|
+
`,{mode:Se})}function Sa(e,t){let r=Ks(e),n=Te(t);if(r==="network")return n.network;if(r==="wallet")return n.wallet??"(not set)";if(Nr.has(r)){let o=Hs(n,n.network)[r];return typeof o==="string"?o:"(not set)"}throw Error(`Unknown config key: "${e}"
|
|
16
|
+
Valid keys: ${ln.join(", ")}`)}function _p(e,t){let r={...e.networks?.[t]??{}},n=!1;for(let s of Nr){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 ba(e,t,r){let n=Ks(e),s=Te(r);if(n==="network"){if(!xe(t))throw Error(`Invalid network: "${t}"
|
|
17
|
+
Valid networks: preprod, preview, undeployed`);_p(s,s.network),s.network=t}else if(n==="wallet"){if(!Ct(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(Nr.has(n)){if(!$p(t))throw Error(`Invalid URL for "${e}": "${t}"
|
|
19
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}"
|
|
20
|
-
Valid keys: ${ln.join(", ")}`);Rr(s,r)}function
|
|
21
|
-
Valid keys: ${ln.join(", ")}`);Rr(n,t)}function
|
|
22
|
-
`,{mode:Se})}catch{}}function
|
|
20
|
+
Valid keys: ${ln.join(", ")}`);Rr(s,r)}function va(e,t){let r=Ks(e),n=Te(t);if(r==="network")n.network=Tr.network;else if(r==="wallet")delete n.wallet;else if(Nr.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: ${ln.join(", ")}`);Rr(n,t)}function Js(){return ln}var Tr,ln,Ip,Nr;var Bt=E(()=>{De();Tr={network:"undeployed"},ln=["network","proof-server","node","indexer-ws","wallet"],Ip={"network-id":"network"};Nr=new Set(["proof-server","node","indexer-ws"])});import{HDWallet as Pp,Roles as Vs}from"@midnight-ntwrk/wallet-sdk-hd";function zs(e,t){let r=Pp.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 xt(e){return zs(e,Vs.Zswap)}function ka(e){return zs(e,Vs.NightExternal)}function pt(e){return zs(e,Vs.Dust)}var Tt=()=>{};import{HDWallet as Op,Roles as Mp}from"@midnight-ntwrk/wallet-sdk-hd";import{createKeystore as Fp,PublicKey as Lp}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{MidnightBech32m as Up,ShieldedAddress as jp,ShieldedCoinPublicKey as Wp,ShieldedEncryptionPublicKey as Bp}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as qs}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as Ca from"@midnight-ntwrk/ledger-v8";function ve(e,t,r=0){let n=Aa[t],s=Op.fromSeed(e);if(s.type!=="seedOk")throw Error("Invalid seed for HD wallet");let o=s.hdWallet.selectAccount(0).selectRole(Mp.NightExternal).deriveKeyAt(r);if(o.type==="keyOutOfBounds")throw Error(`Key index ${r} out of bounds`);let i=Fp(o.key,n);return Lp.fromKeyStore(i).address}function Nt(e,t=0){let r={};for(let n of xr())r[n]=ve(e,n,t);return r}function Ir(e){let t=$r(e),r={};for(let n of xr()){let s=Aa[n];r[n]=Up.encode(s,t).asString()}return r}function $r(e){let t=xt(e),r=Ca.ZswapSecretKeys.fromSeed(t);return new jp(new Wp(Buffer.from(r.coinPublicKey,"hex")),new Bp(Buffer.from(r.encryptionPublicKey,"hex")))}var Aa;var He=E(()=>{De();Tt();Aa={preprod:qs.NetworkId.PreProd,preview:qs.NetworkId.Preview,undeployed:qs.NetworkId.Undeployed}});import*as X from"fs";import*as ge from"path";import{homedir as Hp}from"os";function Ht(e,t,r){let n=ge.resolve(e);if(!X.existsSync(n))return;try{let s=JSON.parse(X.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;X.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
22
|
+
`,{mode:Se})}catch{}}function Xs(){return ge.join(Hp(),ce)}function Rt(){return ge.join(Xs(),Lt)}function Ys(){return ge.join(Xs(),on)}function xa(){let e=Xs();if(!X.existsSync(e))X.mkdirSync(e,{recursive:!0,mode:ye})}function Gp(){xa();let e=Rt();if(!X.existsSync(e))X.mkdirSync(e,{recursive:!0,mode:ye})}function Kp(e){return e.includes("/")||e.includes("\\")||e.endsWith(".json")}function oe(e){if(e!==void 0){if(Kp(e))return ge.resolve(e);return ge.join(Rt(),`${e}.json`)}let r=Te().wallet??yr;return ge.join(Rt(),`${r}.json`)}function mt(){return Te().wallet??yr}function Dr(e){if(!Ct(e))throw Error(`Invalid wallet name: "${e}"
|
|
23
23
|
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=ge.join(Rt(),`${e}.json`);if(!X.existsSync(t))throw Error(`Wallet "${e}" not found.
|
|
24
|
-
Run "midnight wallet list" to see available wallets.`);let r=Te();r.wallet=e,Rr(r)}function
|
|
24
|
+
Run "midnight wallet list" to see available wallets.`);let r=Te();r.wallet=e,Rr(r)}function Zs(){let e=Rt();if(!X.existsSync(e))return[];let t=mt();return X.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(X.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=Nt(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=Ir(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 Jp(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 Ta(e){return Jp(Zs(),e)}function Na(e){if(!Ct(e))throw Error(`Invalid wallet name: "${e}"
|
|
25
25
|
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=Rt(),r=ge.join(t,`${e}.json`);if(!X.existsSync(r))throw Error(`Wallet "${e}" not found.
|
|
26
26
|
Run "midnight wallet list" to see available wallets.`);let n=mt();if(e===n)throw Error(`Cannot remove the active wallet "${e}".
|
|
27
27
|
Switch to another wallet first: midnight wallet use <other-wallet>`);if(X.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>");X.unlinkSync(r)}function
|
|
28
|
+
`+"Create another wallet first: midnight wallet generate <name>");X.unlinkSync(r)}function Ra(){let e=Ys();if(!X.existsSync(e))return;let t=Rt();if(X.existsSync(t)){if(X.readdirSync(t).filter((o)=>o.endsWith(".json")).length>0)return}Gp();let r=ge.join(t,`${yr}.json`);X.copyFileSync(e,r),X.chmodSync(r,Se),X.unlinkSync(e);let n=Te();n.wallet=yr,Rr(n)}function de(e){let t=e?ge.resolve(e):Ys();if(!X.existsSync(t))throw Error(`Wallet file not found: ${t}
|
|
29
29
|
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=X.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((l)=>!n[l]);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=Nt(c),l={seed:n.seed,addresses:d,createdAt:n.createdAt};if(n.mnemonic)l.mnemonic=n.mnemonic;let p=
|
|
31
|
-
`,{mode:Se}),l}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=
|
|
32
|
-
`,{mode:Se})}catch{}return s}function
|
|
33
|
-
`,{mode:Se}),r}var
|
|
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((l)=>!n[l]);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=Nt(c),l={seed:n.seed,addresses:d,createdAt:n.createdAt};if(n.mnemonic)l.mnemonic=n.mnemonic;let p=Ea(n,c);if(p)l.shieldedAddresses=p;let f={...n,addresses:d};if(p)f.shieldedAddresses=p,delete f.shieldedAddress;return X.writeFileSync(t,JSON.stringify(f,null,2)+`
|
|
31
|
+
`,{mode:Se}),l}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=Ea(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,X.writeFileSync(t,JSON.stringify(c,null,2)+`
|
|
32
|
+
`,{mode:Se})}catch{}return s}function Ea(e,t){let r;try{r=Ir(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 un(e,t){let r=t?ge.resolve(t):Ys();if(!t)xa();else{let n=ge.dirname(r);if(!X.existsSync(n))X.mkdirSync(n,{recursive:!0,mode:ye})}return X.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
33
|
+
`,{mode:Se}),r}var ke=E(()=>{Bt();He()});import Vp from"node:v8";import zp from"node:os";import{spawn as qp}from"node:child_process";function Yp(e){let t=e.desiredMb??Yi,r=e.ramFraction??Zi,n=e.minGainMb??Qi;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[Qs]){Qp();return}let e=process.env[Xp],t=e!==void 0?Number(e):void 0,r=Yp({totalMb:Math.floor(zp.totalmem()/Ia),currentLimitMb:Math.floor(Vp.getHeapStatistics().heap_size_limit/Ia),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=qp(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[Qs]:"1"}});Zp(s),s.on("error",()=>{process.env[Qs]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function Zp(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 Qp(){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 Qs="MN_HEAP_BUMPED",Xp="MN_MAX_OLD_SPACE_MB",Ia=1048576;var eo=()=>{};function pn(e=process.versions){if(e.bun!==void 0)return;let t=Number(e.node.split(".")[0]);if(!Number.isInteger(t)||t<22)throw new to(e.node)}var to;var ro=E(()=>{to=class to extends Error{code="UNSUPPORTED_NODE";constructor(e){super(`midnight-wallet-cli needs Node.js 22 or newer; this is Node.js ${e}. The Midnight wallet SDK uses features older versions lack. Install a current Node.js (https://nodejs.org) and run the command again.`);this.name="UnsupportedNodeError",Object.setPrototypeOf(this,to.prototype)}}});async function q(e,t,r){let n=[];Ws((s)=>n.push(s));try{if(t.flags.json=!0,!(rn in t.flags))t.flags[rn]=!0;await e(t,r);let s=n.join("").trim();if(!s)return{};return JSON.parse(s)}finally{Ws(null)}}var mn=()=>{};function $a(e){let t=e.split(`
|
|
34
34
|
|
|
35
35
|
`)[0].trim(),r=t.split(`
|
|
36
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(`
|
|
37
|
-
`).trim()||t}import{randomUUID as
|
|
38
|
-
Valid networks: ${
|
|
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(!
|
|
37
|
+
`).trim()||t}import{randomUUID as em}from"node:crypto";function Da(e={}){let t=e.ttlMs??tm,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=em(),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 tm=300000;var _a=()=>{};function _e(e){let t=x(e.args,"network");if(t!==void 0){if(!xe(t))throw Error(`Invalid network: "${t}"
|
|
38
|
+
Valid networks: ${xr().join(", ")}`);return t}let r=Te(e.configDir);if(r.network&&xe(r.network))return r.network;return"undeployed"}function te(e){let t=_e(e),r=ha(t);return{name:t,config:r}}var pe=E(()=>{De();Bt()});var Fa={};fe(Fa,{default:()=>gn});import*as Ma from"fs";import*as fn from"path";import{homedir as rm}from"os";import{generateMnemonic as nm,mnemonicToSeedSync as Pa,validateMnemonic as sm}from"@scure/bip39";import{wordlist as Oa}from"@scure/bip39/wordlists/english.js";async function gn(e){let t=_e({args:e}),r=x(e,"output"),n=x(e,"seed"),s=process.env.MN_SEED?.trim(),o=n??(s?s:void 0),i=x(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?fn.resolve(r):fn.join(rm(),ce,on);if(Ma.existsSync(a)&&!T(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(!sm(i,Oa))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");d=i,c=Buffer.from(Pa(d))}else d=nm(Oa,256),c=Buffer.from(Pa(d));let l=Nt(c),p=l[t],f={seed:c.toString("hex"),addresses:l,createdAt:new Date().toISOString()};if(d)f.mnemonic=d;let g=un(f,r);if(T(e,"json")){let h={addresses:l,activeAddress:p,activeNetwork:t,seed:c.toString("hex"),file:g,createdAt:f.createdAt};if(d)h.mnemonic=d;P(h);return}if(process.stdout.write(p+`
|
|
40
40
|
`),process.stderr.write(`
|
|
41
41
|
`+j("Wallet Generated")+`
|
|
42
42
|
|
|
@@ -54,7 +54,7 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
54
54
|
`),process.stderr.write(u(" Next: midnight info | midnight balance")+`
|
|
55
55
|
|
|
56
56
|
`),process.stderr.write(H("✓")+` Wallet saved
|
|
57
|
-
`)}var
|
|
57
|
+
`)}var no=E(()=>{He();pe();ke();ue()});var La={};fe(La,{default:()=>hn});async function hn(e){let t=oe(x(e,"wallet")),r=de(t),n=_e({args:e}),s=r.addresses[n];if(T(e,"json")){let i={addresses:r.addresses,activeNetwork:n,activeAddress:s,createdAt:r.createdAt,file:t};if(r.shieldedAddresses)i.shieldedAddresses=r.shieldedAddresses;P(i);return}process.stdout.write(s+`
|
|
58
58
|
`),process.stderr.write(`
|
|
59
59
|
`+j("Wallet Info")+`
|
|
60
60
|
|
|
@@ -69,11 +69,11 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
69
69
|
`),process.stderr.write(` ${u("created")} ${r.createdAt}
|
|
70
70
|
`),process.stderr.write(` ${u("file ")} ${t}
|
|
71
71
|
|
|
72
|
-
`)}var
|
|
73
|
-
`)}var
|
|
72
|
+
`)}var so=E(()=>{ke();pe();ue();ue()});function Pe(){Ua=!0}function W(e,t){if(!Ua)return;let r=new Date().toISOString().slice(11,23);process.stderr.write(u(` [${r}] ${e}: ${t}`)+`
|
|
73
|
+
`)}var Ua=!1;var st=()=>{};function oo(e,t={}){let r=x(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 Y(`${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=x(e,"wallet");if(s===void 0&&t.requireExplicit)throw new Y(`${t.label??"This command"} needs a seed source. Provide one of:
|
|
74
74
|
--seed <hex> 32-byte seed as 64 hex characters
|
|
75
75
|
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
76
|
-
--wallet <name> derive from a saved wallet`);let o=oe(s),i=de(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function
|
|
76
|
+
--wallet <name> derive from a saved wallet`);let o=oe(s),i=de(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function wn(e,t){return oo(e,t).seed}var yn=E(()=>{We();ke()});function im(e){return!om.includes(e)}function Gt(e,t=!1){return im(e)||t}function Sn(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var om;var bn=E(()=>{om=["preview","preprod"]});import{NetworkId as io}from"@midnight-ntwrk/wallet-sdk-abstractions";function It(e){let t=am[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}var am;var vn=E(()=>{am={PreProd:io.NetworkId.PreProd,Preview:io.NetworkId.Preview,Undeployed:io.NetworkId.Undeployed}});import cm from"ws";function Kt(e,t,r){return new Promise((n,s)=>{let o=new cm(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,l=!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===gr)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&&l&&(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:dm,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}`,_=i.get(R);if(_)_.spent=!0}if(r)r(d,c);m()}else if(S.__typename==="UnshieldedTransactionsProgress")c=S.highestTransactionId,l=!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 ${Os/1000}s. Indexer: ${t}`))},Os)})}function Pr(e){return e===gr}var dm=`
|
|
77
77
|
subscription UnshieldedTransactions($address: UnshieldedAddress!) {
|
|
78
78
|
unshieldedTransactions(address: $address) {
|
|
79
79
|
__typename
|
|
@@ -87,10 +87,10 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
|
-
`;var Or=()=>{};function
|
|
91
|
-
`),h=await p()}}else W("facade","No cache, building fresh"),h=await p();return{facade:h,keystore:d,zswapSecretKeys:a,dustSecretKey:c,restoredFromCache:g}}function
|
|
90
|
+
`;var Or=()=>{};function ja(e,t,r){let n;for(let s of e)if(s.value>=t&&(n===void 0||s.value<n.value))n=s;return n===void 0?r(t):[n]}function Wa({owed:e,coinCount:t,choose:r,feeWith:n}){let s=e;for(let o=0;o<=t*2;o++){let i=s>0n?r(s):[];if(i===void 0)return{kind:"short",atFirstChoice:o===0};let a=n(i),c=i.reduce((d,l)=>d+l.value,0n);if(a<=c)return{kind:"covered",fee:a,inputs:i};s=a}return{kind:"short",atFirstChoice:!1}}function Ba(e,t){let r=t;return e.map((n)=>{let s=r>=n.value?n.value:r;return r-=s,{...n,value:s}})}import{Imbalances as lm,InsufficientFundsError as Ha,getBalanceRecipe as um}from"@midnight-ntwrk/wallet-sdk-capabilities";import{CustomDustWallet as pm}from"@midnight-ntwrk/wallet-sdk-dust-wallet";import{Transacting as Ga,V1Builder as mm}from"@midnight-ntwrk/wallet-sdk-dust-wallet/v1";import{LedgerOps as ao}from"@midnight-ntwrk/wallet-sdk-utilities";function co(e){return pm(e,new mm().withDefaults().withTransacting(fm))}var Ka,fm=(e,t)=>new Ka(e.networkId,e.costParameters,()=>t().coinSelection,()=>t().coinsAndBalancesCapability,()=>t().keysCapability);var Ja=E(()=>{Ka=class Ka extends Ga.TransactingCapabilityImplementation{computeBalancingRecipe(...e){let[t,r,n,s,o,i]=e,a;try{let c=-n.reduce((l,p)=>l+Ga.TransactingCapabilityImplementation.feeImbalance(p,this.calculateFee(p,i)),0n),d=this.getCoins().getAvailableCoinsWithGeneratedDust(r,o);a=Wa({owed:c,coinCount:d.length,choose:(l)=>ja(d,l,(p)=>this.#e(d,p)),feeWith:(l)=>this.dryRunFee(l,n,t,r,s,o,i)})}catch(c){return ao.ledgerTry(()=>{throw c})}if(a.kind==="covered"){let{fee:c,inputs:d}=a;return ao.ledgerTry(()=>({fee:c,recipeInputs:Ba(d,c)}))}if(a.atFirstChoice)return super.computeBalancingRecipe(...e);return ao.ledgerTry(()=>{throw new Ha("dust")})}#e(e,t){try{return um({coins:e.map((n)=>({type:"dust",value:n.value,token:n.token})),initialImbalances:lm.fromEntry("dust",-t),feeTokenType:"dust",transactionCostModel:{inputFeeOverhead:0n,outputFeeOverhead:0n},createOutput:(n)=>n,isCoinEqual:(n,s)=>n.type===s.type&&n.value===s.value}).inputs.map((n)=>({token:n.token,value:n.value}))}catch(r){if(r instanceof Ha)return;throw r}}}});import{existsSync as Mr,mkdirSync as gm,writeFileSync as hm,readFileSync as Va,unlinkSync as kn,readdirSync as lo,renameSync as wm}from"node:fs";import{join as $t,dirname as ym}from"node:path";import{homedir as za}from"node:os";import{randomBytes as Sm}from"node:crypto";import*as Cn from"@midnight-ntwrk/ledger-v8";function uo(e){return e.toString(16).padStart(64,"0")}function Ye(e){let t=pt(e),r=Cn.DustSecretKey.fromSeed(t);return uo(r.publicKey)}function po(e,t){let r=t??$t(za(),ce,$e);return $t(r,e)}function mo(e,t,r){let n=t.slice(0,20);return $t(po(e,r),`dust-${n}.json`)}function Fr(e,t,r){let n=mo(e,t,r);if(!Mr(n))return null;try{let s=JSON.parse(Va(n,"utf-8"));if(s.version!==qa)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:Cn.DustLocalState.deserialize(o),lastAppliedEventId:s.lastAppliedEventId,retention:{ownedGenerationIndices:s.ownedGenerationIndices,generationFrontier:s.generationFrontier}}}catch{return null}}function fo(e,t,r,n,s,o,i=bm){let a={version:qa,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=mo(e,t,s),d=ym(c);if(!Mr(d))gm(d,{recursive:!0,mode:ye});let l=c+`.tmp.${Sm(4).toString("hex")}`;try{hm(l,JSON.stringify(a),{mode:Se}),wm(l,c)}catch(p){try{kn(l)}catch{}throw p}}function Xa(e,t,r){if(!t)return[];let n=po(e,r);if(!Mr(n))return[];let s=[],o;try{o=lo(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(Va(a,"utf-8"));if(!c.chainId)continue;if(c.chainId!==t)kn(a),s.push(a)}catch{}}return s}function ft(e,t,r){let n=r??$t(za(),ce,$e);if(e&&t){let o=mo(e,t,r);try{kn(o)}catch{}return}let s=(o)=>{if(!Mr(o))return;try{for(let i of lo(o))if(i.startsWith("dust-")&&i.endsWith(".json"))try{kn($t(o,i))}catch{}}catch{}};if(e){s(po(e,r));return}if(!Mr(n))return;try{for(let o of lo(n))s($t(n,o))}catch{}}var qa=2,bm;var Dt=E(()=>{Tt();bm={ownedGenerationIndices:[],generationFrontier:0}});import{ShieldedWallet as Ya}from"@midnight-ntwrk/wallet-sdk-shielded";import{UnshieldedWallet as Za,createKeystore as vm,PublicKey as km}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{WalletFacade as Qa}from"@midnight-ntwrk/wallet-sdk-facade";import*as Jt from"@midnight-ntwrk/ledger-v8";import{NetworkId as go,InMemoryTransactionHistoryStorage as Cm,TransactionHistoryStorage as Am}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as Ne from"rxjs";async function Ze(e,t,r){let n=Em[t.networkId];if(n===void 0)throw Error(`Unknown networkId: ${t.networkId}`);W("facade",`Building facade for network ${t.networkId}`),W("facade",`Node: ${t.node}`),W("facade",`Indexer: ${t.indexerWS}`),W("facade",`Proof server: ${t.proofServer}`);let s=xt(e),o=ka(e),i=pt(e),a=Jt.ZswapSecretKeys.fromSeed(s),c=Jt.DustSecretKey.fromSeed(i),d=vm(o,n),l={networkId:n,indexerClientConnection:{indexerHttpUrl:t.indexer,indexerWsUrl:t.indexerWS},costParameters:{additionalFeeOverhead:Gi,feeBlocksMargin:Ki},txHistoryStorage:new Cm(Am.TransactionHistoryCommonSchema),provingServerUrl:new URL(t.proofServer),relayURL:new URL(t.node)},p=()=>Qa.init({configuration:l,shielded:(m)=>Ya(m).startWithSecretKeys(a),unshielded:(m)=>Za(m).startWithPublicKey(km.fromKeyStore(d)),dust:(m)=>co(m).startWithSecretKey(c,Jt.LedgerParameters.initialParameters().dust)}),f=r?xm(r,t,c.publicKey):null,g=!1,h;if(f){W("facade","Restoring from cache...");try{h=await Qa.init({configuration:l,shielded:(m)=>Ya(m).restore(f.shielded),unshielded:(m)=>Za(m).restore(f.unshielded),dust:(m)=>co(m).restore(f.dust)}),g=!0,W("facade","Cache restore successful")}catch(m){W("facade",`Cache restore failed: ${m.message}`),process.stderr.write(` Cache restore failed, building from scratch: ${m.message}
|
|
91
|
+
`),h=await p()}}else W("facade","No cache, building fresh"),h=await p();return{facade:h,keystore:d,zswapSecretKeys:a,dustSecretKey:c,restoredFromCache:g}}function wo(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 xm(e,t,r){try{let n=t.networkId.toLowerCase(),s=uo(r),o=Fr(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 W("facade",`Facade dust offset=${a} >= dust-direct offset=${o.lastAppliedEventId}; skipping bridge`),e;return W("facade",`Bridged dust-direct cache (facade offset ${a} → dust-direct offset ${o.lastAppliedEventId})`),{...e,dust:wo(e.dust,o)}}catch(n){return W("facade",`Dust-direct bridge skipped: ${n.message}`),e}}function ho(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 Tm(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 gt(e,t={}){let{onProgress:r,onSyncDetail:n,timeoutMs:s,syncMode:o="full",requireStrictSync:i=!1}=t,{facade:a,zswapSecretKeys:c,dustSecretKey:d}=e;W("sync","Starting facade (connecting to node and indexer)..."),await a.start(c,d),W("sync","Facade started, subscribing to state...");let l=s??qi;W("sync",`Sync timeout: ${l/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(W("sync",`Sync timed out after ${l/1000}s (${w} emissions)`),S)try{let v=S.unshielded?.progress;W("sync",` unshielded: applied=${v?.appliedId} highest=${v?.highestTransactionId} complete=${v?.isStrictlyComplete()}`);let R=S.dust?.state?.progress;if(W("sync",` dust: applied=${R?.appliedIndex} highest=${R?.highestRelevantWalletIndex} complete=${R?.isStrictlyComplete?.()} connected=${R?.isConnected}`),o==="full"){let _=S.shielded?.state?.progress;W("sync",` shielded: complete=${_?.isStrictlyComplete()}`)}}catch{}h(Error("Wallet sync timed out"))}},l);e.keepAlive=a.state().subscribe({next:(v)=>{if(m)return;if(w++,S=v,e.restoredFromCache){let _=Rm(v);if(_){m=!0,clearTimeout(b),W("sync",`Stale cache detected: ${_}`),h(new An(_));return}}if(r){let _=v.unshielded.progress;if(_){let Z=Number(_.appliedId),L=Number(_.highestTransactionId);r(Math.min(Z,L),L)}}let R=[];try{if((o==="full"||o==="no-dust")&&!v.shielded?.state?.progress?.isStrictlyComplete())R.push("shielded");if(o!=="no-dust"&&Tm(v))R.push("dust");if(!v.unshielded?.progress?.isStrictlyComplete())R.push("unshielded")}catch{}if(R.length>0){n?.(R.join(", "));let _=R.join(",");if(w===1||_!==y||w%100===0)W("sync",`Waiting on: ${R.join(", ")} (emission #${w})`),y=_}if(ho(v,o)){m=!0,clearTimeout(b),W("sync",`Sync complete after ${w} emissions`),g(v);return}if(p){let _=Date.now()-f;if(_>=Nm&&ho(v,"no-dust"))m=!0,clearTimeout(b),W("sync",`Sync resolved via cached-restore grace (${_}ms, ${w} emissions)`),g(v)}},error:(v)=>{if(!m)W("sync",`Sync error: ${v.message}`),clearTimeout(b),h(v)}})})}function Rm(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 ec(e){let t=(r)=>{let n=r.unshielded?.progress?.isStrictlyComplete()??!1,s=r.dust?.state?.progress?.isStrictlyComplete()??!1;return n&&s};try{return await Ne.firstValueFrom(e.facade.state().pipe(Ne.filter(t),Ne.timeout(15000)))}catch{return await Ne.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 Ne.firstValueFrom(e.facade.state().pipe(Ne.filter(r),Ne.timeout(t)))}catch{return await Ne.firstValueFrom(e.facade.state())}}async function yo(e,t="full"){return Ne.firstValueFrom(e.facade.state().pipe(Ne.filter((r)=>ho(r,t)),Ne.timeout(Xi)))}async function Fe(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 Em,Nm=1e4,An;var Ge=E(()=>{Ja();Tt();Dt();st();Em={PreProd:go.NetworkId.PreProd,Preview:go.NetworkId.Preview,Undeployed:go.NetworkId.Undeployed};An=class An extends Error{code="STALE_CACHE";constructor(e){super(`Cached wallet state is stale (from a previous chain). ${e}
|
|
92
92
|
Run: midnight cache clear --wallet <name> --network <name>
|
|
93
|
-
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 En(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 Lr(e){let t=e?.message?.toLowerCase()??"";if(e?._tag==="Wallet.InsufficientFunds")return!0;return t==="insufficient funds"||t.startsWith("insufficient funds")}import{existsSync as jr,mkdirSync as $m,writeFileSync as Dm,readFileSync as tc,unlinkSync as Ur,readdirSync as xn,renameSync as _m}from"node:fs";import{join as Qe,dirname as Pm}from"node:path";import{homedir as So}from"node:os";import{randomBytes as Om}from"node:crypto";function bo(e,t,r){let n=r??Qe(So(),ce,$e),s=e.slice(0,20);return Qe(n,t,`${s}.json`)}function ht(e,t,r){let n=bo(e,t,r);if(!jr(n))return null;try{let s=tc(n,"utf-8"),o=JSON.parse(s);if(o.version!==Fs)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 Le(e,t,r,n,s){let[o,i,a]=await Promise.all([r.shielded.serializeState(),r.unshielded.serializeState(),r.dust.serializeState()]),c={version:Fs,network:t,address:e,timestamp:new Date().toISOString(),wallets:{shielded:o,unshielded:i,dust:a},...s?{chainId:s}:{}},d=bo(e,t,n),l=Pm(d);if(!jr(l))$m(l,{recursive:!0,mode:ye});let p=d+`.tmp.${Om(4).toString("hex")}`;try{Dm(p,JSON.stringify(c),{mode:Se}),_m(p,d)}catch(f){try{Ur(p)}catch{}throw f}}function rc(e,t,r){if(!t)return[];let n=r??Qe(So(),ce,$e),s=Qe(n,e);if(!jr(s))return[];let o=[],i;try{i=xn(s)}catch{return[]}for(let a of i){if(!a.endsWith(".json"))continue;let c=Qe(s,a);try{let d=JSON.parse(tc(c,"utf-8"));if(!d.chainId)continue;if(d.chainId!==t)Ur(c),o.push(c)}catch{}}return o}function Ke(e,t,r){let n=r??Qe(So(),ce,$e);if(e&&t){let s=bo(e,t,r);try{Ur(s)}catch{}return}if(t){let s=Qe(n,t);if(!jr(s))return;try{for(let o of xn(s))if(o.endsWith(".json"))Ur(Qe(s,o))}catch{}return}if(!jr(n))return;try{for(let s of xn(n)){let o=Qe(n,s);try{for(let i of xn(o))if(i.endsWith(".json"))Ur(Qe(o,i))}catch{}}}catch{}}var wt=()=>{};import Mm from"ws";async function zt(e,t,r=[]){let n=e.timeoutMs??Fm;return new Promise((s,o)=>{let i=new Mm(e.url),a=!1,c=(l)=>{if(!a)a=!0,l()},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(l){clearTimeout(d),c(()=>o(l instanceof Error?l:Error(String(l))))}}),i.on("message",(l)=>{clearTimeout(d),c(()=>{try{let p=JSON.parse(l.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",(l)=>{clearTimeout(d),c(()=>o(l instanceof Error?l:Error(String(l))))})})}var Fm=5000;var Tn=()=>{};async function Nn(e){let t=nc.get(e);if(t&&Date.now()-t.fetchedAt<Lm)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 nc.set(e,{hash:r,fetchedAt:Date.now()}),r}catch{return null}}var nc,Lm=60000;var vo=E(()=>{Tn();nc=new Map});function Um(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 Rn(e,t,r){let n=Um(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 jm from"ws";function In(e,t){let{query:r,variables:n,onNext:s,buildResult:o,timeoutMs:i,idleMs:a,idleBeforeFirstEvent:c,initialSilenceMs:d,signal:l}=t;return new Promise((p,f)=>{let g=new jm(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{}l?.removeEventListener("abort",_)},v=(L,J)=>{if(m)return;m=!0,b();try{p(o(J))}catch(M){f(M instanceof Error?M:Error(String(M)))}},R=(L)=>{if(m)return;m=!0,b(),f(L)},_=()=>R(Error("Operation cancelled"));l?.addEventListener("abort",_,{once:!0});let Z=()=>{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",(L)=>{let J;try{J=JSON.parse(L.toString())}catch{return}if(J.type==="connection_ack"){if(g.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:r,variables:n}})),c)Z();if(d&&d>0)S=setTimeout(()=>{if(!h&&!m)v("initial-silence",!1)},d);return}if(J.type==="error"){R(Error(`GraphQL subscription error: ${JSON.stringify(J.payload)?.slice(0,300)}`));return}if(J.type!=="next")return;if(J.payload?.errors){R(Error(`GraphQL error: ${J.payload.errors[0]?.message||"unknown"}`));return}if(h=!0,S)clearTimeout(S),S=void 0;let M;try{M=s(J.payload?.data)}catch(O){R(O instanceof Error?O:Error(String(O)));return}if(Z(),M)v("caught-up",!1)}),g.on("error",(L)=>R(Error(`WebSocket error: ${L.message}`))),g.on("close",()=>{if(m)return;v(h?"closed-early":"graceful-close",h)}),w=setTimeout(()=>v("timeout",!0),i)})}var ko=()=>{};import*as qt from"@midnight-ntwrk/ledger-v8";function Bm(){let e=new qt.DustParameters(Ji,Vi,zi);return new qt.DustLocalState(e)}function sc(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:l=0,initialRetention:p,collapse:f}=r,g=f!==!1&&process.env[Co]!=="1",h=500,m=d??Bm(),w=[],y=e.publicKey,S=new Set((p?.ownedGenerationIndices??[]).map(BigInt)),b=BigInt(p?.generationFrontier??0),v=(M)=>{let O=M.content;if(O?.tag!=="dustInitialUtxo"||O.generationIndex===void 0)return;let Q=O.generationIndex;if(Q+1n>b)b=Q+1n;if(O.generation?.owner===y)S.add(Q)},R=()=>({ownedGenerationIndices:[...S].map(Number),generationFrontier:Number(b)}),_=0,Z=l-1,L=-1,J=()=>{if(w.length===0)return;if(m=m.replayEvents(e,w),_+=w.length,w.length=0,g)m=Rn(m,S,b).state;if(s&&Z>=0)try{s(m,Z,R())}catch{}};return In(t,{query:Wm,variables:{id:l},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(M)=>{let O=M?.dustLedgerEvents;if(!O)return!1;let Q;try{Q=qt.Event.deserialize(Buffer.from(O.raw,"hex"))}catch(le){throw Error(`Failed to deserialize dust event ${O.id}: ${le.message}`)}if(v(Q),w.push(Q),Z=O.id,O.maxId>L)L=O.maxId;if(w.length>=500)try{J()}catch(le){throw Error(`Failed applying dust events: ${le.message}`)}return n?.(_+w.length,L),Z>=L},buildResult:(M)=>{try{J();let O=new Date;return m=m.processTtls(O),{balance:m.walletBalance(O),availableCoins:m.utxos.length,eventCount:_,ownedUtxoCount:m.utxos.length,syncTime:m.syncTime,state:m,retention:R(),lastAppliedEventId:Z,partial:M}}catch(O){throw Error(`Failed to build dust state: ${O.message}`)}}})}var Co="MN_DISABLE_DUST_COLLAPSE",Wm=`
|
|
94
94
|
subscription DustLedgerEvents($id: Int) {
|
|
95
95
|
dustLedgerEvents(id: $id) {
|
|
96
96
|
type: __typename
|
|
@@ -99,9 +99,9 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
99
99
|
maxId
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
|
-
`;var
|
|
102
|
+
`;var Ao=E(()=>{ko()});import{spawn as Hm}from"node:child_process";import{existsSync as yt,mkdirSync as Gm,readFileSync as cc,readdirSync as oc,unlinkSync as ic,writeFileSync as Km}from"node:fs";import{homedir as dc}from"node:os";import{dirname as ac,join as ot}from"node:path";import{fileURLToPath as Jm}from"node:url";import*as lc from"@midnight-ntwrk/ledger-v8";function uc(){let e=process.env.MN_DUST_SYNC_BIN;if(e&&yt(e))return e;let t=process.platform==="win32"?"dust-sync.exe":"dust-sync",r=ac(Jm(import.meta.url));for(let n of[["..",".."],[".."]]){let s=ot(r,...n,"sidecar","dust-sync","target","release",t);if(yt(s))return s}try{let n=`@nel349/dust-sync-${process.platform}-${process.arch}`,s=Vm(import.meta.url),o=ot(ac(s.resolve(`${n}/package.json`)),t);if(yt(o))return o}catch{}return null}function Vm(e){return globalThis.require??Is("node:module").createRequire(e)}function pc(){if(process.env.MN_DISABLE_NATIVE_DUST==="1")return!1;return uc()!==null}function zm(e,t,r){if(e+1>=t)return"existing";if(r)return"seed";return"fresh"}function qm(e){if(!yt(e))return-2;try{let t=JSON.parse(cc(e,"utf-8"));return typeof t.last_applied_event_id==="number"?t.last_applied_event_id:-2}catch{return-2}}function Xm(e,t){let r=ot(dc(),ce,$e,e);if(!yt(r))Gm(r,{recursive:!0,mode:ye});return ot(r,`dust-native-${t.slice(0,20)}.json`)}function $n(e,t){let r=ot(dc(),ce,$e);if(e&&t){try{ic(ot(r,e,`dust-native-${t.slice(0,20)}.json`))}catch{}return}let n=(s)=>{if(!yt(s))return;try{for(let o of oc(s))if(o.startsWith("dust-native-")&&o.endsWith(".json"))try{ic(ot(s,o))}catch{}}catch{}};if(e){n(ot(r,e));return}if(!yt(r))return;try{for(let s of oc(r))n(ot(r,s))}catch{}}function mc(e,t,r){return new Promise((n,s)=>{let o=uc();if(!o){s(Error("dust-sync sidecar not found"));return}let i=t.networkId.toLowerCase(),a=Ye(e),c=Xm(i,a),d=["--indexer-ws",t.indexerWS,"--out",c],l=zm(qm(c),r.startFromId,!!r.initialState);if(l==="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};Km(c,JSON.stringify(w),{mode:Se})}if(l!=="fresh")d.push("--resume",c);let p=Hm(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(pt(e)).toString("hex");p.stdin.write(g+`
|
|
103
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&&!yt(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(
|
|
104
|
+
`).filter(Boolean).pop(),S=y?JSON.parse(y):JSON.parse(cc(c,"utf-8"));n(Ym(S))}catch(y){s(Error(`dust-sync output parse failed: ${y.message}`))}})})}function Ym(e){let t=new Date,r=lc.DustLocalState.deserialize(new Uint8Array(Buffer.from(e.dust_state,"hex")));if(process.env[Co]!=="1"){let s=new Set(e.owned_generation_indices.map((o)=>BigInt(o)));r=Rn(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 Eo=E(()=>{Tt();Ao();Dt()});import*as gc from"@midnight-ntwrk/ledger-v8";class hc{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??nf,this.fetchUnshielded=e.fetchUnshielded??sf,this.fetchDust=e.fetchDust??af,this.fetchChainId=e.fetchChainId??Nn,this.cacheDir=e.cacheDir}async dust(e,t,r={}){let n=Dn(t),s=Ye(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);Xa(n,i,this.cacheDir);let a=i??void 0,c=r.forceFresh?null:Fr(n,s,this.cacheDir),d=c!==null,l=0,p=c?.lastAppliedEventId??-1,f=null;for(let h=0;h<Qm;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{fo(n,s,w,y,this.cacheDir,a,S)}catch{}}}),p=f.lastAppliedEventId>=0?f.lastAppliedEventId:c?.lastAppliedEventId??-1,f.lastAppliedEventId>=0||!c)try{fo(n,s,f.state,p,this.cacheDir,a,f.retention)}catch{}if(l+=f.eventCount,!f.partial)break;c=Fr(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:l,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=Dn(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=Dn(t),c=ve(e,a),d=t.networkId!=="Undeployed",l=n.syncTimeoutMs??(d?tf:ef),p=await this.fetchChainId(t.node).catch(()=>null);rc(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 Fe(g)}catch{}};try{for(let b=1;b<=Wr;b++){if(n.signal?.aborted)throw Error("Operation cancelled");let v=n.forceFresh?null:ht(c,a,this.cacheDir);g=await Ze(e,t,v);try{h=await gt(g,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:l,syncMode:s,requireStrictSync:o});break}catch(R){if(n.signal?.aborted)throw Error("Operation cancelled");if(R instanceof An&&b<Wr&&i){n.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${b+1}/${Wr})...`),await Fe(g).catch(()=>{}),g=void 0,Ke(c,a,this.cacheDir),ft(a,Ye(e),this.cacheDir);try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch{}continue}if(b<Wr&&String(R?.message??"").includes("timed out")){try{await Le(c,a,g.facade,this.cacheDir,f)}catch{}n.onStatus?.(`Sync timed out, retrying (attempt ${b+1}/${Wr})...`),await Fe(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<fc&&Lr(b)))throw b;if(n.onStatus?.(`Refreshing wallet state (attempt ${S+1}/${fc})...`),await Fe(g).catch(()=>{}),g=void 0,await new Promise((_)=>setTimeout(_,rf)),n.signal?.aborted)throw Error("Operation cancelled");let R=ht(c,a,this.cacheDir);g=await Ze(e,t,R),h=await gt(g,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:l,syncMode:s,requireStrictSync:o})}}if(!n.skipAutoSave)try{await Le(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=Dn(e.network),r=e.kinds??["dust","unshielded","facade"];if(r.includes("dust"))if(e.seed){let n=Ye(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{Ke(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{W("repo",`tip unavailable; skipping memo for ${t}`)}}async getTip(e,t){let r=this.tipMemo.get(e.networkId);if(r&&this.now()-r.fetchedAt<Zm)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 nf(e){return zt({url:e.node,timeoutMs:3000},"chain_getBlockHash",[])}function sf(e,t,r){return Kt(e,t.indexerWS,r)}function of(e,t,r){let n=pt(e),s=gc.DustSecretKey.fromSeed(n);return sc(s,t.indexerWS,r)}async function af(e,t,r){if(pc())try{return await mc(e,t,r)}catch(n){W("dust",`native sidecar failed, using WASM: ${n.message}`)}return of(e,t,r)}function Dn(e){let t=e.networkId.toLowerCase();if(xe(t))return t;throw Error(`Unsupported network: ${e.networkId}`)}function me(){if(!xo)xo=new hc;return xo}var Zm=5000,Qm=6,ef=30000,tf=120000,Wr=3,fc=5,rf=5000,xo=null;var it=E(()=>{De();Ge();Dt();wt();vo();Or();Ao();Eo();st();Tn();Tt();He()});import*as Xt from"@midnight-ntwrk/ledger-v8";function df(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 wc(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:l=0}=r,p=500,f=d??new Xt.ZswapLocalState,g=[],h=0,m=l-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 In(t,{query:cf,variables:{id:l},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}=df(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 cf=`
|
|
105
105
|
subscription ZswapLedgerEvents($id: Int) {
|
|
106
106
|
zswapLedgerEvents(id: $id) {
|
|
107
107
|
id
|
|
@@ -109,23 +109,23 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
109
109
|
maxId
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
|
-
`;var
|
|
113
|
-
Expected a bech32m address for network "${t.networkId}"`)}}function
|
|
114
|
-
Available: ${
|
|
112
|
+
`;var yc=E(()=>{ko()});import{existsSync as _n,mkdirSync as lf,writeFileSync as uf,readFileSync as pf,unlinkSync as No,readdirSync as Sc,renameSync as mf}from"node:fs";import{join as Yt,dirname as ff}from"node:path";import{homedir as bc}from"node:os";import{randomBytes as gf}from"node:crypto";import*as Br from"@midnight-ntwrk/ledger-v8";function kc(e){return Br.ZswapSecretKeys.fromSeed(xt(e)).coinPublicKey}function Cc(e,t){let r=t??Yt(bc(),ce,$e);return Yt(r,e)}function Ro(e,t,r){let n=t.slice(0,20);return Yt(Cc(e,r),`shielded-${n}.json`)}function hf(e,t,r,n){let s=Ro(e,t,r);if(!_n(s))return null;try{let o=JSON.parse(pf(s,"utf-8"));if(o.version!==vc)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:Br.ZswapLocalState.deserialize(new Uint8Array(Buffer.from(o.zswapState,"hex"))),lastAppliedEventId:o.lastAppliedEventId}}catch{return null}}function To(e,t,r,n,s,o){let i={version:vc,network:e,coinPublicKeyHex:t,lastAppliedEventId:n,timestamp:new Date().toISOString(),zswapState:Buffer.from(r.serialize()).toString("hex"),...o?{chainId:o}:{}},a=Ro(e,t,s),c=ff(a);if(!_n(c))lf(c,{recursive:!0,mode:ye});let d=a+`.tmp.${gf(4).toString("hex")}`;try{uf(d,JSON.stringify(i),{mode:Se}),mf(d,a)}catch(l){try{No(d)}catch{}throw l}}function Pn(e,t,r){let n=r??Yt(bc(),ce,$e);if(e&&t){let o=Ro(e,t,r);try{No(o)}catch{}return}let s=(o)=>{if(!_n(o))return;try{for(let i of Sc(o))if(i.startsWith("shielded-")&&i.endsWith(".json"))try{No(Yt(o,i))}catch{}}catch{}};if(e){s(Cc(e,r));return}if(!_n(n))return;try{for(let o of Sc(n))s(Yt(n,o))}catch{}}async function Ac(e,t,r,n={}){let s=Br.ZswapSecretKeys.fromSeed(xt(e)),o=s.coinPublicKey,i=n.forceFresh?null:hf(t,o,void 0,n.chainId),a=i?i.lastAppliedEventId+1:0,c=await wc(s,r,{initialState:i?.state,startFromId:a,onProgress:n.onProgress,signal:n.signal,timeoutMs:n.timeoutMs,onCheckpoint:(d,l)=>{try{To(t,o,d,l,void 0,n.chainId)}catch{}}});if(c.lastAppliedEventId>=0)To(t,o,c.state,c.lastAppliedEventId,void 0,n.chainId);else if(!i)To(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 vc=1;var Io=E(()=>{Tt();yc()});function Ec(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,l=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);l=g>0?g/d:0}}return{applied:i.applied,highest:i.highest,percent:c,ratePerSec:d,etaSec:l}};return{sample(i){return r.push(i),s(i.t),n=o(),n},snapshot(){return n},reset(){r.length=0,n=null}}}function xc(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 ${wf(e.etaSec)}`);if(e.ratePerSec!==null&&e.ratePerSec>0)r.push(`${Math.round(e.ratePerSec)} evt/s`);return r.join(" · ")}function wf(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 _o from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as yf,UnshieldedAddress as Sf}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as $o}from"@midnight-ntwrk/wallet-sdk-abstractions";function Hr(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 Gr(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 vf(e,t){let r=bf[t.networkId];if(r===void 0)throw Error(`Unknown networkId: ${t.networkId}`);try{return yf.parse(e).decode(Sf,r)}catch(n){throw Error(`Invalid recipient address: ${n.message}
|
|
113
|
+
Expected a bech32m address for network "${t.networkId}"`)}}function On(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 Do(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 kf(e,t,r){let n=new Date(Date.now()+wr*60*1000);await Promise.race([e.facade.dust.waitForSyncedState(),new Promise((d,l)=>setTimeout(()=>l(Error("Insufficient funds: dust wallet sync timed out")),_s))]);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 Cf(e,t,r,n){let s=Date.now(),o=s+ta,i,a=!1,c=setInterval(()=>{if(a&&n){let d=Do(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 kf(e,t,r)}catch(d){if(i=d,En(d)&&Date.now()+Ms<o){a=!0;let l=Do(Date.now()-s);n?.(`Waiting for dust generation capacity (${l} elapsed, ~5 min on fresh wallets)...`),await new Promise((p)=>setTimeout(p,Ms));continue}throw d}throw i??Error("Dust registration timed out")}finally{clearInterval(c)}}async function et(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 Cf(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<Ps){try{if((await Promise.race([e.facade.waitForSyncedState(),new Promise((c,d)=>setTimeout(()=>d(Error("Poll sync timed out")),_s))])).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 Af(e,t,r,n,s,o,i){let a=Date.now(),c=a+Ps,d,l=0;while(!0)try{if(d)await yo(e,"lite");let p=new Date(Date.now()+wr*60*1000);W("transfer","Building transfer transaction...");let f=await e.facade.transferTransaction([{type:"unshielded",outputs:[{amount:r,receiverAddress:t,type:_o.unshieldedToken().raw}]}],{shieldedSecretKeys:e.zswapSecretKeys,dustSecretKey:e.dustSecretKey},{ttl:p,payFees:!0});W("transfer","Signing recipe...");let g=await e.facade.signRecipe(f,(S)=>e.keystore.signData(S));W("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")),sn)})]);W("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 W("transfer",`Transaction submitted: ${y}`),y}catch(p){if(d=p,(p?.code===ra||p?.message?.includes("115")||p?.message?.toLowerCase().includes("stale"))&&++l<ea)continue;if(Lr(p))throw p;if(En(p)&&Date.now()<c){let g=Do(Date.now()-a);o?.(`Dust insufficient, re-ensuring (${g} elapsed)...`);try{let h=await yo(e,"lite"),m=h.dust.balance(new Date);if(m>0n&&m<hr)throw Error(`Insufficient dust for transaction fees.
|
|
114
|
+
Available: ${On(m)} DUST, need ≥${On(hr)} DUST.
|
|
115
115
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
116
|
-
Check status: midnight dust status`);await et(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:l,onSubmittingTick:p,onSyncWarning:f}=e,g=Hr(s),h=
|
|
117
|
-
Available: ${
|
|
116
|
+
Check status: midnight dust status`);await et(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:l,onSubmittingTick:p,onSyncWarning:f}=e,g=Hr(s),h=vf(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");W("transfer","Sync complete, checking balance...");let b=S.unshielded.balances[_o.unshieldedToken().raw]??0n,v=S.unshielded.availableCoins?.length??0;if(W("transfer",`Balance: ${Number(b)/Ds} NIGHT, coins: ${v}`),b<g){let Z=Number(b)/Ds;throw Error(`Insufficient balance: ${Z.toFixed(6)} NIGHT available, ${s} NIGHT requested`)}let R=S.dust.balance(new Date);if(R>0n&&R<hr)throw Error(`Insufficient dust for transaction fees.
|
|
117
|
+
Available: ${On(R)} DUST, need ≥${On(hr)} DUST.
|
|
118
118
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
119
|
-
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(W("transfer","Ensuring dust availability..."),await et(y,c,S),W("transfer","Dust available"),o?.aborted)throw Error("Operation cancelled");return W("transfer","Building and submitting transaction..."),{txHash:await
|
|
120
|
-
`)},fail(d){if(t)return;t=!0,
|
|
119
|
+
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(W("transfer","Ensuring dust availability..."),await et(y,c,S),W("transfer","Dust available"),o?.aborted)throw Error("Operation cancelled");return W("transfer","Building and submitting transaction..."),{txHash:await Af(y,h,g,d,l,c,p),amountMicroNight:g}},{syncMode:"lite",requireStrictSync:!0,signal:o,onStatus:c,onSyncProgress:i,onSyncDetail:a,onSyncWarning:f})}finally{w(),m()}}var bf;var St=E(()=>{Ge();it();st();bf={PreProd:$o.NetworkId.PreProd,Preview:$o.NetworkId.Preview,Undeployed:$o.NetworkId.Undeployed}});function Rc(){return _t}function Nc(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function G(e){let t=!1;if(!lt()){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,_t=null,process.stderr.write(`\r✓ ${d??a}\x1B[K
|
|
120
|
+
`)},fail(d){if(t)return;t=!0,_t=null,process.stderr.write(`\r✗ ${d??a}\x1B[K
|
|
121
121
|
`)},log(d){process.stderr.write(`\r\x1B[K${d}
|
|
122
|
-
`),process.stderr.write(`⠋ ${a}`)}};return
|
|
123
|
-
`)},fail(a){if(t)return;t=!0,clearInterval(o),
|
|
122
|
+
`),process.stderr.write(`⠋ ${a}`)}};return _t=c,c}let r=0,n=e,s=()=>{let a=U(Tc[r]),d=(process.stderr.columns||80)-4,l=n;if(Nc(l).length>d)l=Nc(l).slice(0,d);process.stderr.write(`\r${a} ${l}\x1B[K`),r=(r+1)%Tc.length};s();let o=setInterval(s,Ef),i={update(a){n=a},stop(a){if(t)return;t=!0,clearInterval(o),_t=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),_t=null;let c=a??n;process.stderr.write(`\r\x1B[31m✗\x1B[0m ${c}\x1B[K
|
|
124
124
|
`)},log(a){process.stderr.write(`\r\x1B[K${a}
|
|
125
|
-
`),s()}};return
|
|
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(T(e,"shielded")){let a=
|
|
125
|
+
`),s()}};return _t=i,i}async function Mn(e,t,r){let n=Date.now(),s=(a)=>{let c=Math.floor(a/1000),d=Math.floor(c/60).toString().padStart(2,"0"),l=(c%60).toString().padStart(2,"0");return`${d}:${l}`},o=()=>e.update(`${t} ${s(Date.now()-n)}`);o();let i=setInterval(o,1000);try{return await r}finally{clearInterval(i)}}var Tc,Ef=80,_t=null;var Je=E(()=>{Tc=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var Dc={};fe(Dc,{default:()=>Fn});import*as Ic from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as xf}from"@midnight-ntwrk/wallet-sdk-address-format";async function Fn(e){if(e.subcommand)return Nf(e);return $c(e)}function Tf(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(Ie(e))Pe();let t=e.subcommand;W("balance",`address=${t}`);let r=Tf(t),n=x(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(T(e,"shielded")){let a=Ta(t);if(a){W("balance",`shielded positional → wallet ${a.wallet.name} on ${a.network}`);let c={...e,flags:{...e.flags,wallet:a.wallet.file,network:a.network}};return $c(c)}throw Error("Shielded balances are private — they can only be read with the wallet's secret key, "+`not from an address alone.
|
|
127
127
|
This address isn't one of your wallets. Check its shielded balance from the wallet that owns it:
|
|
128
|
-
midnight balance --wallet <name> --shielded --network ${s}`)}Me(o,{proofServer:
|
|
128
|
+
midnight balance --wallet <name> --shielded --network ${s}`)}Me(o,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},s);let i=G(`Checking balance on ${s}...`);try{let a=await me().unshielded(t,o,{forceFresh:T(e,"no-cache"),onProgress:(c,d)=>{if(d>0){let l=Math.round(c/d*100);i.update(`Syncing transactions... ${l}%`)}}});if(i.stop(`Synced ${a.txCount} transactions`),T(e,"json")){let c={};for(let[l,p]of a.balances){let f=Pr(l)?"NIGHT":l;c[f]=Pr(l)?Et(p):p.toString()}let d=c.NIGHT!==void 0?{NIGHT:c.NIGHT}:{};if(ct(e)){P({network:s,balances:c,...d,utxoCount:a.utxoCount});return}P({address:t,network:s,balances:c,...d,utxoCount:a.utxoCount,txCount:a.txCount});return}if(a.balances.size===0)process.stdout.write(`0
|
|
129
129
|
`);else for(let[c,d]of a.balances)process.stdout.write(`${Pr(c)?"NIGHT":c}=${d}
|
|
130
130
|
`);if(process.stderr.write(`
|
|
131
131
|
`+j("Balance")+`
|
|
@@ -141,7 +141,7 @@ This address isn't one of your wallets. Check its shielded balance from the wall
|
|
|
141
141
|
`)}process.stderr.write(`
|
|
142
142
|
`+z()+`
|
|
143
143
|
|
|
144
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
144
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function $c(e){if(Ie(e))Pe();let{name:t,config:r}=te({args:e});W("balance",`network=${t} indexerWS=${r.indexerWS}`);let{seed:n,walletPath:s,config:o}=oo(e);W("balance",`wallet path=${s??"(from --seed/MN_SEED)"}`);let i=o?.addresses[t]??ve(n,t),a=o?.shieldedAddresses?.[t]??"";Me(r,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},t);let c=he(),d=Ce(),l=T(e,"no-cache"),p=T(e,"json"),f=Ic.unshieldedToken().raw,g=null;try{if(!p){if(process.stderr.write(`
|
|
145
145
|
`+j("Balance")+`
|
|
146
146
|
|
|
147
147
|
`),process.stderr.write(A("Address",ne(i))+`
|
|
@@ -155,15 +155,15 @@ This address isn't one of your wallets. Check its shielded balance from the wall
|
|
|
155
155
|
`);if(!p)process.stdout.write(`NIGHT=${m}
|
|
156
156
|
`),process.stderr.write(`
|
|
157
157
|
`+k("Shielded")+`
|
|
158
|
-
`);let y=Gt(t,T(e,"force-shielded")),S=a,b=0n,v=0,R=0;if(y){if(!p)g=G("Syncing shielded...");let
|
|
158
|
+
`);let y=Gt(t,T(e,"force-shielded")),S=a,b=0n,v=0,R=0;if(y){if(!p)g=G("Syncing shielded...");let _=Ec(),Z=It(r.networkId);if(S=xf.encode(Z,$r(n)).asString(),s)Ht(s,t,S);let L=await Nn(r.node).catch(()=>null)??void 0,J=await Ac(n,t,r.indexerWS,{forceFresh:l,chainId:L,onProgress:(M,O)=>{if(!g)return;let Q=_.sample({applied:M,highest:O,t:Date.now()});g.update(xc(Q,"Syncing shielded"))}});if(b=J.balance,v=J.availableCoins,R=0,g)if(g.stop("Shielded ready"),g=null,b>0n)process.stderr.write(A(" NIGHT",k(cn(b)))+`
|
|
159
159
|
`),process.stderr.write(A(" Coins",`${v} available, ${R} pending`)+`
|
|
160
160
|
`);else process.stderr.write(` ${u("No shielded balance")}
|
|
161
|
-
`)}else if(!p)process.stderr.write(` ${u("Skipped — "+
|
|
162
|
-
`);if(p){if(ct(e)){P({network:t,unshielded:{NIGHT:
|
|
161
|
+
`)}else if(!p)process.stderr.write(` ${u("Skipped — "+Sn(t))}
|
|
162
|
+
`);if(p){if(ct(e)){P({network:t,unshielded:{NIGHT:Et(m),utxoCount:w},shielded:{NIGHT:Et(b),availableCoins:v,pendingCoins:R},shieldedSynced:y});return}P({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"}
|
|
163
163
|
`),process.stderr.write(`
|
|
164
164
|
`+z()+`
|
|
165
165
|
|
|
166
|
-
`)}catch(h){throw g?.fail("Failed"),h}finally{d(),c()}}var
|
|
166
|
+
`)}catch(h){throw g?.fail("Failed"),h}finally{d(),c()}}var Po=E(()=>{st();De();ke();yn();pe();De();bn();vn();Or();it();Io();He();vo();Ge();St();ue();Je()});var _c={};fe(_c,{default:()=>Ln});async function Ln(e){let t=wn(e,{requireExplicit:!0,label:"address"}),r=x(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(T(e,"json")){P({address:o,network:s,index:n,path:i});return}process.stdout.write(o+`
|
|
167
167
|
`),process.stderr.write(`
|
|
168
168
|
`),process.stderr.write(A("Network",s)+`
|
|
169
169
|
`),process.stderr.write(A("Index",n.toString())+`
|
|
@@ -171,36 +171,36 @@ This address isn't one of your wallets. Check its shielded balance from the wall
|
|
|
171
171
|
`),process.stderr.write(A("Path",u(i))+`
|
|
172
172
|
`),process.stderr.write(z()+`
|
|
173
173
|
|
|
174
|
-
`)}var
|
|
174
|
+
`)}var Oo=E(()=>{yn();He();pe();ue()});var Pc={};fe(Pc,{default:()=>Un});async function Un(e){let t=_e({args:e}),r=Buffer.from(tt,"hex"),n=ve(r,t);if(T(e,"json")){P({address:n,network:t});return}process.stdout.write(n+`
|
|
175
175
|
`),process.stderr.write(`
|
|
176
176
|
`),process.stderr.write(A("Network",t)+`
|
|
177
177
|
`),process.stderr.write(A("Address",ne(n))+`
|
|
178
178
|
`),process.stderr.write(A("Seed",u("0x01 (genesis)"))+`
|
|
179
179
|
`),process.stderr.write(z()+`
|
|
180
180
|
|
|
181
|
-
`)}var
|
|
181
|
+
`)}var Mo=E(()=>{He();pe();ue()});var Mc={};fe(Mc,{default:()=>jn});import*as Oc from"@midnight-ntwrk/ledger-v8";function Kr(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 Rf(e){return{readTime:Kr(e,"readTime",1000000000n),computeTime:Kr(e,"computeTime",1000000000n),blockUsage:Kr(e,"blockUsage",10000n),bytesWritten:Kr(e,"bytesWritten",10000n),bytesChurned:Kr(e,"bytesChurned",1000000n)}}async function jn(e){let t=Oc.LedgerParameters.initialParameters(),r=Rf(t);if(T(e,"json")){P(r);return}for(let[n,s]of Object.entries(r))process.stdout.write(`${n}=${s}
|
|
182
182
|
`);process.stderr.write(`
|
|
183
183
|
`+j("Block Limits")+`
|
|
184
184
|
|
|
185
185
|
`),process.stderr.write(u(" Derived from LedgerParameters.initialParameters()")+`
|
|
186
186
|
|
|
187
|
-
`);for(let[n,s]of Object.entries(r)){let o=
|
|
187
|
+
`);for(let[n,s]of Object.entries(r)){let o=If[n]??"";process.stderr.write(A(n,`${k(s.toLocaleString())} ${u(o)}`)+`
|
|
188
188
|
`)}process.stderr.write(`
|
|
189
189
|
`+z()+`
|
|
190
190
|
`),process.stderr.write(u(" bytesWritten is typically the tightest constraint")+`
|
|
191
191
|
`),process.stderr.write(u(" for large contract deployments.")+`
|
|
192
192
|
|
|
193
|
-
`)}var
|
|
193
|
+
`)}var If;var Fo=E(()=>{ue();If={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});var Uc={};fe(Uc,{default:()=>Qt});import*as Fc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Lc,ShieldedAddress as $f}from"@midnight-ntwrk/wallet-sdk-address-format";async function Qt(e,t){dt(e);let r=e.subcommand;if(!r)throw Error(`Missing amount.
|
|
194
194
|
Usage: midnight airdrop <amount> [--wallet <name|file|address>]
|
|
195
195
|
Example: midnight airdrop 1000
|
|
196
196
|
Example: midnight airdrop 1000 --wallet alice
|
|
197
|
-
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=Gr(r),{name:s,config:o}=te({args:e});if(Me(o,{proofServer:
|
|
197
|
+
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=Gr(r),{name:s,config:o}=te({args:e});if(Me(o,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},s),s!=="undeployed")throw Error(`Airdrop is only available on the "undeployed" network (local devnet).
|
|
198
198
|
Current network: "${s}"
|
|
199
|
-
On preprod/preview, use a faucet or transfer from another wallet.`);let i=
|
|
199
|
+
On preprod/preview, use a faucet or transfer from another wallet.`);let i=x(e,"wallet"),a=T(e,"shielded")||i!==void 0&&i.startsWith("mn_shield-addr_"),c=_f(e,s,o,a);if(a)return Mf(e,c,n,s,o,t);return Of(e,c,n,s,o,t)}function Df(e){return e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_")}function _f(e,t,r,n){let s=x(e,"wallet");if(s!==void 0&&Df(s))return Pf(s,t,r,n);let o=oe(s),i=de(o);if(n){let a=It(r.networkId),c=Buffer.from(i.seed,"hex"),d=$r(c),l=Lc.encode(a,d).asString();return{kind:"wallet",raw:d,bech32m:l,walletPath:o}}return{kind:"address",address:i.addresses[t]}}function Pf(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.
|
|
200
200
|
Pass a shielded address (mn_shield-addr_...) or drop --shielded.
|
|
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=It(r.networkId),a;try{a=
|
|
203
|
+
Got: ${e}`);if(n){let i=It(r.networkId),a;try{a=Lc.parse(e).decode($f,i)}catch(c){throw Error(`Invalid shielded address: ${c.message}`)}return{kind:"address",raw:a,bech32m:e}}return{kind:"address",address:e}}async function Of(e,t,r,n,s,o){if(Ie(e))Pe();let i=t.address,a=Buffer.from(tt,"hex");process.stderr.write(`
|
|
204
204
|
`+j("Airdrop")+`
|
|
205
205
|
|
|
206
206
|
`),process.stderr.write(A("Network",n)+`
|
|
@@ -221,7 +221,7 @@ Got: ${e}`);if(n){let i=It(r.networkId),a;try{a=Pc.parse(e).decode(Tf,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
|
|
224
|
+
Try: midnight airdrop 1`);throw d}}async function Mf(e,t,r,n,s,o){let i=Hr(r);if(Ie(e))Pe();let a=Buffer.from(tt,"hex"),c=Fc.unshieldedToken().raw,{raw:d,bech32m:l}=t;if(t.kind==="wallet")Ht(t.walletPath,n,l);process.stderr.write(`
|
|
225
225
|
`+j("Shielded Airdrop")+`
|
|
226
226
|
|
|
227
227
|
`),process.stderr.write(A("Network",n)+`
|
|
@@ -229,20 +229,20 @@ Try: midnight airdrop 1`);throw d}}async function _f(e,t,r,n,s,o){let i=Hr(r);if
|
|
|
229
229
|
`),process.stderr.write(A("To",ne(l,!0))+`
|
|
230
230
|
`),process.stderr.write(A("Amount",k(r+" NIGHT (shielded)"))+`
|
|
231
231
|
`),process.stderr.write(`
|
|
232
|
-
`);let p=he(),f=
|
|
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 _=Number(y)/1e6;throw Error(`Genesis wallet has insufficient shielded balance: ${_.toFixed(6)} NIGHT available, ${r} NIGHT requested`)}if(g.update("Checking dust..."),await et(m,(_)=>g.update(_)),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,(_)=>m.keystore.signData(_));g.update("Generating ZK proof (this may take a few minutes)...");let v=await m.facade.finalizeRecipe(b),R=await Mn(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"),T(e,"json")){P({txHash:h,amount:r,shieldedAddress:l,network:n,type:"shielded"});return}process.stdout.write(h+`
|
|
233
233
|
`),process.stderr.write(`
|
|
234
234
|
`+ut(`Airdropped ${r} shielded NIGHT to your wallet`,h)+`
|
|
235
235
|
`),process.stderr.write(`
|
|
236
236
|
`+z()+`
|
|
237
237
|
`),process.stderr.write(u(" 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 Wn=E(()=>{st();ke();pe();De();vn();He();St();Ge();it();ue();Je()});var Bc={};fe(Bc,{default:()=>Bn});import*as Wc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as jc,ShieldedAddress as Ff}from"@midnight-ntwrk/wallet-sdk-address-format";async function Bn(e,t){dt(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=T(e,"shielded"),o=
|
|
245
|
-
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function
|
|
244
|
+
Example: midnight transfer mn_addr_undeployed1... 100`);let s=T(e,"shielded"),o=Lf(r,e,s);if(s)return jf(e,o,n,t);return Uf(e,o,n,t)}function Lf(e,t,r){if(e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_"))return e;let n=oe(e),s=de(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 Uf(e,t,r,n){let s=Gr(r),o=oe(x(e,"wallet")),i=de(o),a=Buffer.from(i.seed,"hex"),{name:c,config:d}=te({args:e}),l=i.addresses[c];if(Me(d,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},c),process.stderr.write(`
|
|
246
246
|
`+j("Transfer")+`
|
|
247
247
|
|
|
248
248
|
`),process.stderr.write(A("Network",c)+`
|
|
@@ -257,7 +257,7 @@ Regenerate the wallet or run "midnight balance --shielded" first.`);return i}ret
|
|
|
257
257
|
`+z()+`
|
|
258
258
|
`),process.stderr.write(u(" 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 jf(e,t,r,n){let s=Gr(r),o=Hr(s),i=oe(x(e,"wallet")),a=de(i),c=Buffer.from(a.seed,"hex"),{name:d,config:l}=te({args:e});if(!Gt(d,T(e,"force-shielded")))throw Error(Sn(d));let p=a.addresses[d],f=It(l.networkId),g=Wc.unshieldedToken().raw;Me(l,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},d);let h;try{h=jc.parse(t).decode(Ff,f)}catch(S){throw Error(`Invalid shielded address: ${S.message}
|
|
261
261
|
Expected a shielded address (mn_shield-addr_...) for network "${l.networkId}"`)}if(process.stderr.write(`
|
|
262
262
|
`+j("Shielded Transfer")+`
|
|
263
263
|
|
|
@@ -265,19 +265,19 @@ Expected a shielded address (mn_shield-addr_...) for network "${l.networkId}"`)}
|
|
|
265
265
|
`),process.stderr.write(A("To",ne(t,!0))+`
|
|
266
266
|
`),process.stderr.write(A("Amount",k(s+" NIGHT (shielded)"))+`
|
|
267
267
|
`),process.stderr.write(`
|
|
268
|
-
`),Ie(e))Pe();let m=he(),w=
|
|
269
|
-
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(y.update("Checking dust..."),await et(b,(O)=>y.update(O)),n?.aborted)throw Error("Operation cancelled");y.update("Building shielded transaction...");let Z=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 L=await b.facade.signRecipe(Z,(O)=>b.keystore.signData(O));y.update("Generating ZK proof (this may take a few minutes)...");let J=await b.facade.finalizeRecipe(L),M=await
|
|
268
|
+
`),Ie(e))Pe();let m=he(),w=Ce(),y=G("Syncing wallet...");try{let S=await me().withFacade(c,l,async({bundle:b,state:v})=>{let R=jc.encode(f,v.shielded.address).asString();Ht(i,d,R);let _=v.shielded.balances[g]??0n;if(_<o){let O=Number(_)/1e6;throw Error(`Insufficient shielded balance: ${O.toFixed(6)} NIGHT available, ${s} NIGHT requested.
|
|
269
|
+
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(y.update("Checking dust..."),await et(b,(O)=>y.update(O)),n?.aborted)throw Error("Operation cancelled");y.update("Building shielded transaction...");let Z=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 L=await b.facade.signRecipe(Z,(O)=>b.keystore.signData(O));y.update("Generating ZK proof (this may take a few minutes)...");let J=await b.facade.finalizeRecipe(L),M=await Mn(y,"Submitting and waiting for finalization (typically 12 to 30s)...",b.facade.submitTransaction(J));return String(M)},{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"),T(e,"json")){P({txHash:S,amount:s,recipient:t,network:d,type:"shielded"});return}process.stdout.write(S+`
|
|
270
270
|
`),process.stderr.write(`
|
|
271
271
|
`+ut(`Transferred ${s} shielded NIGHT`,S)+`
|
|
272
272
|
`),process.stderr.write(`
|
|
273
273
|
`+z()+`
|
|
274
274
|
`),process.stderr.write(u(" 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 Lo=E(()=>{st();ke();pe();De();bn();vn();St();Ge();it();ue();Je()});async function Wf(e,t){let r=await Ze(e,t,null);try{return await r.facade.dust.serializeState()}finally{await Fe(r)}}async function Hc(e,t,r,n={}){let s=Ye(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?wo(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 Gc=E(()=>{Dt();Ge();it()});var Kc={};fe(Kc,{default:()=>er});async function er(e,t){let r=e.subcommand;if(!r||r!=="register"&&r!=="status"&&r!=="export")throw new Y(`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}=te({args:e});if(Me(s,{proofServer:
|
|
280
|
+
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=te({args:e});if(Me(s,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},n),Ie(e))Pe();let o=T(e,"json"),i=ct(e);if(r==="export"){await Bf(wn(e),n,s,o,i,t);return}let a=de(oe(x(e,"wallet"))),c=Buffer.from(a.seed,"hex"),d=a.addresses[n];if(r==="status"){let g=await Hf(d,n,s.indexerWS,t);if(!g.isRegistered){Gf(n,g,o,i);return}let h=!T(e,"no-cache");await Jf(c,s,g,o,i,h,t);return}dt(e);let l={},p=he((g,h)=>l.current?.(g,h)),f=Ce();try{await Kf(c,s,o,t,l)}finally{f(),p()}}async function Bf(e,t,r,n,s,o){let i=G(`Reading dust events from ${t}...`);try{let a=await Hc(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){P({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
|
`+A("Network",a.network)+`
|
|
283
283
|
`),process.stderr.write(A("Dust balance",br(a.balance))+`
|
|
@@ -288,12 +288,12 @@ Usage:
|
|
|
288
288
|
`+u(" Re-run `mn dust export` to resume from this checkpoint and finish.")+`
|
|
289
289
|
`);process.stderr.write(`
|
|
290
290
|
`+u("Restore with the wallet SDK dustSerializedState to skip the cold dust sync.")+`
|
|
291
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
291
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Hf(e,t,r,n){process.stderr.write(`
|
|
292
292
|
`+j("Dust Status")+`
|
|
293
293
|
|
|
294
294
|
`),process.stderr.write(A("Network",t)+`
|
|
295
295
|
|
|
296
|
-
`);let s=G(`Checking registration on ${t}...`);try{let o=await Kt(e,r,(c,d)=>{if(d>0){let l=Math.min(Math.round(c/d*100),100);s.update(l>=100?"Checking registration...":`Checking registration... ${l}%`)}});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
|
|
296
|
+
`);let s=G(`Checking registration on ${t}...`);try{let o=await Kt(e,r,(c,d)=>{if(d>0){let l=Math.min(Math.round(c/d*100),100);s.update(l>=100?"Checking registration...":`Checking registration... ${l}%`)}});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 Gf(e,t,r,n){let{registeredUtxos:s,unregisteredUtxos:o}=t,i=s+o;if(r){if(n){P({network:e,registered:!1,registeredUtxos:s,unregisteredUtxos:o});return}P({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(A("Registered",k("no"))+`
|
|
@@ -305,16 +305,16 @@ Usage:
|
|
|
305
305
|
`);process.stderr.write(`
|
|
306
306
|
`+z()+`
|
|
307
307
|
|
|
308
|
-
`)}async function
|
|
308
|
+
`)}async function Kf(e,t,r,n,s){let o=t.networkId.toLowerCase();process.stderr.write(`
|
|
309
309
|
`+j("Dust Register")+`
|
|
310
310
|
|
|
311
311
|
`),process.stderr.write(A("Network",o)+`
|
|
312
312
|
|
|
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:l})=>{if(n?.aborted)throw Error("Operation cancelled");i.update("Checking dust status...");let p=await et(d,(g)=>i.update(g),l);if(n?.aborted)throw Error("Operation cancelled");let f=await
|
|
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:l})=>{if(n?.aborted)throw Error("Operation cancelled");i.update("Checking dust status...");let p=await et(d,(g)=>i.update(g),l);if(n?.aborted)throw Error("Operation cancelled");let f=await ec(d);return{result:p,dustBal:f.dust.balance(new Date)}},{syncMode:"lite",requireStrictSync:!0,signal:n,onStatus:(d)=>i.update(d),onSyncProgress:(d,l)=>{if(l>0){let p=Math.min(Math.round(d/l*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;P(d);return}process.stdout.write(c.toString()+`
|
|
314
314
|
`),process.stderr.write(`
|
|
315
315
|
`+ut(a.alreadyAvailable?`Dust tokens already available: ${br(c)}`:`Dust tokens available: ${br(c)}`)+`
|
|
316
316
|
|
|
317
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
317
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Jf(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:l,unregisteredUtxos:p}=r;if(n){if(s){P({network:a,registered:!0,registeredUtxos:l,unregisteredUtxos:p,dustBalance:Wt(d.balance),dustAvailable:d.availableCoins>0});return}P({subcommand:"status",registered:!0,registeredUtxos:l,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=${l}
|
|
320
320
|
`),process.stdout.write(`unregistered_utxos=${p}
|
|
@@ -328,21 +328,21 @@ Usage:
|
|
|
328
328
|
`);process.stderr.write(`
|
|
329
329
|
`+z()+`
|
|
330
330
|
|
|
331
|
-
`)}catch(d){throw c.fail("Failed"),d}}var
|
|
332
|
-
`)}else if(n){if(Ke(void 0,n),ft(n)
|
|
333
|
-
`)}else{if(Ke(),ft()
|
|
334
|
-
`)}}var
|
|
335
|
-
Valid keys: ${
|
|
336
|
-
Valid keys: ${
|
|
337
|
-
`)}else if(t==="unset"){
|
|
331
|
+
`)}catch(d){throw c.fail("Failed"),d}}var Hn=E(()=>{We();st();ke();yn();pe();De();Ge();St();Or();Gc();it();ue();Je()});var Jc={};fe(Jc,{default:()=>Gn});async function Gn(e){if(e.subcommand!=="clear")throw new Y("Usage: midnight cache clear [--network <name>] [--wallet <name|file>]");let r=x(e,"wallet"),n=x(e,"network"),s=T(e,"json");if(r){let o=oe(r),i=de(o),{name:a}=te({args:e}),c=i.addresses[a];Ke(c,a);let d=Ye(Buffer.from(i.seed,"hex"));ft(a,d),$n(a,d);let l=kc(Buffer.from(i.seed,"hex"));if(Pn(a,l),s){P({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(Ke(void 0,n),ft(n),$n(n),Pn(n),s){P({action:"clear",scope:"network",network:n});return}process.stderr.write(H("✓")+` Cache cleared for network "${n}"
|
|
333
|
+
`)}else{if(Ke(),ft(),$n(),Pn(),s){P({action:"clear",scope:"all"});return}process.stderr.write(H("✓")+` Cache cleared
|
|
334
|
+
`)}}var Uo=E(()=>{We();wt();Dt();Io();Eo();ke();pe()});var Vc={};fe(Vc,{default:()=>Kn});async function Kn(e){let t=e.subcommand;if(!t||!["get","set","unset"].includes(t))throw new Y(`Usage: midnight config <get|set|unset> <key> [value]
|
|
335
|
+
Valid keys: ${Js().join(", ")}`);let r=e.positionals[0];if(!r)throw new Y(`Missing config key.
|
|
336
|
+
Valid keys: ${Js().join(", ")}`);if(t==="get"){let n=Sa(r);if(T(e,"json")){P({action:"get",key:r,value:n});return}process.stdout.write(n+`
|
|
337
|
+
`)}else if(t==="unset"){va(r);let n=r==="network"?"(default)":"(removed)";if(T(e,"json")){P({action:"unset",key:r,value:n});return}process.stderr.write(H("✓")+` ${r} ${n}
|
|
338
338
|
`)}else{let n=e.positionals[1];if(n===void 0)throw new Y(`Missing value for config set.
|
|
339
|
-
Usage: midnight config set ${r} <value>`);if(
|
|
340
|
-
`)}}var
|
|
339
|
+
Usage: midnight config set ${r} <value>`);if(ba(r,n),T(e,"json")){P({action:"set",key:r,value:n});return}process.stderr.write(H("✓")+` ${r} = ${n}
|
|
340
|
+
`)}}var jo=E(()=>{We();Bt()});import{execSync as Jr}from"child_process";import{existsSync as zc,mkdirSync as Vf,readFileSync as zf,writeFileSync as qc}from"fs";import{homedir as qf}from"os";import{join as Bo}from"path";function zn(){try{return Jr("docker compose version",{...Vn,timeout:1e4}).trim()}catch{try{throw Jr("docker --version",{...Vn,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 tr(){if(
|
|
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(zc(Wo)&&zc(Jn)&&zf(Wo,"utf-8").trim()===Xc)return!1;return Vf(Ho,{recursive:!0,mode:ye}),qc(Jn,Qf,"utf-8"),qc(Wo,Xc,"utf-8"),!0}function Ve(e){return Jr(`docker compose -f "${Jn}" ${e}`,Vn)}function at(){try{let e=Ve("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:eg[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=at();if(n.length===3&&n.every((o)=>o.state==="running")){if(n.every((i)=>i.health==="healthy"||i.health===""))return!0}Jr(`sleep ${t/1000}`,{timeout:t+1000})}return!1}function Go(){return Jn}function Yc(){let e=[];for(let t of Ko)try{Jr(`docker rm -f "${t}"`,{...Vn,timeout:1e4}),e.push(t)}catch{}return e}var Xc="3.0.6",Xf="midnightntwrk/midnight-node:1.0.0",Yf="midnightntwrk/indexer-standalone:4.3.3",Zf="midnightntwrk/proof-server:8.1.0",Ho,Jn,Wo,Qf,Vn,eg,Ko;var qn=E(()=>{Ho=Bo(qf(),ce,sa),Jn=Bo(Ho,"compose.yml"),Wo=Bo(Ho,".version"),Qf=`services:
|
|
344
344
|
proof-server:
|
|
345
|
-
image: '${
|
|
345
|
+
image: '${Zf}'
|
|
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 tr(){if(Gc(
|
|
|
353
353
|
- "6300:6300"
|
|
354
354
|
|
|
355
355
|
indexer:
|
|
356
|
-
image: '${
|
|
356
|
+
image: '${Yf}'
|
|
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 tr(){if(Gc(
|
|
|
389
389
|
condition: service_started
|
|
390
390
|
|
|
391
391
|
node:
|
|
392
|
-
image: '${
|
|
392
|
+
image: '${Xf}'
|
|
393
393
|
container_name: "node"
|
|
394
394
|
# Self-heal across Docker Desktop restarts / transient stops (see proof-server).
|
|
395
395
|
restart: unless-stopped
|
|
@@ -403,23 +403,23 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function tr(){if(Gc(
|
|
|
403
403
|
start_period: 5s
|
|
404
404
|
environment:
|
|
405
405
|
CFG_PRESET: "dev"
|
|
406
|
-
`,
|
|
407
|
-
`)}async function
|
|
406
|
+
`,Vn={encoding:"utf-8",timeout:30000};eg={node:"9944",indexer:"8088","proof-server":"6300"};Ko=["node","indexer","proof-server"]});async function Zc(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 Qc=E(()=>{Tn()});async function ed(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 td=E(()=>{Or()});async function rd(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 id={};fe(id,{default:()=>Xn});import{spawn as nd}from"child_process";import{existsSync as tg,rmSync as rg}from"node:fs";import{resolve as ng}from"node:path";function sg(e){return sd.includes(e)}function od(e){let t=[];for(let r of e){let n=r.state==="running"?H:V,s=r.health?` (${r.health})`:"",o=r.port?`:${r.port}`:"",i=r.image?` ${u(r.image)}`:"";if(t.push(` ${r.name.padEnd(16)}${n(r.state)}${u(s)}${u(o)}`),i)t.push(i)}return t.join(`
|
|
407
|
+
`)}async function og(e){if(tr())process.stderr.write(u(` Wrote compose.yml to ${Go()}`)+`
|
|
408
408
|
`);let r=G("Starting local network...");try{if(Ve("up -d"),r.update("Waiting for services to be healthy..."),!rr(120000))r.stop(F("Services started but not all healthy yet")),process.stderr.write(`
|
|
409
409
|
`+u(" Tip: run ")+k("midnight localnet logs")+u(" to check for errors")+`
|
|
410
|
-
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() =>
|
|
410
|
+
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() => Qc());await Promise.resolve().then(() => td());await Promise.resolve();await Promise.resolve().then(() => De());await Promise.resolve().then(() => He());await Promise.resolve();let p=Er("undeployed");await Zc(p.node,{timeoutMs:30000}),r.update("Waiting for indexer to ingest genesis state...");let f=ve(Buffer.from(tt,"hex"),"undeployed");await ed(p.indexerWS,f,{timeoutMs:30000}),r.update("Waiting for proof server..."),await rd(p.proofServer,{timeoutMs:30000}),r.stop("Local network is running")}catch(o){r.stop(F("Services running but chain/indexer/proof-server not fully ready yet")),process.stderr.write(`
|
|
411
411
|
`+u(" Tip: give it a few more seconds then retry. Run ")+k("midnight localnet logs")+u(" 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
416
|
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=at();if(e){P({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
|
-
`+
|
|
417
|
+
`+od(n)+`
|
|
418
418
|
`);for(let s of n)process.stdout.write(`${s.name}=${s.state}:${s.port}
|
|
419
419
|
`);process.stderr.write(`
|
|
420
420
|
`+u(" 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
|
|
421
|
+
`)}async function ig(e){let t=G("Stopping local network...");try{if(Ve("stop"),t.stop("Local network stopped (containers preserved)"),e){P({subcommand:"stop",status:"stopped"});return}}catch(r){throw t.fail("Failed to stop local network"),r}}async function ag(e){let t=G("Tearing down local network...");try{Ve("down --volumes");await Promise.resolve().then(() => wt());await Promise.resolve().then(() => Dt());Ke(void 0,"undeployed"),ft("undeployed");let s=cg();if(t.stop("Local network removed (containers, networks, volumes, caches)"),e){P({subcommand:"down",status:"removed",cachesCleared:!0,dappLevelDbWiped:s});return}if(s)process.stderr.write(u(" 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 cg(){let e=ng(process.cwd(),"midnight-level-db");if(!tg(e))return!1;try{return rg(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function dg(e){let t=at();if(e){P({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
423
|
`+j("Localnet Status")+`
|
|
424
424
|
|
|
425
425
|
`),process.stderr.write(u(" No services running.")+`
|
|
@@ -428,13 +428,13 @@ Run "midnight localnet clean" to remove them, then try again.`);if(s.message.inc
|
|
|
428
428
|
`);return}process.stderr.write(`
|
|
429
429
|
`+j("Localnet Status")+`
|
|
430
430
|
|
|
431
|
-
`),process.stderr.write(
|
|
431
|
+
`),process.stderr.write(od(t)+`
|
|
432
432
|
`),process.stderr.write(`
|
|
433
433
|
`+z()+`
|
|
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",l)})}let s=
|
|
436
|
+
`)}async function lg(e){let t=G("Removing conflicting containers...");try{try{Ve("down")}catch{}let r=Yc();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){P({subcommand:"clean",status:"cleaned",removed:r});return}}catch(r){throw t.fail("Failed to clean up"),r}}async function ug(e){let t=Go(),r=x(e,"tail"),n=T(e,"json");if(r!==void 0||n){let o=r??"200",i=nd("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,l)=>{i.on("close",(p)=>{if(p!==0&&p!==null){l(Error(`docker compose logs exited with code ${p}: ${c.trim()}`));return}if(n)P({tail:Number(o),lines:a.split(`
|
|
437
|
+
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",l)})}let s=nd("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 Xn(e){let t=e.subcommand;if(!t||!sg(t))throw new Y(`Usage: midnight localnet <${sd.join("|")}>
|
|
438
438
|
|
|
439
439
|
Subcommands:
|
|
440
440
|
up Start the local network
|
|
@@ -444,15 +444,15 @@ Subcommands:
|
|
|
444
444
|
logs Stream service logs
|
|
445
445
|
clean Remove conflicting containers
|
|
446
446
|
|
|
447
|
-
Example: midnight localnet up`);
|
|
447
|
+
Example: midnight localnet up`);zn();let r=T(e,"json");switch(process.stderr.write(`
|
|
448
448
|
`+j("Localnet")+`
|
|
449
449
|
|
|
450
|
-
`),t){case"up":return
|
|
450
|
+
`),t){case"up":return og(r);case"stop":return ig(r);case"down":return ag(r);case"status":return dg(r);case"logs":return ug(e);case"clean":return lg(r)}}var sd;var Jo=E(()=>{We();qn();ue();Je();sd=["up","stop","down","status","logs","clean"]});var dd={};fe(dd,{default:()=>nr});import*as cd from"fs";import*as Vo from"path";import{homedir as pg}from"os";import{generateMnemonic as mg,mnemonicToSeedSync as ad,mnemonicToEntropy as fg,validateMnemonic as gg}from"@scure/bip39";import{wordlist as zo}from"@scure/bip39/wordlists/english.js";async function nr(e){let t=e.subcommand;switch(t){case"generate":return hg(e);case"list":case"ls":return wg(e);case"use":return yg(e);case"info":return Sg(e);case"remove":case"rm":return bg(e);case"seed":return vg(e);default:throw new Y(`Unknown wallet subcommand: "${t??"(none)"}"
|
|
451
451
|
Available: generate, list, use, info, remove, seed
|
|
452
|
-
Run "midnight help wallet" for usage.`)}}async function
|
|
452
|
+
Run "midnight help wallet" for usage.`)}}async function hg(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
453
453
|
Usage: midnight wallet generate <name> [--network <name>]`);if(!Ct(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=
|
|
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(!
|
|
454
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=_e({args:e}),n=x(e,"seed"),s=x(e,"mnemonic");if(n!==void 0&&s!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let o=Vo.join(pg(),ce,Lt),i=Vo.join(o,`${t}.json`);if(cd.existsSync(i)&&!T(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(!gg(s,zo))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");c=s,a=Buffer.from(ad(c))}else c=mg(zo,256),a=Buffer.from(ad(c));let d=Nt(a),l=Ir(a),p=d[r],f={seed:a.toString("hex"),addresses:d,shieldedAddresses:l,createdAt:new Date().toISOString()};if(c)f.mnemonic=c;let g=un(f,i);if(Dr(t),T(e,"json")){let m={name:t,addresses:d,shieldedAddresses:l,activeAddress:p,activeNetwork:r,seed:a.toString("hex"),file:g,createdAt:f.createdAt,active:!0};if(c)m.mnemonic=c;P(m);return}process.stdout.write(p+`
|
|
456
456
|
`),process.stderr.write(`
|
|
457
457
|
`+j("Wallet Generated")+`
|
|
458
458
|
|
|
@@ -473,7 +473,7 @@ Use --force to overwrite.`);let a,c;if(n!==void 0){let m=n.replace(/^0x/,"");if(
|
|
|
473
473
|
`),process.stderr.write(u(" Next: midnight wallet list | midnight balance")+`
|
|
474
474
|
|
|
475
475
|
`),process.stderr.write(H("✓")+` Wallet saved
|
|
476
|
-
`)}async function
|
|
476
|
+
`)}async function wg(e){let t=Zs(),r=_e({args:e});if(T(e,"json")){if(ct(e)){P({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}P({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(u(" Create one: midnight wallet generate <name> --network <name>")+`
|
|
479
479
|
|
|
@@ -486,9 +486,9 @@ Use --force to overwrite.`);let a,c;if(n!==void 0){let m=n.replace(/^0x/,"");if(
|
|
|
486
486
|
`+z()+`
|
|
487
487
|
`),process.stderr.write(u(` ● = 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 yg(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
490
|
+
Usage: midnight wallet use <name>`);if(Dr(t),T(e,"json")){P({wallet:t,active:!0});return}process.stderr.write(H("✓")+` Active wallet set to "${t}"
|
|
491
|
+
`)}async function Sg(e){let t=x(e,"wallet")??e.positionals[0]??mt(),r=oe(t),n=de(r),s=t===mt(),o=_e({args:e}),i=n.addresses[o];if(T(e,"json")){if(ct(e)){P({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;P(c);return}process.stdout.write(i+`
|
|
492
492
|
`),process.stderr.write(`
|
|
493
493
|
`+j(`Wallet: ${t}`)+`
|
|
494
494
|
|
|
@@ -504,15 +504,15 @@ Usage: midnight wallet use <name>`);if(_r(t),T(e,"json")){P({wallet:t,active:!0}
|
|
|
504
504
|
`),process.stderr.write(` ${u("file ")} ${r}
|
|
505
505
|
`),process.stderr.write(` ${u("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 bg(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
508
|
+
Usage: midnight wallet remove <name>`);if(Na(t),T(e,"json")){P({wallet:t,removed:!0});return}process.stderr.write(H("✓")+` Wallet "${t}" removed
|
|
509
|
+
`)}async function vg(e){let t=x(e,"wallet")??e.positionals[0]??mt(),r=oe(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=T(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(fg(s.mnemonic,zo)).toString("hex")}if(T(e,"json")){let c={name:t,seed:s.seed};if(s.mnemonic)c.mnemonic=s.mnemonic;if(i)c.entropy=i;P(c);return}if(process.stderr.write(`
|
|
511
511
|
`),process.stderr.write(F(k(" ⚠ WARNING: This will display your wallet seed and mnemonic."))+`
|
|
512
512
|
`),process.stderr.write(F(" Anyone with this seed can access your funds.")+`
|
|
513
513
|
`),process.stderr.write(F(" Never share it. Never paste it into a website.")+`
|
|
514
514
|
`),process.stderr.write(`
|
|
515
|
-
`),!await
|
|
515
|
+
`),!await kg(" Show seed? (y/N) ")){process.stderr.write(u(" Cancelled.")+`
|
|
516
516
|
|
|
517
517
|
`);return}if(process.stdout.write(s.seed+`
|
|
518
518
|
`),process.stderr.write(`
|
|
@@ -525,51 +525,51 @@ Usage: midnight wallet remove <name>`);if(xa(t),T(e,"json")){P({wallet:t,removed
|
|
|
525
525
|
`),process.stderr.write(u(" Note: seed and entropy derive DIFFERENT Midnight wallets from the")+`
|
|
526
526
|
`),process.stderr.write(u(" same mnemonic. Use the value your target project accepts.")+`
|
|
527
527
|
`);process.stderr.write(`
|
|
528
|
-
`)}function
|
|
528
|
+
`)}function kg(e){return new Promise((t)=>{let r=Is("readline"),n=r.createInterface({input:process.stdin,output:process.stderr});n.question(e,(s)=>{n.close(),t(s.trim().toLowerCase()==="y")})})}var Yn=E(()=>{We();He();pe();ke();ue()});var fd={};fe(fd,{default:()=>md});function Xo(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 qo(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=`${an}${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 xg(e){let t=x(e,"network");if(t)return t;try{await Promise.resolve().then(() => Bt());let n=Te();if(n.network&&xe(n.network))return n.network}catch{}return}async function es(e,t={}){let r=new AbortController,n=setTimeout(()=>r.abort(),Eg),s=Date.now();try{return{response:await fetch(e,{...t,signal:r.signal}),latencyMs:Date.now()-s}}finally{clearTimeout(n)}}async function Tg(e){let t=new Date().toISOString();try{let{response:r,latencyMs:n}=await es(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 Ng(e){let t=new Date().toISOString(),r=e.replace(/^wss:/,"https:").replace(/^ws:/,"http:");try{let{response:n,latencyMs:s}=await es(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",l;if(c)d="degraded",l="Node is syncing";else if(a===0)d="degraded",l="No peers";return{status:d,latencyMs:s,lastChecked:t,peers:a,isSyncing:c,...l?{notes:l}:{}}}catch(n){return{status:"down",latencyMs:0,lastChecked:t,notes:n.message}}}async function Rg(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 es(e);if(!r.ok)return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`};return{status:n>ud?"degraded":"up",latencyMs:n,lastChecked:t,...n>ud?{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 es(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 pd(e){if(!xe(e))return{};let t=Er(e),r=Cg[e];if(!r)return{};let[n,s,o,i]=await Promise.all([Tg(t.indexer),Ng(t.node),Rg(r.faucet),Ig(r.explorer)]);return{indexer:n,rpc:s,faucet:o,explorer:i}}function $g(e,t,r){process.stderr.write(`
|
|
529
529
|
`+k(e)+`
|
|
530
530
|
`),process.stderr.write(u(" "+"─".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
|
|
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=(Ag[s]??s).padEnd(18);if(o){let c=ld[o.status]??u("—"),d=o.latencyMs>0?u(` ${o.latencyMs}ms`):"",l=o.notes?u(` — ${o.notes}`):"",p="";if(i&&i.status!==o.status&&i.status!=="unknown")p=u(` (canary: ${i.status}${i.lastChecked?" "+Xo(i.lastChecked):""})`);process.stderr.write(` ${rt(a)}${c}${d}${l}${p}
|
|
532
|
+
`)}else if(i){let c=ld[i.status]??u("—"),d=i.latencyMs>0?u(` ${i.latencyMs}ms`):"",l=i.lastChecked?u(` (${Xo(i.lastChecked)})`):"",p=i.notes?u(` — ${i.notes}`):"";process.stderr.write(` ${rt(a)}${c}${d}${l}${p}
|
|
533
|
+
`)}}}function Dg(e,t){let r=t?e.filter((n)=>n.affects.toLowerCase().includes(t.toLowerCase())):e;if(r.length===0)return;process.stderr.write(`
|
|
534
534
|
`+j("Known Issues")+`
|
|
535
535
|
|
|
536
536
|
`);for(let n of r)process.stderr.write(` ${V(n.id.padEnd(28))}${n.summary}
|
|
537
537
|
`),process.stderr.write(` ${" ".repeat(28)}${u(n.status)}
|
|
538
|
-
`)}async function
|
|
538
|
+
`)}async function md(e){let t=T(e,"json"),r=T(e,"all"),n=T(e,"watch"),s=await xg(e)??"preprod",o=G("Checking network status..."),i=null,a=null,c,d;if(r)d=["preprod","preview"];else d=[s];let[l,...p]=await Promise.all([Promise.all([Zn("/api/status"),Zn("/api/issues")]).catch((m)=>(c=m.message,null)),...d.map((m)=>pd(m))]);if(l)[i,a]=l;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:an,canaryAvailable:i!==null,networks:{}};for(let y of d){let S=f[y]??{},b=i?.networks[y],v={...b,...S};m.networks[y]={overall:qo(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;P(m);let w=d.reduce((y,S)=>{let b={...i?.networks[S]??{},...f[S]??{}},v=qo(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
539
|
`+j("Midnight Network Status")+`
|
|
540
|
-
`),i?.lastUpdated)process.stderr.write(u(` Canary: ${
|
|
540
|
+
`),i?.lastUpdated)process.stderr.write(u(` Canary: ${Xo(i.lastUpdated)}`)+" ");if(process.stderr.write(u("Live: just now")+`
|
|
541
541
|
`),c)process.stderr.write(u(` (Dashboard unreachable: ${c})`)+`
|
|
542
542
|
`);if(d.length===0){process.stderr.write(`
|
|
543
543
|
`+u("No network data available.")+`
|
|
544
544
|
|
|
545
|
-
`);return}for(let m of d)
|
|
545
|
+
`);return}for(let m of d)$g(m,i?.networks[m],f[m]??{});if(a){let m=r?void 0:d[0];Dg(a.issues,m)}process.stderr.write(`
|
|
546
546
|
`+z()+`
|
|
547
547
|
`),process.stderr.write(u(" Dashboard: ")+U(an)+`
|
|
548
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((l)=>l!==a),d=sr(s,a,"compiler",
|
|
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&&
|
|
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)=>pd(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(u(" 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=qo(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 Cg,Ag,ld,Eg=15000,Qn=5000,ud=1e4;var gd=E(()=>{De();ue();Je();Cg={preprod:{faucet:"https://faucet.preprod.midnight.network/",explorer:"https://preprod.midnightexplorer.com/"},preview:{faucet:"https://faucet.preview.midnight.network/",explorer:null},undeployed:{faucet:"",explorer:""}},Ag={indexer:"Indexer",rpc:"RPC Node",faucet:"Faucet",explorer:"Explorer",chain:"Chain",dust:"Dust Generation",wallet:"Wallet Ops",dapp:"DApp Flow"},ld={up:H("UP"),down:V("DOWN"),degraded:k("\x1B[33mDEGRADED\x1B[0m"),unknown:u("—")}});import{existsSync as Yo,readFileSync as _g,readdirSync as Pg}from"node:fs";import{join as sr,basename as Og}from"node:path";function ze(e,t){let r=sr(e,"compiler",ts);if(Yo(r))return wd(r,e,[]);for(let n of hd){let s=n?sr(e,n,"managed"):sr(e,"managed");if(!Yo(s))continue;let o;try{o=Pg(s).sort()}catch{continue}let i=o.filter((l)=>Yo(sr(s,l,"compiler",ts)));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((l)=>l!==a),d=sr(s,a,"compiler",ts);return wd(d,sr(s,a),c)}throw Error(`No compiled contract found in ${e}
|
|
552
|
+
Expected: managed/<name>/compiler/${ts}
|
|
553
|
+
Searched: ${hd.map((n)=>n?`${n}/managed/`:"managed/").join(", ")}
|
|
554
|
+
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function wd(e,t,r){let n;try{n=JSON.parse(_g(e,"utf-8"))}catch(o){throw Error(`Failed to parse ${e}: ${o.message}`)}return{info:Mg(n,e,t,r),infoPath:e}}function Mg(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:Og(r),managedDir:r,compilerVersion:o,languageVersion:i,runtimeVersion:a,circuits:c,witnesses:d,siblings:n}}function Oe(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(Oe).join(", ")}]`;case"Boolean":return"boolean";case"String":return"string";case"Vector":return e.types?.[0]?`${Oe(e.types[0])}[]`:"unknown[]";case"Map":if(e.types&&e.types.length>=2)return`Map<${Oe(e.types[0])}, ${Oe(e.types[1])}>`;return"Map<unknown, unknown>";case"Set":return e.types?.[0]?`Set<${Oe(e.types[0])}>`:"Set<unknown>";case"Option":return e.types?.[0]?`${Oe(e.types[0])} | null`:"unknown | null";default:return e["type-name"]??"unknown"}}function yd(e){let t=e.arguments.map((r)=>`${r.name}: ${Oe(r.type)}`).join(", ");return`${e.name}(${t})`}function Sd(e){if(e.pure)return"pure";let t=["impure"];if(e.proof)t.push("proof");return t.join(", ")}function bd(e){let t=e.arguments.map((s)=>`${s.name}: ${Oe(s.type)}`).join(", "),r=Oe(e["result type"]),n=r!=="void"?` → ${r}`:"";return`${e.name}(${t})${n}`}function vd(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:Oe(r.type)})),returnType:Oe(t["result-type"])})),witnesses:e.witnesses.map((t)=>({name:t.name,arguments:t.arguments.map((r)=>({name:r.name,type:Oe(r.type)})),returnType:Oe(t["result type"])}))}}var ts="contract-info.json",hd;var Vr=E(()=>{hd=["","contract/src","contract","contracts/src","contracts","src"]});import*as kd from"node:readline";function Ug(e){return Fg.has(e)}function jg(e){return Lg.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(` ${u("Action:")} ${U(e.method)}`),t.push(` ${u("Network:")} ${e.network}`),e.details.length>0){t.push("");for(let n of e.details)t.push(` ${u(n.label+":")} ${n.value}`)}return t.push(""),t.push(` ${H("[A]pprove")} ${V("[R]eject")}`),ca(t,"heavy")}async function Cd(e,t={}){if(t.approveAll)return process.stderr.write(u(` Auto-approved: ${e.method}`)+`
|
|
555
|
+
`),"approve";if(t.autoApproveReads&&Ug(e.method))return process.stderr.write(u(` Auto-approved (read-only): ${e.method}`)+`
|
|
556
556
|
`),"approve";if(!process.stdin.isTTY){process.stderr.write(V(" Cannot prompt for approval: stdin is not a TTY")+`
|
|
557
|
-
`);let n=
|
|
557
|
+
`);let n=jg(e.method)?"Balancing prompts like any other write":`${e.method} needs a terminal to approve`;return process.stderr.write(u(` ${n}: use --approve-all for non-interactive environments`)+`
|
|
558
558
|
`),"reject"}if(zr)return process.stderr.write(V(" Rejected: another approval prompt is active")+`
|
|
559
559
|
`),"reject";process.stderr.write(`
|
|
560
|
-
`+
|
|
561
|
-
|
|
562
|
-
`),zr=!0;let r;try{r=
|
|
563
|
-
`),"reject"}return new Promise((n)=>{let s=(o)=>{zr=!1,r.close(),n(o)};r.on("close",()=>{if(zr)s("reject")}),r.question(F(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var
|
|
564
|
-
`)}),c.on("connection",(l)=>{let p=`conn_${++
|
|
565
|
-
`)},
|
|
566
|
-
`)}function S(){return new Date(Date.now()+wr*60*1000)}async function b(I,C){C?.start("signing");let N=await
|
|
567
|
-
`),!await M(
|
|
568
|
-
`)}};function le(){p.unsubscribe();for(let[,I]of h)for(let[,C]of I)clearTimeout(C.timer);h.clear()}function Ft(){for(let[,I]of h)if(I.size>0)return!0;return!1}return{handlers:Q,revertPendingTxs:y,hasPendingTxs:Ft,dispose:le}}var
|
|
569
|
-
`)}var
|
|
570
|
-
${r}`)}}async function
|
|
571
|
-
${n}`)}}async function
|
|
572
|
-
${r}`)}}function
|
|
560
|
+
`+Wg(e)+`
|
|
561
|
+
|
|
562
|
+
`),zr=!0;let r;try{r=kd.createInterface({input:process.stdin,output:process.stderr})}catch{return zr=!1,process.stderr.write(V(" Cannot create readline interface")+`
|
|
563
|
+
`),"reject"}return new Promise((n)=>{let s=(o)=>{zr=!1,r.close(),n(o)};r.on("close",()=>{if(zr)s("reject")}),r.question(F(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var Fg,Lg,zr=!1;var Ad=E(()=>{ue();Fg=new Set(["getShieldedBalances","getUnshieldedBalances","getDustBalance","getShieldedAddresses","getUnshieldedAddress","getDustAddress","getTxHistory","getConfiguration","getConnectionStatus"]),Lg=new Set(["balanceUnsealedTransaction","balanceSealedTransaction"])});import{WebSocketServer as Bg}from"ws";function Gg(e){if(Zo(e))return Hg[e.code]??-32603;return-32603}function Zo(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="DAppConnectorAPIError"}function Kg(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 rs(e,t){if(typeof t==="bigint")return t.toString();return t}function Jg(e,t){return t}function Vg(e){let t;try{t=JSON.parse(e,Jg)}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 ns(e){let{port:t,handlers:r,onConnect:n,onDisconnect:s,onRequest:o,onResponse:i}=e,a=new Map,c=new Bg({port:t,host:"127.0.0.1"});c.on("error",(l)=>{process.stderr.write(`WebSocket server error: ${l.message}
|
|
564
|
+
`)}),c.on("connection",(l)=>{let p=`conn_${++zg}`,f={ws:l,id:p,connectedAt:new Date,authenticated:!1,requestCount:0,notify(m,w){if(l.readyState!==l.OPEN)return;let y={jsonrpc:"2.0",method:m,...w&&{params:w}};l.send(JSON.stringify(y,rs))}};a.set(p,f),n?.(f);let g=!1,h=()=>{if(g)return;g=!0,a.delete(p),s?.(f)};l.on("message",async(m)=>{let w=null,y,S,b=Date.now();try{y=Vg(m.toString("utf-8")),w=y.id,f.requestCount++,o?.(f,y);let v=r[y.method];if(!v){let L={jsonrpc:"2.0",id:y.id,error:{code:-32601,message:`Method not found: ${y.method}`}};l.send(JSON.stringify(L,rs));return}S={notify:f.notify.bind(f),connectionId:p,requestId:y.id,metadata:{}};let R=await v(y.params??{},S),_=Date.now()-b;if(y.method==="connect"&&R&&typeof R==="object")f.authenticated=!0,f.networkId=R.networkId;let Z={jsonrpc:"2.0",id:y.id,result:R};l.send(JSON.stringify(Z,rs)),i?.(f,y,_,R,void 0,S.metadata)}catch(v){let R=Date.now()-b,_=v?.rpcCode??Gg(v),Z=v instanceof Error?v.message:"Internal error",L=Zo(v)?{type:v.type,code:v.code}:Kg(v),J={jsonrpc:"2.0",id:w,error:{code:_,message:Z,data:L}};if(l.send(JSON.stringify(J,rs)),y){let M={message:Z,code:Zo(v)?v.code:void 0};i?.(f,y,R,void 0,M,S?.metadata)}}}),l.on("close",h),l.on("error",()=>{h();try{l.close()}catch{}})});async function d(){for(let l of a.values())l.ws.close(1001,"Server shutting down");return a.clear(),new Promise((l,p)=>{c.close((f)=>{if(f)p(f);else l()})})}return{wss:c,connections:a,close:d}}function Re(e,t){let r=Error(t);return r.type="DAppConnectorAPIError",r.code=e,r.reason=t,r}var Hg,zg=0;var ss=E(()=>{Hg={Rejected:-32000,PermissionRejected:-32001,Disconnected:-32002,InvalidRequest:-32602,InternalError:-32603}});function Ed(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 xd}from"@midnight-ntwrk/ledger-v8";function Qo(e){return Buffer.from(e).toString("hex")}function os(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 Rd(e){return Qo(e.serialize())}function qr(e){return xd.deserialize(Td,Nd,Xg,os(e))}function ei(e){return xd.deserialize(Td,Nd,qg,os(e))}var Td="signature",Nd="proof",qg="binding",Xg="pre-binding";var ti=()=>{};function Id(e){let t=Buffer.from(`midnight_signed_message:${e.length}:`,"utf-8");return new Uint8Array(Buffer.concat([t,e]))}function Yg(e){let t=[];for(let r of e.intents?.values()??[])for(let n of[r.guaranteedUnshieldedOffer,r.fallibleUnshieldedOffer])n?.inputs.forEach((s,o)=>t.push(n.signatures[o]!==void 0));return t}function $d(e){let t=Yg(e),r=t.filter(Boolean).length;if(r===0)return"none";return r===t.length?"all":"some"}function Qg(e){return[...new Set([Zg,...e.intents?.keys()??[],...e.fallibleOffer?.keys()??[]])].filter((r)=>[...e.imbalances(r)].some(([n,s])=>n.tag==="unshielded"&&s!==0n))}function Dd(e){let t=$d(e);if(t==="some")throw new or;if(t==="all"){let r=Qg(e);if(r.length>0)throw new Xr(r)}}async function _d(e,t,r){if(t.type!=="UNBOUND_TRANSACTION")return e.signRecipe(t,r);let n=$d(qr(Qo(t.baseTransaction.serialize())));if(n==="none")return e.signRecipe(t,r);if(n==="some")throw new or;if(!t.balancingTransaction)return t;let s=await e.signRecipe({type:"UNPROVEN_TRANSACTION",transaction:t.balancingTransaction},r);if(s.type!=="UNPROVEN_TRANSACTION")throw Error(`The wallet SDK signed an unproven transaction into a ${s.type} recipe`);return{...t,balancingTransaction:s.transaction}}var or,Xr,Zg=0;var Pd=E(()=>{ti();or=class or extends Error{constructor(){super("The transaction has both signed and unsigned unshielded inputs. This wallet can't add its signatures to it without duplicating the existing ones (a wallet SDK limitation): send it with every unshielded input signed, or with none signed.");this.name="PartlySignedTransactionError",Object.setPrototypeOf(this,or.prototype)}};Xr=class Xr extends Error{constructor(e){super(`The transaction's unshielded inputs are already signed, but segment ${e.join(", ")} is not balanced in unshielded value. This wallet balances it by adding inputs and outputs to the same intent, which invalidates those signatures. Leave the unshielded inputs unsigned so they are signed after balancing, or balance the sealed transaction with balanceSealedTransaction, which adds a separate intent.`);this.name="SignedTransactionNeedsUnshieldedError",Object.setPrototypeOf(this,Xr.prototype)}}});import{Transaction as eh}from"@midnight-ntwrk/ledger-v8";function is(e,t){let r=[];r.push({label:"Tx size",value:sh(e.length/2)});let n=th(e,t);if(n){let s=rh(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 th(e,t){let r=nh(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 eh.deserialize(s,o,i,r).toString(!0)}catch{}return null}function rh(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 nh(e){return new Uint8Array(Buffer.from(e,"hex"))}function sh(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 Od=()=>{};import{DustLocalState as oh}from"@midnight-ntwrk/ledger-v8";import{CoreWallet as qe}from"@midnight-ntwrk/wallet-sdk-dust-wallet/v1";var Pt,ih,ah,N0;var Md=E(()=>{Pt=new Map,ih=qe.applyEventsWithChanges;qe.applyEventsWithChanges=function(t,r,n,s){let o=ih.call(qe,t,r,n,s),i=Array.isArray(o)?o[0]:o;if(Pt.size>0&&i?.pendingDust){let a=new Set(i.pendingDust.map((c)=>c.nullifier));for(let c of Pt.keys())if(!a.has(c))Pt.delete(c)}return o};ah=qe.spendCoins;qe.spendCoins=function(t,r,n,s){let o=null;try{o=t.state.serialize()}catch{}let i=ah.call(qe,t,r,n,s),a=i[1]??i;if(o&&a?.pendingDust){for(let c of a.pendingDust)if(!Pt.has(c.nullifier))Pt.set(c.nullifier,o)}return i};N0=qe.revertTransaction;qe.revertTransaction=function(t,r){let n=qe.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=Pt.get(a);if(c){try{i=oh.deserialize(c)}catch{}Pt.delete(a)}}return{...t,state:i,pendingDust:t.pendingDust.filter((a)=>!s.includes(a.nullifier))}};qe.applyFailed=qe.revertTransaction});import*as Ot from"rxjs";import{MidnightBech32m as ri,UnshieldedAddress as ch,ShieldedAddress as dh}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as ni}from"@midnight-ntwrk/wallet-sdk-abstractions";function uh(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 as(e){let{bundle:t,networkConfig:r,approvalOptions:n,callbacks:s}=e,{facade:o,keystore:i,zswapSecretKeys:a,dustSecretKey:c}=t,d=lh[r.networkId];if(d===void 0)throw Error(`Unknown networkId: ${r.networkId}`);let l,p=o.state().pipe(Ot.filter((I)=>I.isSynced)).subscribe((I)=>{l=I});function f(){if(!l)throw Re("Disconnected","Wallet not synced yet");return l}let g={shieldedSecretKeys:a,dustSecretKey:c},h=new Map;function m(I,C,N){let D=h.get(I);if(!D)D=new Map,h.set(I,D);let B=setTimeout(async()=>{if(D.delete(C),D.size===0)h.delete(I);try{await o.revert(N)}catch{}process.stderr.write(u(` abandoned tx reverted (${I})`)+`
|
|
565
|
+
`)},oa);D.set(C,{recipe:N,timer:B})}function w(I,C){let N=h.get(I);if(!N)return;let D=N.get(C);if(D)clearTimeout(D.timer),N.delete(C);if(N.size===0)h.delete(I)}async function y(I){let C=h.get(I);if(!C||C.size===0)return;h.delete(I);for(let[,N]of C){clearTimeout(N.timer);try{await o.revert(N.recipe)}catch{}}process.stderr.write(u(` reverted ${C.size} pending tx(s) on disconnect`)+`
|
|
566
|
+
`)}function S(){return new Date(Date.now()+wr*60*1000)}async function b(I,C){C?.start("signing");let N=await _d(o,I,(K)=>i.signData(K));C?.start("proving");let D,B=await Promise.race([o.finalizeRecipe(N),new Promise((K,ie)=>{D=setTimeout(()=>ie(Error("ZK proof generation timed out")),sn)})]);return clearTimeout(D),C?.complete(),{hex:Rd(B),finalized:B}}function v(I){let C;try{C=qr(I)}catch{return}try{Dd(C)}catch(N){if(N instanceof or||N instanceof Xr)throw Re("InvalidRequest",N.message);throw N}}async function R(I,C=[],N){N?.notify("approval:pending",{method:I});let D=await Cd({method:I,network:r.networkId,details:C,dappName:N?.connectionId},n),B=D==="reject"?"rejected":"approved";if(N?.notify("approval:resolved",{method:I,result:B}),D==="reject")throw Re("Rejected","User rejected the request")}function _(I){return ri.encode(d,I).asString()}function Z(I){let C={};for(let N of I){let D=N.kind;if(D!=="shielded"&&D!=="unshielded")throw Re("InvalidRequest",`Invalid output kind: "${D}" — must be "shielded" or "unshielded"`);if(!C[D])C[D]=[];let B=BigInt(N.value),K;if(D==="unshielded")K=ri.parse(N.recipient).decode(ch,d);else K=ri.parse(N.recipient).decode(dh,d);C[D].push({type:N.type,receiverAddress:K,amount:B})}return Object.entries(C).map(([N,D])=>({type:N,outputs:D}))}function L(I,C){return Ed({onStart:(N)=>{let D=C?.connectionId??"unknown";s?.onPhaseStart?.(D,I,N),C?.notify("progress",{method:I,phase:N,status:"started"})},onComplete:(N,D)=>{let B=C?.connectionId??"unknown";s?.onPhaseComplete?.(B,I,N,D),C?.notify("progress",{method:I,phase:N,status:"completed",durationMs:D})}})}function J(){if(!l)return!1;try{let I=l.dust;return I?.availableCoins?.length>0||I?.balance(new Date)>0n}catch{return!1}}async function M(I){return new Promise((C)=>{if(J()){C(!0);return}let N=o.state().pipe(Ot.filter(()=>J()),Ot.take(1),Ot.timeout(I)).subscribe({next:()=>{N.unsubscribe(),C(!0)},error:()=>{N.unsubscribe(),C(!1)}})})}async function O(I){for(let C=1;C<=Sr;C++)try{return await I()}catch(N){let D=String(N?.message??N??"");if(!(/no dust tokens/i.test(D)||/dust.*unavailable/i.test(D))||C===Sr)throw N;if(process.stderr.write(u(` dust unavailable, waiting for recovery (${C}/${Sr})... [${D.slice(0,60)}]`)+`
|
|
567
|
+
`),!await M(Ls)&&C<Sr)await new Promise((ie)=>setTimeout(ie,Ls))}throw Error("unreachable")}let Q={connect:async(I)=>{let C=String(I.networkId??"");if(C.toLowerCase()!==r.networkId.toLowerCase())throw Re("InvalidRequest",`Network mismatch: wallet is on ${r.networkId}, requested ${C}`);return{networkId:r.networkId}},getUnshieldedBalances:async()=>f().unshielded.balances,getShieldedBalances:async()=>f().shielded.balances,getDustBalance:async()=>{let C=f().dust.balance(new Date);return{cap:C,balance:C}},getUnshieldedAddress:async()=>{let I=f();return{unshieldedAddress:_(I.unshielded.address)}},getShieldedAddresses:async()=>{let C=f().shielded.address;return{shieldedAddress:_(C),shieldedCoinPublicKey:C.coinPublicKeyString(),shieldedEncryptionPublicKey:C.encryptionPublicKeyString()}},getDustAddress:async()=>{let I=f();return{dustAddress:_(I.dust.address)}},getTxHistory:async(I)=>{let C=f(),N=Number(I.pageNumber??0),D=Number(I.pageSize??20);try{let B=C.unshielded.transactionHistory,K=[],ie=0,ee=N*D;for await(let ae of B.getAll()){if(ie>=ee+D)break;if(ie>=ee)K.push({txHash:ae.hash,txStatus:ae.status==="SUCCESS"?{status:"finalized"}:{status:"pending"}});ie++}return K}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,C)=>{let N=I.desiredOutputs;if(!Array.isArray(N)||N.length===0)throw Re("InvalidRequest","desiredOutputs must be a non-empty array");let D=L("makeTransfer",C),B=N.map((Ue,Ae)=>({label:`Output ${Ae+1}`,value:`${Ue.value} → ${String(Ue.recipient).slice(0,20)}... (${Ue.kind})`}));D.start("approve"),await R("makeTransfer",B,C),D.start("building");let K=Z(N),ie=I.options?.payFees??!0,ee=await O(()=>o.transferTransaction(K,g,{ttl:S(),payFees:ie})),{hex:ae,finalized:Ee}=await b(ee,D);return m(C.connectionId,ae,ee),C.metadata.phases=D.getTimings(),{tx:ae}},submitTransaction:async(I,C)=>{let N=String(I.tx??"");if(!N)throw Re("InvalidRequest","tx is required");let D=L("submitTransaction",C);D.start("approve");try{await R("submitTransaction",is(N,"sealed"),C)}catch(K){let ee=h.get(C.connectionId)?.get(N);if(ee)try{await o.revert(ee.recipe)}catch{}throw w(C.connectionId,N),K}let B=ei(N);D.start("submitting");try{let K=await o.submitTransaction(B);return D.complete(),w(C.connectionId,N),C.metadata.phases=D.getTimings(),{txHash:K}}catch(K){D.complete();let ee=h.get(C.connectionId)?.get(N);if(ee)try{await o.revert(ee.recipe)}catch{}w(C.connectionId,N);let ae=uh(K),Ee=Error(`Transaction submission failed: ${ae}`);throw Ee.cause=K,Ee}},balanceUnsealedTransaction:async(I,C)=>{let N=String(I.tx??"");if(!N)throw Re("InvalidRequest","tx is required");v(N);let D=L("balanceUnsealedTransaction",C);D.start("approve"),await R("balanceUnsealedTransaction",is(N,"unsealed"),C),D.start("building");let B=qr(N),K=await O(()=>o.balanceUnboundTransaction(B,g,{ttl:S()})),{hex:ie,finalized:ee}=await b(K,D);return m(C.connectionId,ie,K),C.metadata.phases=D.getTimings(),{tx:ie}},balanceSealedTransaction:async(I,C)=>{let N=String(I.tx??"");if(!N)throw Re("InvalidRequest","tx is required");let D=L("balanceSealedTransaction",C);D.start("approve"),await R("balanceSealedTransaction",is(N,"sealed"),C),D.start("building");let B=ei(N),K=await O(()=>o.balanceFinalizedTransaction(B,g,{ttl:S()})),{hex:ie,finalized:ee}=await b(K,D);return m(C.connectionId,ie,K),C.metadata.phases=D.getTimings(),{tx:ie}},makeIntent:async(I,C)=>{let{desiredInputs:N,desiredOutputs:D,options:B}=I;if(!B)throw Re("InvalidRequest","options is required for makeIntent");let K=L("makeIntent",C);K.start("approve"),await R("makeIntent",[],C),K.start("building");let ie={};if(Array.isArray(N))for(let Ae of N){let Rs=Ae.kind;if(!ie[Rs])ie[Rs]={};ie[Rs][Ae.type]=BigInt(Ae.value)}let ee=Z(D??[]),ae=await O(()=>o.initSwap(ie,ee,g,{ttl:S(),payFees:B.payFees??!0})),{hex:Ee,finalized:Ue}=await b(ae,K);return m(C.connectionId,Ee,ae),C.metadata.phases=K.getTimings(),{tx:Ee}},signData:async(I,C)=>{let N=String(I.data??""),D=I.options;if(!N||!D?.encoding)throw Re("InvalidRequest","data and options.encoding are required");if(D.keyType&&D.keyType!=="unshielded")throw Re("InvalidRequest",`Unsupported keyType: "${D.keyType}" — only "unshielded" is supported`);await R("signData",[{label:"Encoding",value:D.encoding},{label:"Data",value:N.length>64?N.slice(0,64)+"...":N}],C);let B;switch(D.encoding){case"hex":B=os(N);break;case"base64":B=new Uint8Array(Buffer.from(N,"base64"));break;case"text":B=new Uint8Array(Buffer.from(N,"utf-8"));break;default:throw Re("InvalidRequest",`Unknown encoding: ${D.encoding}`)}let K=i.signData(Id(B)),ie=i.getPublicKey();return{data:N,signature:String(K),verifyingKey:String(ie)}},getProvingProvider:async()=>({provingProvider:"ready",proverServerUri:r.proofServer}),hintUsage:async(I)=>{let C=I.methodNames??[];process.stderr.write(u(` DApp hints usage: ${C.join(", ")}`)+`
|
|
568
|
+
`)}};function le(){p.unsubscribe();for(let[,I]of h)for(let[,C]of I)clearTimeout(C.timer);h.clear()}function Ft(){for(let[,I]of h)if(I.size>0)return!0;return!1}return{handlers:Q,revertPendingTxs:y,hasPendingTxs:Ft,dispose:le}}var lh;var si=E(()=>{Ad();ss();ti();Pd();Od();Md();lh={PreProd:ni.NetworkId.PreProd,Preview:ni.NetworkId.Preview,Undeployed:ni.NetworkId.Undeployed}});import{Socket as ph}from"node:net";function mh(e){return new Promise((t)=>{let r=new ph;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 fh(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 cs(e){let t=e.port??At,r=(e.network??"undeployed").toLowerCase(),n=e.onMessage??(()=>{});if(await mh(t)){let s=await fh(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 gh(e)}async function gh(e){let t=e.port??At,r=e.onMessage??(()=>{}),n=de(oe(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 l=ht(a,o),p=await Ze(s,i,l);r("Syncing wallet..."),await gt(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 Le(a,o,p.facade)}catch{}let f=as({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=ns({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 Fe(p)}catch{}}}}var oi=E(()=>{ke();pe();Ge();wt();St();si();ss()});import{existsSync as Fd}from"node:fs";import{join as Ld}from"node:path";function ls(e){for(let t of ds){let r=Ld(e,t);if(Fd(r))return r}return null}function wh(e){for(let t of hh){let r=Ld(e,t);if(Fd(r))return r}return null}function us(e){let{projectRoot:t,witnessNames:r}=e,n=wh(t),s=[`Contract declares ${r.length} witness(es): ${r.join(", ")}`,"but no compiled witnesses module was found.","",`Searched (relative to ${t}):`,...ds.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 ds,hh;var ps=E(()=>{ds=["dist/witnesses.js","src/witnesses.js","contract/dist/witnesses.js","contract/src/witnesses.js"],hh=["src/witnesses.ts","contract/src/witnesses.ts"]});function ms(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(ms)}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]=ms(e[r]);return t}return e}function Ud(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 yh}from"node:child_process";import{writeFileSync as Sh,unlinkSync as jd,existsSync as fs,symlinkSync as Wd}from"node:fs";import{join as Yr,dirname as Bd}from"node:path";import{fileURLToPath as bh}from"node:url";function vh(){let e=Bd(bh(import.meta.url));for(let t=0;t<8;t++){let r=Yr(e,"node_modules");if(fs(r))return r;let n=Bd(e);if(n===e)break;e=n}return null}async function ir(e){let t=Eh(e),r=await ai(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`State script returned unexpected output:
|
|
570
|
+
${r}`)}}async function gs(e){let t=Ch(e),r=e.privateStateSecretKey?{MN_PRIVATE_STATE_SECRET:e.privateStateSecretKey}:void 0,n=await ai(e.dappDir,t,e.onMessage,r);try{return JSON.parse(n)}catch{throw Error(`Deploy script returned unexpected output:
|
|
571
|
+
${n}`)}}async function hs(e){let t=Ah(e),r=await ai(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`Call script returned unexpected output:
|
|
572
|
+
${r}`)}}function Hd(e){return`
|
|
573
573
|
import WebSocket from 'ws';
|
|
574
574
|
|
|
575
575
|
const RPC_URL = 'ws://127.0.0.1:${e}';
|
|
@@ -610,7 +610,7 @@ function rpcCall(method, params = {}) {
|
|
|
610
610
|
function rpcClose() {
|
|
611
611
|
if (rpcWs) rpcWs.close();
|
|
612
612
|
}
|
|
613
|
-
`}function
|
|
613
|
+
`}function Gd(){return`
|
|
614
614
|
// Wallet provider backed by mn serve RPC
|
|
615
615
|
const walletProvider = {
|
|
616
616
|
getCoinPublicKey: () => {
|
|
@@ -640,7 +640,7 @@ const walletProvider = {
|
|
|
640
640
|
|
|
641
641
|
// Get wallet state for coin/encryption public keys
|
|
642
642
|
const walletState = await rpcCall('getShieldedAddresses', {});
|
|
643
|
-
`}function
|
|
643
|
+
`}function Kd(e,t){return`
|
|
644
644
|
import { pathToFileURL } from 'node:url';
|
|
645
645
|
import { resolve } from 'node:path';
|
|
646
646
|
import { CompiledContract } from '@midnight-ntwrk/compact-js';
|
|
@@ -654,7 +654,7 @@ const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract',
|
|
|
654
654
|
// Both relative-to-cwd locations and contract/<...> locations are checked
|
|
655
655
|
// so mn dev (which chdirs into the contract sub-package) and mn contract
|
|
656
656
|
// deploy run from a workspace root both work.
|
|
657
|
-
const WITNESS_CANDIDATES = ${JSON.stringify(
|
|
657
|
+
const WITNESS_CANDIDATES = ${JSON.stringify(ds)};
|
|
658
658
|
let witnesses;
|
|
659
659
|
let createPrivateState;
|
|
660
660
|
for (const p of WITNESS_CANDIDATES) {
|
|
@@ -685,7 +685,7 @@ if (!witnesses) {
|
|
|
685
685
|
// Uses a deterministic seed derived from the wallet so post/takeDown use the same key.
|
|
686
686
|
// The private state provider (leveldb) persists between calls, but initialPrivateState
|
|
687
687
|
// is the fallback when no stored state exists yet.
|
|
688
|
-
${
|
|
688
|
+
${kh}
|
|
689
689
|
function makeInitialPrivateState() {
|
|
690
690
|
if (createPrivateState) {
|
|
691
691
|
// Secret precedence (see resolvePrivateStateSecretKey, injected above via
|
|
@@ -711,7 +711,7 @@ const compiled = witnesses
|
|
|
711
711
|
CompiledContract.withVacantWitnesses,
|
|
712
712
|
(c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR),
|
|
713
713
|
);
|
|
714
|
-
`}function
|
|
714
|
+
`}function Jd(e,t,r){return`
|
|
715
715
|
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
716
716
|
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
717
717
|
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
@@ -734,23 +734,23 @@ const providers = {
|
|
|
734
734
|
walletProvider,
|
|
735
735
|
midnightProvider: walletProvider,
|
|
736
736
|
};
|
|
737
|
-
`}function
|
|
737
|
+
`}function Ch(e){let t=e.privateStateKey??`${e.contractName}PrivateState`,r=JSON.stringify(e.args??[]);return`
|
|
738
738
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
739
739
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
740
740
|
|
|
741
|
-
${
|
|
742
|
-
${
|
|
741
|
+
${Hd(e.servePort)}
|
|
742
|
+
${Kd(e.contractName,e.managedDir)}
|
|
743
743
|
|
|
744
744
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
745
745
|
await rpcConnect();
|
|
746
746
|
process.stderr.write('Connected\\n');
|
|
747
747
|
|
|
748
|
-
${
|
|
749
|
-
${
|
|
748
|
+
${Gd()}
|
|
749
|
+
${Jd(e.managedDir,e.networkConfig,t)}
|
|
750
750
|
|
|
751
751
|
import { deployContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
752
752
|
|
|
753
|
-
${
|
|
753
|
+
${Vd}
|
|
754
754
|
const constructorArgs = (${r}).map(coerceArg);
|
|
755
755
|
process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n');
|
|
756
756
|
const deployed = await deployContract(providers, {
|
|
@@ -766,19 +766,19 @@ process.stderr.write('Deploy complete: ' + address + '\\n');
|
|
|
766
766
|
console.log(JSON.stringify({ contractAddress: address }));
|
|
767
767
|
rpcClose();
|
|
768
768
|
process.exit(0);
|
|
769
|
-
`}function
|
|
769
|
+
`}function Ah(e){let t=e.privateStateKey??`${e.contractName}PrivateState`;return`
|
|
770
770
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
771
771
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
772
772
|
|
|
773
|
-
${
|
|
774
|
-
${
|
|
773
|
+
${Hd(e.servePort)}
|
|
774
|
+
${Kd(e.contractName,e.managedDir)}
|
|
775
775
|
|
|
776
776
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
777
777
|
await rpcConnect();
|
|
778
778
|
process.stderr.write('Connected\\n');
|
|
779
779
|
|
|
780
|
-
${
|
|
781
|
-
${
|
|
780
|
+
${Gd()}
|
|
781
|
+
${Jd(e.managedDir,e.networkConfig,t)}
|
|
782
782
|
|
|
783
783
|
import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
784
784
|
|
|
@@ -791,14 +791,14 @@ const deployed = await findDeployedContract(providers, {
|
|
|
791
791
|
});
|
|
792
792
|
|
|
793
793
|
process.stderr.write('Calling ${e.circuit}...\\n');
|
|
794
|
-
${
|
|
794
|
+
${Vd}
|
|
795
795
|
const args = (${JSON.stringify(e.args??[])}).map(coerceArg);
|
|
796
796
|
await deployed.callTx.${e.circuit}(...args);
|
|
797
797
|
|
|
798
798
|
console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(e.circuit)} }));
|
|
799
799
|
rpcClose();
|
|
800
800
|
process.exit(0);
|
|
801
|
-
`}function
|
|
801
|
+
`}function Eh(e){return`
|
|
802
802
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
803
803
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
804
804
|
|
|
@@ -861,19 +861,19 @@ for (const key of Object.keys(state)) {
|
|
|
861
861
|
|
|
862
862
|
console.log(JSON.stringify({ fields, maps }));
|
|
863
863
|
process.exit(0);
|
|
864
|
-
`}function
|
|
865
|
-
`,r?.(h)}),l.on("close",(g)=>{if(a(),g!==0){d(Error(f.trim()||`Script exited with code ${g}`));return}c(p.trim())}),l.on("error",(g)=>{a(),d(g)})})}var
|
|
866
|
-
const resolvePrivateStateSecretKey = (${
|
|
867
|
-
`;
|
|
868
|
-
const coerceArg = (${
|
|
869
|
-
`;
|
|
864
|
+
`}function Th(e){if(!ii)return[];let t=[];if(!fs(e)){try{Wd(ii,e),t.push(e)}catch{}return t}for(let r of xh){let n=Yr(ii,r),s=Yr(e,r);if(!fs(n)||fs(s))continue;try{Wd(n,s),t.push(s)}catch{}}return t}async function ai(e,t,r,n){let s=Yr(e,"node_modules"),o=Th(s),i=Yr(e,`.mn-contract-${Date.now()}.mjs`);Sh(i,t);let a=()=>{try{jd(i)}catch{}for(let c of o.slice().reverse())try{jd(c)}catch{}};return new Promise((c,d)=>{let l=yh("node",[i],{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1",...n}}),p="",f="";l.stdout?.on("data",(g)=>{p+=g.toString()}),l.stderr?.on("data",(g)=>{let h=g.toString().trim();if(h)f+=h+`
|
|
865
|
+
`,r?.(h)}),l.on("close",(g)=>{if(a(),g!==0){d(Error(f.trim()||`Script exited with code ${g}`));return}c(p.trim())}),l.on("error",(g)=>{a(),d(g)})})}var ii,kh,Vd,xh;var Zr=E(()=>{ps();ii=vh();kh=`
|
|
866
|
+
const resolvePrivateStateSecretKey = (${Ud.toString()});
|
|
867
|
+
`;Vd=`
|
|
868
|
+
const coerceArg = (${ms.toString()});
|
|
869
|
+
`;xh=["@midnight-ntwrk","ws"]});import{indexerPublicDataProvider as Nh}from"@midnight-ntwrk/midnight-js-indexer-public-data-provider";function zd(e){return Nh(e.indexer,e.indexerWS??e.indexer.replace("http","ws"))}var qd=()=>{};var Qd={};fe(Qd,{default:()=>ar});import{resolve as ws}from"node:path";function Qr(){return{update(){},stop(){},fail(){},log(){}}}function Rh(e){return Xd.includes(e)}async function ar(e,t){let r=e.subcommand;if(!r||!Rh(r))throw new Y(`Usage: midnight contract <${Xd.join("|")}>
|
|
870
870
|
|
|
871
871
|
inspect Show circuits, witnesses, and types for a compiled contract
|
|
872
872
|
deploy Deploy a contract to the network
|
|
873
873
|
call Call a circuit on a deployed contract
|
|
874
874
|
state Read the ledger state of a deployed contract
|
|
875
875
|
|
|
876
|
-
Run "midnight help contract" for more info.`);switch(r){case"inspect":return
|
|
876
|
+
Run "midnight help contract" for more info.`);switch(r){case"inspect":return Ih(e);case"deploy":return $h(e);case"call":return _h(e);case"state":return Ph(e)}}function ys(e){let t=x(e,"managed"),r=x(e,"path");return ws(t??r??process.cwd())}async function Ih(e){let t=T(e,"json"),r=ys(e),n=x(e,"name"),{info:s}=ze(r,n);if(t){P(vd(s));return}if(process.stderr.write(`
|
|
877
877
|
`+j(`Contract: ${s.name}`)+`
|
|
878
878
|
|
|
879
879
|
`),process.stderr.write(A("Compiler",s.compilerVersion)+`
|
|
@@ -882,18 +882,18 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return Eh(
|
|
|
882
882
|
`),process.stderr.write(`
|
|
883
883
|
`+k(" Circuits")+`
|
|
884
884
|
`),s.circuits.length===0)process.stderr.write(u(" (none)")+`
|
|
885
|
-
`);else for(let o of s.circuits){let i=
|
|
885
|
+
`);else for(let o of s.circuits){let i=yd(o),a=Sd(o),c=o.pure?U(a):F(a);process.stderr.write(` ${i} ${u("—")} ${c}
|
|
886
886
|
`)}if(process.stderr.write(`
|
|
887
887
|
`+k(" Witnesses")+`
|
|
888
888
|
`),s.witnesses.length===0)process.stderr.write(u(" (none)")+`
|
|
889
|
-
`);else for(let o of s.witnesses)process.stderr.write(` ${
|
|
889
|
+
`);else for(let o of s.witnesses)process.stderr.write(` ${bd(o)}
|
|
890
890
|
`);if(s.siblings.length>0){process.stderr.write(`
|
|
891
891
|
`+k(" Other contracts in this project")+`
|
|
892
892
|
`);for(let o of s.siblings)process.stderr.write(` ${U(o)}
|
|
893
893
|
`);process.stderr.write(`
|
|
894
894
|
`+u(" Inspect a sibling: mn contract inspect --name <name>")+`
|
|
895
895
|
`)}process.stderr.write(`
|
|
896
|
-
`)}async function
|
|
896
|
+
`)}async function Yd(e,t,r){await Promise.resolve().then(() => ke());await Promise.resolve().then(() => pe());await Promise.resolve().then(() => it());await Promise.resolve();let{config:c}=te({args:{command:"contract",subcommand:void 0,positionals:[],flags:{network:e}}}),d=de(oe(r)),l=Buffer.from(d.seed,"hex"),p=d.addresses[e],f=t?Qr():G("Checking wallet..."),g=me();try{let m=(await g.unshielded(p,c)).balances.get(gr)??0n;if(m===0n)throw f.fail("No NIGHT balance"),Error(`Wallet has 0 NIGHT on ${e}.
|
|
897
897
|
|
|
898
898
|
Fund your wallet before deploying:
|
|
899
899
|
Address: ${p}
|
|
@@ -904,34 +904,34 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return Eh(
|
|
|
904
904
|
Register for dust generation:
|
|
905
905
|
Run: midnight dust register --network ${e}
|
|
906
906
|
Then wait: midnight dust status --network ${e}
|
|
907
|
-
`);f.stop(`Wallet OK (${m} NIGHT, dust available)`)}catch(h){throw f.fail("Wallet check failed"),h}}async function
|
|
907
|
+
`);f.stop(`Wallet OK (${m} NIGHT, dust available)`)}catch(h){throw f.fail("Wallet check failed"),h}}async function Zd(e,t,r){await Promise.resolve().then(() => oi());let s=t?Qr():G("Starting mn serve..."),o=await cs({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 $h(e){let t=T(e,"json"),r=ws(x(e,"path")??process.cwd()),n=ys(e),s=x(e,"name");await Promise.resolve().then(() => Zr());await Promise.resolve().then(() => pe());if(!t)process.stderr.write(`
|
|
908
908
|
`+j("Contract Deploy")+`
|
|
909
909
|
|
|
910
|
-
`);let{info:a}=ze(n,s),c=a.witnesses.map((w)=>w.name);if(c.length>0){await Promise.resolve().then(() =>
|
|
910
|
+
`);let{info:a}=ze(n,s),c=a.witnesses.map((w)=>w.name);if(c.length>0){await Promise.resolve().then(() => ps());if(!ls(r))throw Error(us({projectRoot:r,witnessNames:c}))}let d=x(e,"network")??"undeployed",{config:l}=te({args:{command:"contract",subcommand:"deploy",positionals:[],flags:{network:d}}}),p=x(e,"args"),f=[];if(p)try{let w=JSON.parse(p);f=Array.isArray(w)?w:Object.values(w)}catch(w){throw new Y(`Invalid --args JSON: ${w.message}`)}let g=x(e,"secret-key");if(g!==void 0&&!/^[0-9a-fA-F]{64}$/.test(g))throw new Y("--secret-key must be 32 bytes of hex (64 chars)");if(!t){if(process.stderr.write(A("Contract",a.name)+`
|
|
911
911
|
`),process.stderr.write(A("Network",d)+`
|
|
912
912
|
`),f.length>0)process.stderr.write(A("Constructor args",String(f.length))+`
|
|
913
913
|
`);process.stderr.write(`
|
|
914
|
-
`)}await
|
|
914
|
+
`)}await Yd(d,t,x(e,"wallet"));let h=await Zd(d,t,x(e,"wallet")),m=t?Qr():G("Deploying contract...");try{let w=await gs({dappDir:r,networkConfig:l,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)P({subcommand:"deploy",contractName:a.name,address:w.contractAddress,network:d});else process.stderr.write(`
|
|
915
915
|
`),process.stderr.write(A("Address",w.contractAddress)+`
|
|
916
916
|
`),process.stderr.write(`
|
|
917
917
|
`+H(" ✓ Deploy successful")+`
|
|
918
|
-
`),
|
|
919
|
-
`)}catch(w){throw m.fail("Deploy failed"),w}finally{await h.stop()}}function
|
|
918
|
+
`),Dh(w.contractAddress,a.circuits,d),process.stdout.write(w.contractAddress+`
|
|
919
|
+
`)}catch(w){throw m.fail("Deploy failed"),w}finally{await h.stop()}}function Dh(e,t,r){let n=r==="undeployed"?"":` --network ${r}`;process.stderr.write(`
|
|
920
920
|
`+u(" Next:")+`
|
|
921
921
|
`),process.stderr.write(u(" mn contract state --address ")+U(e)+u(n)+`
|
|
922
922
|
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(u(" mn contract call --address ")+U(e)+u(" --circuit ")+U(s.name)+u(n)+`
|
|
923
923
|
`);process.stderr.write(`
|
|
924
|
-
`)}async function
|
|
924
|
+
`)}async function _h(e){let t=T(e,"json"),r=ws(x(e,"path")??process.cwd()),n=ys(e),s=x(e,"name"),o=nn(e,"address","contract address"),i=nn(e,"circuit","circuit name"),a=x(e,"args");await Promise.resolve().then(() => Zr());await Promise.resolve().then(() => pe());if(!t)process.stderr.write(`
|
|
925
925
|
`+j("Contract Call")+`
|
|
926
926
|
|
|
927
|
-
`);let{info:l}=ze(n,s),p=[];if(a)try{let w=JSON.parse(a);p=Array.isArray(w)?w:Object.values(w)}catch(w){throw new Y(`Invalid --args JSON: ${w.message}`)}let f=
|
|
927
|
+
`);let{info:l}=ze(n,s),p=[];if(a)try{let w=JSON.parse(a);p=Array.isArray(w)?w:Object.values(w)}catch(w){throw new Y(`Invalid --args JSON: ${w.message}`)}let f=x(e,"network")??"undeployed",{config:g}=te({args:{command:"contract",subcommand:"call",positionals:[],flags:{network:f}}});if(!t)process.stderr.write(A("Contract",l.name)+`
|
|
928
928
|
`),process.stderr.write(A("Circuit",i)+`
|
|
929
929
|
`),process.stderr.write(A("Address",o.slice(0,20)+"...")+`
|
|
930
930
|
|
|
931
|
-
`);await
|
|
931
|
+
`);await Yd(f,t,x(e,"wallet"));let h=await Zd(f,t,x(e,"wallet")),m=t?Qr():G(`Calling ${i}...`);try{let w=await hs({dappDir:r,networkConfig:g,managedDir:l.managedDir,contractName:l.name,contractAddress:o,circuit:i,args:p,servePort:h.port,onMessage:(y)=>m.update(y)});if(m.stop(H("✓")+` ${i} called`),t)P({subcommand:"call",contractName:l.name,circuit:i,address:o,network:f,status:w.status});else process.stderr.write(`
|
|
932
932
|
`+H(" ✓ Circuit call successful")+`
|
|
933
933
|
|
|
934
|
-
`)}catch(w){throw m.fail("Call failed"),w}finally{await h.stop()}}async function
|
|
934
|
+
`)}catch(w){throw m.fail("Call failed"),w}finally{await h.stop()}}async function Ph(e){let t=T(e,"json"),r=ws(x(e,"path")??process.cwd()),n=ys(e),s=x(e,"name"),o=nn(e,"address","contract address");await Promise.resolve().then(() => pe());await Promise.resolve().then(() => Zr());let c=x(e,"network")??"undeployed",{config:d}=te({args:{command:"contract",subcommand:"state",positionals:[],flags:{network:c}}});if(!t)process.stderr.write(`
|
|
935
935
|
`+j("Contract State")+`
|
|
936
936
|
|
|
937
937
|
`),process.stderr.write(A("Address",o.slice(0,20)+"...")+`
|
|
@@ -942,25 +942,25 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return Eh(
|
|
|
942
942
|
`);for(let[m,w]of Object.entries(f.maps))process.stderr.write(` ${m}: ${u(`Map (${w.size} entries)`)}
|
|
943
943
|
`)}else process.stderr.write(u(" (no ledger fields found)")+`
|
|
944
944
|
`);process.stderr.write(`
|
|
945
|
-
`)}}catch(p){l.stop(F("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() =>
|
|
945
|
+
`)}}catch(p){l.stop(F("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() => qd());let h=await zd(d).queryContractState(o);if(!h)throw Error(`No contract found at address ${o} on ${c}`);let m=h.data??h;if(t)P({subcommand:"state",address:o,network:c,raw:m});else process.stderr.write(k(" Raw State")+`
|
|
946
946
|
`),process.stderr.write(u(" (run from dApp root for parsed ledger fields)")+`
|
|
947
947
|
`),process.stderr.write(` ${JSON.stringify(m).slice(0,200)}
|
|
948
948
|
|
|
949
|
-
`)}}var
|
|
950
|
-
Run this command from the root of a dApp project, or create a ${
|
|
951
|
-
Check the build log: ${i}`);if(await
|
|
952
|
-
Check the build log: ${i}`)}function
|
|
949
|
+
`)}}var Xd;var Ss=E(()=>{We();ue();Je();Vr();Xd=["inspect","deploy","call","state"]});import{existsSync as cr,readFileSync as en,readdirSync as Oh}from"node:fs";import{join as Mt,resolve as Mh}from"node:path";function bs(e){let t=Mh(e??process.cwd()),r=Mt(t,ci);if(!cr(r))throw Error(`No ${ci} found in ${t}
|
|
950
|
+
Run this command from the root of a dApp project, or create a ${ci} file.`);let n;try{n=JSON.parse(en(r,"utf-8"))}catch(o){throw Error(`Failed to parse ${r}: ${o.message}`)}return{config:Uh(n,r),configPath:r,dappDir:t}}function di(e){let t=Mt(e,Fh);if(!cr(t))return[];let r=Oh(t,{withFileTypes:!0}),n=[];for(let s of r){if(!s.isDirectory())continue;let o=Mt(t,s.name),i=Mt(o,"suite.json");if(!cr(i))continue;let a;try{a=JSON.parse(en(i,"utf-8"))}catch(c){throw Error(`Failed to parse ${i}: ${c.message}`)}n.push({suite:jh(a,i),suiteDir:o})}return n}function sl(e){let t=Mt(e,"assertions.json");if(!cr(t))return null;let r;try{r=JSON.parse(en(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return Wh(r,t)}function ol(e){let t=Mt(e,"actions.json");if(!cr(t))return null;let r;try{r=JSON.parse(en(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return Bh(r,t)}function il(e){let t=Mt(e,"prompt.md");if(!cr(t))return null;return en(t,"utf-8")}function Uh(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&&!el.includes(r.network))throw Error(`${t}: "network" must be one of: ${el.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"||!Lh.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 jh(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(!tl.includes(r.strategy))throw Error(`${t}: "strategy" must be one of: ${tl.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&&!rl.includes(r.browserMode))throw Error(`${t}: "browserMode" must be one of: ${rl.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 Wh(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 Bh(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"||!nl.includes(s.type))throw Error(`${t}: action "${s.id}" has invalid type "${s.type}". Valid: ${nl.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 ci="dapp.test.json",Fh="tests/suites",el,tl,rl,Lh,nl;var al=E(()=>{el=["undeployed","preprod","preview"],tl=["browser","cli","hybrid"],rl=["dom","script","vision","auto"],Lh=/^(cache-clear|localnet-up|balance:\d+|dust|dust-register|dust-wait|mn-serve|build-and-serve)$/;nl=["contract-deploy","contract-call","contract-state","wallet-cmd"]});function cl(){let e=[];return{cleanups:e,addCleanup(t){e.push(t)}}}import{spawn as Hh}from"node:child_process";import{createWriteStream as Gh}from"node:fs";import{join as Kh}from"node:path";import Jh from"node:http";import Vh from"node:net";async function ll(e){let{dappDir:t,buildCmd:r,buildDir:n=".",port:s,url:o,logFile:i,timeoutMs:a=240000,onMessage:c=()=>{}}=e;if(await zh(s)){if(await dl(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 qh(s),await new Promise((m)=>setTimeout(m,2000))}let d=Kh(t,n),l=Gh(i,{flags:"a"}),p=Hh("bash",["-lc",r],{cwd:d,stdio:["ignore","pipe","pipe"],detached:!1});p.stdout?.pipe(l),p.stderr?.pipe(l);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 dl(o))return c("UI ready"),{port:s,child:p,stop(){if(!f)p.kill("SIGTERM"),setTimeout(()=>{if(!f)p.kill("SIGKILL")},5000).unref();l.end()}};await new Promise((m)=>setTimeout(m,2000))}throw p.kill("SIGTERM"),l.end(),Error(`UI did not start within ${Math.round(a/1000)}s at ${o}
|
|
952
|
+
Check the build log: ${i}`)}function zh(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 qh(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 dl(e){return new Promise((t)=>{let r=Jh.get(e,{timeout:3000},(n)=>{t(n.statusCode===200),n.resume()});r.on("error",()=>t(!1)),r.on("timeout",()=>{r.destroy(),t(!1)})})}var ul=()=>{};import*as gl from"@midnight-ntwrk/ledger-v8";import{execSync as Xh}from"node:child_process";import{join as Yh}from"node:path";async function hl(e,t,r,n){let s=[];for(let o of e.prep){let i=Date.now();n.onStepStart(o);try{await Zh(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 Zh(e,t,r,n,s){if(e==="cache-clear")return Qh(t);if(e==="localnet-up")return rw(s);if(e.startsWith("balance:")){let o=parseInt(e.split(":")[1],10);return nw(o,t,s)}if(e==="dust"||e==="dust-register"||e==="dust-wait")return sw(t,s);if(e==="mn-serve")return ow(t,n,s);if(e==="build-and-serve")return iw(t,r,n,s);throw Error(`Unknown prep step: ${e}`)}async function Qh(e){let t=e.network??"undeployed";Ke(void 0,t)}function tw(){try{return Xh(`curl -s -o /dev/null http://localhost:8088${vt} --max-time 3`,{timeout:5000,stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ml(e,t){let r=Date.now();while(Date.now()-r<e){if(tw())return!0;t?.("Waiting for indexer...");let{execSync:n}=Is("node:child_process");try{n("sleep 2",{timeout:3000})}catch{}}return!1}async function rw(e){zn(),tr();let t=["node","indexer","proof-server"],r=at();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(ml(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<=vs;i++){e.onMessage(`Attempt ${i}/${vs}: tearing down...`),Ve("down"),e.onMessage(`Attempt ${i}/${vs}: starting...`),Ve("up -d");let a=rr(ew);if(a&&ml(pl,(f)=>e.onMessage(f))){e.onMessage("Localnet running (indexer verified)");return}if(a){e.onMessage(`Attempt ${i}: Docker healthy but indexer not responding after ${pl/1000}s`);continue}let c=at(),d=t.filter((f)=>!c.some((g)=>g.name===f&&g.state==="running")),l=c.filter((f)=>f.state==="running"&&f.health&&f.health!=="healthy"),p=[];if(d.length>0)p.push(`not running: ${d.join(", ")}`);if(l.length>0)p.push(`unhealthy: ${l.map((f)=>f.name).join(", ")}`);e.onMessage(`Attempt ${i} failed: ${p.join("; ")||"timeout"}`)}throw Error(`Localnet failed to start after ${vs} attempts`)}async function nw(e,t,r){let n=t.network??"undeployed",{config:s}=te({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:n}}}),o=de(oe()),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(),l=ht(a,n),p=await Ze(i,s,l);try{let h=await gt(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=gl.unshieldedToken().raw,w=h.unshielded.balances[m]??0n;if(w>0n){r.onMessage(`Balance OK: ${w}`);try{await Le(a,n,p.facade)}catch{}return}}finally{d(),c();try{await Fe(p)}catch{}}if(n!=="undeployed")throw Error(`Wallet has 0 NIGHT on ${n}. Fund your wallet before running tests:
|
|
953
953
|
mn airdrop ${e} (if faucet available)
|
|
954
|
-
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let f=Buffer.from(tt,"hex"),g=
|
|
954
|
+
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let f=Buffer.from(tt,"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 sw(e,t){let r=e.network??"undeployed",{config:n}=te({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}}),s=de(oe()),o=Buffer.from(s.seed,"hex"),i=s.addresses[r],a=he(),c=Ce(),d=ht(i,r),l=await Ze(o,n,d);try{if(t.onMessage("Syncing wallet..."),await gt(l,{syncMode:"lite"}),t.onMessage("Ensuring dust..."),(await et(l,(h)=>t.onMessage(`Dust: ${h}`))).alreadyAvailable){t.onMessage("Dust already available");try{await Le(i,r,l.facade)}catch{}return}t.onMessage("Dust registered. Waiting for coins to become available...");let f=await Vt(l,fl);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:
|
|
955
955
|
mn dust register
|
|
956
|
-
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${
|
|
957
|
-
`).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 ${fl/1000}s. The chain may be slow — try again.`)}t.onMessage("Dust is available");try{await Le(i,r,l.facade)}catch{}}finally{c(),a();try{await Fe(l)}catch{}}}async function ow(e,t,r){r.onMessage("Starting mn serve...");let n=await cs({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 iw(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=Yh(t,"tests","results",`build_${Date.now()}.log`),a=await ll({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 ew=30000,vs=2,pl=30000,fl=90000;var wl=E(()=>{wt();ke();pe();qn();Ge();wt();St();He();oi();ul()});import{execSync as yl,spawn as aw}from"node:child_process";import{createWriteStream as cw,existsSync as dw,mkdirSync as lw,readFileSync as uw}from"node:fs";import{dirname as pw,join as mw}from"node:path";import{homedir as fw}from"node:os";function gw(){let e=mw(fw(),".claude.json");if(!dw(e))return!1;try{let t=JSON.parse(uw(e,"utf-8"));return Boolean(t.mcpServers?.["chrome-devtools"])}catch{return!1}}function ww(e){let t;try{t=yl(`ps -ax -o pid,command | grep "${hw}" | 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{yl(`kill ${n}`,{stdio:"pipe"})}catch{}}function li(e){let t=e.browserMode??"vision";if(t==="auto")return"vision";return t}async function Sl(e){let{suite:t,prompt:r,dappDir:n,logFile:s,onMessage:o=()=>{}}=e,i=(t.timeout??600)*1000,a=li(t);if(a==="dom"||a==="script"){if(!gw())throw Error(`Browser mode "${a}" requires the chrome-devtools MCP server, which is not registered in ~/.claude.json.
|
|
958
958
|
|
|
959
959
|
Install it:
|
|
960
960
|
claude mcp add chrome-devtools --scope user npx chrome-devtools-mcp@latest
|
|
961
961
|
|
|
962
|
-
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");
|
|
963
|
-
`),s}function
|
|
962
|
+
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");ww(o)}lw(pw(s),{recursive:!0});let c=cw(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 l=r;if(a==="dom")l=yw+r;else if(a==="script")l=Sw+r;return d.push("-p",l),o(`Launching Claude (mode: ${a}, model: ${t.model??"default"}, timeout: ${t.timeout??600}s)`),new Promise((p)=>{let f=aw("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 hw="chrome-devtools-mcp/chrome-profile",yw="## 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",Sw="## 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 bl=()=>{};import{existsSync as bw,readFileSync as vw}from"node:fs";import kw from"node:net";async function vl(e,t){let r=[];for(let n of e)try{let s=await Cw(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 Cw(e,t){switch(e.type){case"balance-changed":return Aw(e,t);case"process-exit-code":return Ew(e,t);case"port-listening":return xw(e);case"agent-report-no-failure":return Nw(e,t);default:throw Error(`Unsupported assertion type: "${e.type}" (available in v2)`)}}function Aw(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 Ew(e,t){if(t.processExitCode===void 0)throw Error("Process exit code not available");let r=e.params.code;return t.processExitCode===r}function xw(e){let t=e.params.port;return new Promise((r)=>{let n=new kw.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 Nw(e,t){let r=e.params??{},n=r.logPath??t.agentLogPath;if(!n||!bw(n))return!0;let s;try{s=vw(n,"utf-8")}catch{return!0}let o=Iw(s),i=r.markers??Tw;for(let a of i)if(Rw(o,a))return!1;return!0}function Rw(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 Iw(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"")}var Tw;var kl=E(()=>{Tw=["FAILED","❌","did not pass","test failed","overall: fail","result: fail"]});import{existsSync as $w,mkdirSync as Dw,writeFileSync as _w,readFileSync as Pw,readdirSync as Ow}from"node:fs";import{join as ks}from"node:path";function Al(e,t){let r=ks(t,Cl);Dw(r,{recursive:!0});let n=`${e.suite}_${e.timestamp.replace(/[:.]/g,"-")}.json`,s=ks(r,n);return _w(s,JSON.stringify(e,null,2)+`
|
|
963
|
+
`),s}function El(e,t){let r=ui(e,t);return r.length>0?r[0]:null}function ui(e,t){let r=ks(e,Cl);if(!$w(r))return[];let n=Ow(r).filter((o)=>o.endsWith(".json")).filter((o)=>!t||o.startsWith(t+"_")),s=[];for(let o of n)try{let i=Pw(ks(r,o),"utf-8");s.push(JSON.parse(i))}catch{}return s.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),s}var Cl="tests/results";var xl=()=>{};import{execSync as Mw}from"node:child_process";async function pi(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)Fw(e.buildHandle.port,t)}function Fw(e,t){try{Mw(`osascript -e 'tell application "Google Chrome"
|
|
964
964
|
repeat with theWindow in every window
|
|
965
965
|
repeat with theTab in every tab of theWindow
|
|
966
966
|
if URL of theTab contains "localhost:${e}" then
|
|
@@ -968,7 +968,7 @@ Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision
|
|
|
968
968
|
end if
|
|
969
969
|
end repeat
|
|
970
970
|
end repeat
|
|
971
|
-
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 Tl=()=>{};function Nl(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(Nl);default:return null}}function mi(e){let t={};for(let r of e.arguments)t[r.name]=Nl(r.type);return t}function fi(e,t){if((t.strategy??"cli")==="browser"){if(!t.browser)throw Error("Browser strategy requires browser options (port, buildCmd, buildDir?, url?)");return Gw(t,t.browser)}return Hw(e,t)}function Hw(e,t){let r=t.suiteName??Lw,n=t.network??Rl,s=t.servePort??Il;return{dappConfig:{name:t.contractName,network:n,prep:$l},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??jw},actions:{actions:Jw(e)},assertions:{post:[Dl(s)]},prompt:null,suiteName:r}}function Gw(e,t){let r=e.suiteName??Uw,n=e.network??Rl,s=e.servePort??Il,o=t.url??`http://localhost:${t.port}/`,i={name:e.contractName,network:n,port:t.port,buildCmd:t.buildCmd,url:o,prep:Bw};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??Ww,...t.browserMode?{browserMode:t.browserMode}:{}},actions:null,assertions:{post:[{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"},Dl(s),{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}]},prompt:Kw(e.contractName,o),suiteName:r}}function Dl(e){return{id:"serve-port-listening",type:"port-listening",params:{port:e},expect:"pass"}}function Kw(e,t){return`You are running an automated E2E test of ${e}.
|
|
972
972
|
|
|
973
973
|
The UI is at ${t} — open it in Chrome.
|
|
974
974
|
mn serve is running with --approve-all so contract calls will auto-approve.
|
|
@@ -998,44 +998,44 @@ Follow these steps:
|
|
|
998
998
|
|
|
999
999
|
If any step fails, report exactly what you see on screen and stop.
|
|
1000
1000
|
Take screenshots at each major step to document the test.
|
|
1001
|
-
`}function
|
|
1001
|
+
`}function Jw(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=mi(n);t.push(s)}return t.push({id:"check-final",type:"contract-state"}),t}var Rl="undeployed",Lw="cli-default",Uw="ui-default",jw=300,Ww=600,Il=9932,$l,Bw;var gi=E(()=>{$l=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Bw=[...$l,"build-and-serve"]});import{existsSync as Pl,mkdirSync as Vw,readFileSync as zw,writeFileSync as _l}from"node:fs";import{join as dr}from"node:path";function Ol(e,t){let{dappDir:r,force:n=!1}=t,s=dr(r,"tests","suites",e.suiteName),o=dr(r,"dapp.test.json"),i=[{path:dr(s,"suite.json"),kind:"json",body:e.suite},{path:dr(s,"assertions.json"),kind:"json",body:e.assertions}];if(e.actions)i.push({path:dr(s,"actions.json"),kind:"json",body:e.actions});if(e.prompt)i.push({path:dr(s,"prompt.md"),kind:"text",body:e.prompt});if(!n){let l=i.filter((p)=>Pl(p.path)).map((p)=>p.path);if(l.length>0)throw Error(`Suite "${e.suiteName}" already exists at ${s}.
|
|
1002
1002
|
Pick a different suite name (--suite <name>) or pass --force to overwrite.
|
|
1003
1003
|
Existing files:
|
|
1004
1004
|
`+l.map((p)=>` - ${p}`).join(`
|
|
1005
|
-
`))}let a=
|
|
1005
|
+
`))}let a=qw(o,e,n);Vw(s,{recursive:!0});let c=[],d=[];if(a.action==="write")_l(o,JSON.stringify(e.dappConfig,null,2)+`
|
|
1006
1006
|
`),c.push(o);else d.push(o);for(let l of i){let p=l.kind==="json"?JSON.stringify(l.body,null,2)+`
|
|
1007
|
-
`:l.body;
|
|
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
|
|
1007
|
+
`:l.body;_l(l.path,p),c.push(l.path)}return{written:c,preserved:d}}function qw(e,t,r){if(r||!Pl(e))return{action:"write"};let n;try{n=JSON.parse(zw(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 Ml=()=>{};import{existsSync as Ll,readdirSync as Xw,readFileSync as Yw,statSync as Zw}from"node:fs";import{basename as Qw,extname as ey,join as Ul,relative as ty}from"node:path";function jl(e){let t=new Map;for(let r of ry){let n=Ul(e,r);if(!Ll(n))continue;hi(n,e,t)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function Wl(e,t=e){if(!Ll(e))return[];let r=new Map;return hi(e,t,r),[...r.values()].sort((n,s)=>n.name.localeCompare(s.name))}function hi(e,t,r){let n;try{n=Xw(e)}catch{return}for(let s of n){let o=Ul(e,s),i;try{i=Zw(o)}catch{continue}if(i.isDirectory()){if(ny.has(s.toLowerCase()))continue;hi(o,t,r);continue}if(ey(s)!==Fl)continue;if(s.endsWith(".test.tsx")||s.endsWith(".spec.tsx"))continue;let a=Qw(s,Fl);if(!sy(a,o))continue;let c=iy(a);if(r.has(c))continue;r.set(c,{name:c,component:a,path:o,relativePath:ty(t,o)})}}function sy(e,t){if(!/^[A-Z][A-Za-z0-9]*$/.test(e))return!1;let r;try{r=Yw(t,"utf-8")}catch{return!1}return oy.test(r)}function iy(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}var ry,Fl=".tsx",ny,oy;var wi=E(()=>{ry=["src/components","src/pages","src/screens","src/views"];ny=new Set(["layout","layouts","shared","common","ui","icons","styles"]);oy=/\bexport\s+(default\b|const\s+[A-Z]|function\s+[A-Z])/});import{existsSync as ay,statSync as cy}from"node:fs";import*as Bl from"node:readline";function Hl(){return process.stdin.isTTY===!0}function Xe(e,t){let r=Bl.createInterface({input:process.stdin,output:process.stderr}),n=t!==void 0?u(` [${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 Gl(){process.stderr.write(`
|
|
1009
1009
|
`+U("Test scaffold setup")+`
|
|
1010
1010
|
`);for(;;){let e=(await Xe("Strategy? cli or ui","cli")).toLowerCase();if(e==="cli")return"cli";if(e==="ui"||e==="browser")return"browser";process.stderr.write(u(` Unknown strategy "${e}". Pick "cli" or "ui".
|
|
1011
|
-
`))}}async function
|
|
1011
|
+
`))}}async function Kl(e={}){process.stderr.write(`
|
|
1012
1012
|
`+u("Browser test scaffold needs your dApp UI details:")+`
|
|
1013
|
-
`);let t=e.port!==void 0?String(e.port):await Xe("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 Xe("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 Xe("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await Xe("URL",`http://localhost:${r}/`),a=e.browserMode??await
|
|
1013
|
+
`);let t=e.port!==void 0?String(e.port):await Xe("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 Xe("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 Xe("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await Xe("URL",`http://localhost:${r}/`),a=e.browserMode??await dy();return{port:r,buildCmd:n,buildDir:o,url:i,browserMode:a}}async function dy(){process.stderr.write(`
|
|
1014
1014
|
`+U("Browser mode — how should Claude perceive the page?")+`
|
|
1015
1015
|
`),process.stderr.write(` ${u("1.")} dom ${u("— accessibility tree (text). Fast. HTML / React / Vue UIs.")}
|
|
1016
1016
|
`),process.stderr.write(` ${u("2.")} vision ${u("— screenshots. Slow. Canvas games (no DOM).")}
|
|
1017
1017
|
`),process.stderr.write(` ${u("3.")} script ${u("— direct JS. Fastest. Needs dApp-side hooks (advanced).")}
|
|
1018
1018
|
`),process.stderr.write(u(` dom and script need chrome-devtools-mcp installed.
|
|
1019
1019
|
`));for(;;){let e=(await Xe("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(F(` Pick 1 (dom), 2 (vision), or 3 (script).
|
|
1020
|
-
`))}}async function
|
|
1020
|
+
`))}}async function Jl(e){let t=e.filter((r)=>!r.pure);if(t.length===0){process.stderr.write(u(` No impure circuits in this contract — nothing to test as a write path.
|
|
1021
1021
|
`));return}process.stderr.write(`
|
|
1022
1022
|
`+U("Pick the circuit this suite will exercise:")+`
|
|
1023
1023
|
`);for(let r=0;r<t.length;r++)process.stderr.write(` ${u(`${r+1}.`)} ${t[r].name}
|
|
1024
1024
|
`);process.stderr.write(u(` (or type "skip" to scaffold all circuits without AI)
|
|
1025
1025
|
`));for(;;){let r=(await Xe("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(u(` Pick a number 1–${t.length}, the circuit name, or "skip".
|
|
1026
|
-
`))}}async function
|
|
1026
|
+
`))}}async function yi(e){if(e.length===0)return ly();process.stderr.write(`
|
|
1027
1027
|
`+U("Pick the screen this suite will test:")+`
|
|
1028
1028
|
`);for(let t=0;t<e.length;t++)process.stderr.write(` ${u(`${t+1}.`)} ${e[t].name} ${u(`(${e[t].relativePath})`)}
|
|
1029
1029
|
`);process.stderr.write(u(` (or type "skip" to scaffold a generic prompt.md without AI)
|
|
1030
1030
|
`));for(;;){let t=(await Xe("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(u(` Pick a number 1–${e.length}, the screen name, or "skip".
|
|
1031
|
-
`))}}async function
|
|
1031
|
+
`))}}async function ly(){process.stderr.write(u(`
|
|
1032
1032
|
Could not auto-discover screens (no src/components, src/pages, or src/screens under the build dir).
|
|
1033
|
-
`));for(;;){let e=(await Xe('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!
|
|
1034
|
-
`));continue}let t;try{t=
|
|
1035
|
-
`));continue}if(t.isDirectory()){let r=
|
|
1036
|
-
`));continue}return
|
|
1037
|
-
`));continue}return
|
|
1038
|
-
`))}}function
|
|
1033
|
+
`));for(;;){let e=(await Xe('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!ay(e)){process.stderr.write(u(` No such path: ${e}
|
|
1034
|
+
`));continue}let t;try{t=cy(e)}catch{process.stderr.write(u(` Cannot stat: ${e}
|
|
1035
|
+
`));continue}if(t.isDirectory()){let r=Wl(e);if(r.length===0){process.stderr.write(u(` No PascalCase .tsx components in ${e}
|
|
1036
|
+
`));continue}return yi(r)}if(!e.endsWith(".tsx")){process.stderr.write(u(` Not a .tsx file: ${e}
|
|
1037
|
+
`));continue}return py(e)}}async function Vl(){let e=(await Xe("What does success look like? (one line, optional)")).trim();return e===""?void 0:e}async function Si(e){for(;;){let t=(await Xe("Suite name",e)).trim();if(uy(t))return t;process.stderr.write(F(` Suite names must be kebab-case (a–z, 0–9, dashes, underscores). Try again.
|
|
1038
|
+
`))}}function uy(e){return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e)}function py(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 zl=E(()=>{wi()});function Yl(e){let{contractName:t,contractSummary:r,contractSource:n,targetCircuit:s,goal:o,witnessDependentCircuits:i}=e,a=i&&i.size>0?`
|
|
1039
1039
|
## Circuits NOT testable from a CLI suite
|
|
1040
1040
|
|
|
1041
1041
|
These circuits call witnesses that read from private state. In a
|
|
@@ -1140,9 +1140,9 @@ Args coercion the runner applies (so JSON arg values can be):
|
|
|
1140
1140
|
- [0..255] int array → Uint8Array for Bytes<N>
|
|
1141
1141
|
- object → recurses into Struct fields
|
|
1142
1142
|
|
|
1143
|
-
${
|
|
1143
|
+
${Xl}
|
|
1144
1144
|
|
|
1145
|
-
Now produce the JSON.`}function
|
|
1145
|
+
Now produce the JSON.`}function Zl(e){let{contractName:t,contractSummary:r,screenComponent:n,screenSource:s,relatedSources:o,url:i,goal:a}=e,c=(o??[]).map((p)=>`
|
|
1146
1146
|
--- ${p.path} ---
|
|
1147
1147
|
${p.source}
|
|
1148
1148
|
--- end ${p.path} ---`).join(`
|
|
@@ -1219,81 +1219,81 @@ A JSON object with three keys:
|
|
|
1219
1219
|
chain (e.g. ledger-field on a contract-state read).
|
|
1220
1220
|
- description: one short sentence summarising what this suite verifies.
|
|
1221
1221
|
|
|
1222
|
-
${
|
|
1222
|
+
${Xl}
|
|
1223
1223
|
|
|
1224
|
-
Now produce the JSON.`}function
|
|
1225
|
-
`)}var
|
|
1224
|
+
Now produce the JSON.`}function bi(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 ql="```json",Xl;var Ql=E(()=>{Xl=`Output rules:
|
|
1226
1226
|
- Reply with EXACTLY one ${"```json"} ... \`\`\` fenced code block.
|
|
1227
1227
|
- Inside the fence: valid JSON, nothing else (no comments, no trailing text).
|
|
1228
1228
|
- Fields you don't know about: omit them. Don't invent fields.
|
|
1229
1229
|
- Use only the circuit / ledger field names that appear in the inputs below.
|
|
1230
|
-
- Be concise — fewer, well-named actions beat many vague ones.`});function lr(e,t){if(t.length===0)return{byCircuit:new Map};let r=uy(e),n=py(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,l]of n){o.set(d,new Set),i.set(d,new Set);for(let p of fy(l.body,l.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,l]of i){let p=o.get(d);for(let f of l)for(let g of o.get(f)??[])if(!p.has(g))p.add(g),a=!0}}let c=new Map;for(let[d,l]of n){if(!l.isCircuit)continue;let p=o.get(d);if(p&&p.size>0)c.set(d,[...p].sort())}return{byCircuit:c}}function uy(e){return e.replace(ly,"").replace(dy,"")}function py(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,l=c+1;for(;l<e.length&&d>0;l++){let g=e[l];if(g==="{")d++;else if(g==="}")d--}if(d!==0)continue;let p=e.slice(c+1,l-1),f=my(i);t.set(o,{body:p,argNames:f,isCircuit:s==="circuit"})}return t}function my(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 fy(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(gy.has(o)||t.has(o))continue;r.add(o)}return r}var dy,ly,gy;var ks=x(()=>{dy=/\/\/[^\n]*/g,ly=/\/\*[\s\S]*?\*\//g;gy=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var ou={};fe(ou,{claudeSubprocessRunner:()=>Si,findContractSourcePath:()=>bi,generateCliScaffoldWithAI:()=>Ty,generateUiScaffoldWithAI:()=>Ny,isClaudeAvailable:()=>ky});import{execFileSync as hy,spawn as wy}from"node:child_process";import{existsSync as yi,readdirSync as yy,readFileSync as Zl}from"node:fs";import{dirname as ur,join as Cs}from"node:path";function ky(){try{return hy("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function ru(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${Kl} ... \`\`\` 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 Cy(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=xy(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)"}`);Ay(s,o)}return{actions:r}}function Ay(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 xy(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 Ey(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 Ty(e,t=Si){let r=e.contractSourcePath&&yi(e.contractSourcePath)?Zl(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?lr(r,n).byCircuit:new Map,o=e.targetCircuit?li(e.targetCircuit):void 0,i=Vl({contractName:e.contract.name,contractSummary:wi({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=ru(a),d=Cy(c,e.contract),l=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${su(e.goal)??"ai"}`),p=e.network??Ql,f=e.servePort??eu,g={name:e.contract.name,network:p,prep:tu},h={name:l,description:c.description,strategy:"cli",timeout:Sy},m=Ry(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:l,excludedCircuits:w.length>0?w:void 0}}async function Ny(e,t=Si){let r=e.screen?Zl(e.screen.path,"utf-8"):void 0,n=zl({contractName:e.contract.name,contractSummary:wi({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=ru(s);Ey(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${su(e.goal)??"ai"}`),a=e.network??Ql,c=e.servePort??eu,d=e.url,l={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:vy};if(e.buildDir)l.buildDir=e.buildDir;let p={name:i,description:o.description,strategy:"browser",timeout:by,...e.browserMode?{browserMode:e.browserMode}:{}},f=Iy(o.assertions,c);return{dappConfig:l,suite:p,actions:null,assertions:f,prompt:o.prompt,suiteName:i}}function nu(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function Ry(e,t){if(e.post.some((n)=>n.type==="port-listening"&&nu(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function Iy(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"&&nu(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 su(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 bi(e){let t=e.split("/").pop(),r=[ur(e),Cs(ur(e),"src"),ur(ur(e)),Cs(ur(ur(e)),"src")];for(let n of r){if(!yi(n))continue;if(t){let i=Cs(n,`${t}.compact`);if(yi(i))return i}let s;try{s=yy(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return Cs(n,o)}return}var Ql="undeployed",eu=9932,Sy=300,by=600,tu,vy,Xl=300000,Yl=4194304,Si=(e)=>new Promise((t,r)=>{let n=wy("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${Xl/1000}s`))},Xl);n.stdout?.on("data",(d)=>{if(i+=d.length,i>Yl){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,l)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${Yl/1024/1024}MB; aborted.`));return}if(l==="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 vi=x(()=>{ql();pi();ks();tu=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],vy=[...tu,"build-and-serve"]});import{existsSync as iu,readFileSync as au,writeFileSync as $y,mkdirSync as _y}from"node:fs";import{join as cu}from"node:path";async function du(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:l}=e,p=[],f=r.network??"undeployed",g;if(!a)g=Uy(n,s,f);let{info:h}=ze(n),m=Ly(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 Dy(y,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:g,witnessDeps:m,onMessage:l});if(b.contractAddress){if(g=b.contractAddress,jy(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 Dy(e,t){switch(e.type){case"contract-deploy":return Py(e,t);case"contract-call":return Oy(e,t);case"contract-state":return My(e,t);case"wallet-cmd":return Fy(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 fs({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 Oy(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 ir({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 gs({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 ir({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 My(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await ir({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)ki(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);ki(s,a,o,n)}catch{ki(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 lr(e,t){if(t.length===0)return{byCircuit:new Map};let r=gy(e),n=hy(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,l]of n){o.set(d,new Set),i.set(d,new Set);for(let p of yy(l.body,l.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,l]of i){let p=o.get(d);for(let f of l)for(let g of o.get(f)??[])if(!p.has(g))p.add(g),a=!0}}let c=new Map;for(let[d,l]of n){if(!l.isCircuit)continue;let p=o.get(d);if(p&&p.size>0)c.set(d,[...p].sort())}return{byCircuit:c}}function gy(e){return e.replace(fy,"").replace(my,"")}function hy(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,l=c+1;for(;l<e.length&&d>0;l++){let g=e[l];if(g==="{")d++;else if(g==="}")d--}if(d!==0)continue;let p=e.slice(c+1,l-1),f=wy(i);t.set(o,{body:p,argNames:f,isCircuit:s==="circuit"})}return t}function wy(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 yy(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(Sy.has(o)||t.has(o))continue;r.add(o)}return r}var my,fy,Sy;var Cs=E(()=>{my=/\/\/[^\n]*/g,fy=/\/\*[\s\S]*?\*\//g;Sy=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var du={};fe(du,{claudeSubprocessRunner:()=>ki,findContractSourcePath:()=>Ci,generateCliScaffoldWithAI:()=>$y,generateUiScaffoldWithAI:()=>Dy,isClaudeAvailable:()=>xy});import{execFileSync as by,spawn as vy}from"node:child_process";import{existsSync as vi,readdirSync as ky,readFileSync as ru}from"node:fs";import{dirname as ur,join as As}from"node:path";function xy(){try{return by("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function iu(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${ql} ... \`\`\` 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=Ry(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)"}`);Ny(s,o)}return{actions:r}}function Ny(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 Ry(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 Iy(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 $y(e,t=ki){let r=e.contractSourcePath&&vi(e.contractSourcePath)?ru(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?lr(r,n).byCircuit:new Map,o=e.targetCircuit?mi(e.targetCircuit):void 0,i=Yl({contractName:e.contract.name,contractSummary:bi({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=iu(a),d=Ty(c,e.contract),l=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${cu(e.goal)??"ai"}`),p=e.network??nu,f=e.servePort??su,g={name:e.contract.name,network:p,prep:ou},h={name:l,description:c.description,strategy:"cli",timeout:Cy},m=_y(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:l,excludedCircuits:w.length>0?w:void 0}}async function Dy(e,t=ki){let r=e.screen?ru(e.screen.path,"utf-8"):void 0,n=Zl({contractName:e.contract.name,contractSummary:bi({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=iu(s);Iy(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${cu(e.goal)??"ai"}`),a=e.network??nu,c=e.servePort??su,d=e.url,l={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:Ey};if(e.buildDir)l.buildDir=e.buildDir;let p={name:i,description:o.description,strategy:"browser",timeout:Ay,...e.browserMode?{browserMode:e.browserMode}:{}},f=Py(o.assertions,c);return{dappConfig:l,suite:p,actions:null,assertions:f,prompt:o.prompt,suiteName:i}}function au(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function _y(e,t){if(e.post.some((n)=>n.type==="port-listening"&&au(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function Py(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"&&au(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 cu(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 Ci(e){let t=e.split("/").pop(),r=[ur(e),As(ur(e),"src"),ur(ur(e)),As(ur(ur(e)),"src")];for(let n of r){if(!vi(n))continue;if(t){let i=As(n,`${t}.compact`);if(vi(i))return i}let s;try{s=ky(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return As(n,o)}return}var nu="undeployed",su=9932,Cy=300,Ay=600,ou,Ey,eu=300000,tu=4194304,ki=(e)=>new Promise((t,r)=>{let n=vy("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${eu/1000}s`))},eu);n.stdout?.on("data",(d)=>{if(i+=d.length,i>tu){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,l)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${tu/1024/1024}MB; aborted.`));return}if(l==="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 Ai=E(()=>{Ql();gi();Cs();ou=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Ey=[...ou,"build-and-serve"]});import{existsSync as lu,readFileSync as uu,writeFileSync as Oy,mkdirSync as My}from"node:fs";import{join as pu}from"node:path";async function mu(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:l}=e,p=[],f=r.network??"undeployed",g;if(!a)g=Hy(n,s,f);let{info:h}=ze(n),m=By(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 Fy(y,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:g,witnessDeps:m,onMessage:l});if(b.contractAddress){if(g=b.contractAddress,Gy(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 Fy(e,t){switch(e.type){case"contract-deploy":return Ly(e,t);case"contract-call":return Uy(e,t);case"contract-state":return jy(e,t);case"wallet-cmd":return Wy(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function Ly(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 gs({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 Uy(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 ir({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 hs({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 ir({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 ir({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)Ei(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);Ei(s,a,o,n)}catch{Ei(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1231
1231
|
${n.join(`
|
|
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
|
|
1233
|
-
`)}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 Ei(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 Wy(e,t){return{id:e.id,type:e.type,status:"pass",duration:0,message:`wallet-cmd: ${e.cmd??"no command"} (not yet implemented)`}}function By(e){if(e.witnesses.length===0)return new Map;let t=Ci(e.managedDir);if(!t||!lu(t))return new Map;let r=uu(t,"utf-8"),n=e.witnesses.map((s)=>s.name);return lr(r,n).byCircuit}function fu(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 gu(e,t){return pu(e,"tests","results",`.contract-cache-${t}.json`)}function Hy(e,t,r){let n=gu(e,t);if(!lu(n))return;try{let s=JSON.parse(uu(n,"utf-8"));if(s.network!==r)return;return s.address}catch{return}}function Gy(e,t,r,n){let s=gu(e,t);My(pu(e,"tests","results"),{recursive:!0});let o={address:n,network:r,timestamp:new Date().toISOString()};Oy(s,JSON.stringify(o,null,2)+`
|
|
1233
|
+
`)}var hu=E(()=>{Zr();Vr();Cs();Ai()});var bu={};fe(bu,{default:()=>Es});import{join as wu}from"node:path";import{mkdirSync as Ky}from"node:fs";function Jy(e){return yu.includes(e)}async function Es(e,t){let r=e.subcommand;if(!r||!Jy(r))throw new Y(`Usage: midnight test <${yu.join("|")}>
|
|
1234
1234
|
|
|
1235
1235
|
create Generate dapp.test.json + a CLI test suite from the contract
|
|
1236
1236
|
run Run test suites for the current dApp
|
|
1237
1237
|
list List available test suites
|
|
1238
1238
|
results Show latest test results
|
|
1239
1239
|
|
|
1240
|
-
Run from the root of a dApp project containing dapp.test.json.`);let n=T(e,"json");switch(r){case"create":return
|
|
1240
|
+
Run from the root of a dApp project containing dapp.test.json.`);let n=T(e,"json");switch(r){case"create":return Yy(e,n);case"run":return tS(e,n,t);case"list":return rS(n);case"results":return nS(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 Y(`Unknown strategy "${e}". Use "cli" or "ui".`)}function zy(e){return e==="preprod"||e==="preview"||e==="undeployed"?e:void 0}function qy(e){let t={},r=x(e,"port");if(r!==void 0){let a=parseInt(r,10);if(!Number.isFinite(a)||a<=0||a>65535)throw new Y(`Invalid --port "${r}" — must be 1–65535.`);t.port=a}let n=x(e,"build-cmd");if(n!==void 0)t.buildCmd=n;let s=x(e,"build-dir");if(s!==void 0)t.buildDir=s;let o=x(e,"url");if(o!==void 0)t.url=o;let i=x(e,"browser-mode");if(i!==void 0){if(i!=="dom"&&i!=="vision"&&i!=="script"&&i!=="auto")throw new Y(`Invalid --browser-mode "${i}" — must be dom, vision, or script.`);t.browserMode=i}return t}function Xy(e){if(e.port===void 0||e.buildCmd===void 0)throw new Y("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 Yy(e,t){let{resolve:r}=await import("node:path");await Promise.resolve().then(() => Vr());await Promise.resolve().then(() => gi());await Promise.resolve().then(() => Ml());let i=await Promise.resolve().then(() => (zl(),{}));await Promise.resolve();let m=await Promise.resolve().then(() => (Ai(),du));await Promise.resolve().then(() => wi());let y=r(x(e,"path")??process.cwd()),S=x(e,"name"),b=x(e,"suite"),v=zy(x(e,"network")),R=T(e,"force"),_=!t&&Hl(),Z=x(e,"goal"),L=x(e,"screen"),J=T(e,"no-ai"),O=Vy(x(e,"strategy"))??(_?await Gl():"cli"),Q;if(O==="browser"){let B=qy(e);Q=_?await Kl(B):Xy(B)}let{info:le}=ze(y,S),Ft=!J&&m.isClaudeAvailable(),I=!J&&(Z!==void 0||L!==void 0||_&&Ft),C=I?await Zy({strategy:O,info:le,dappDir:y,browser:Q,network:v,suiteName:b,goalFlag:Z,screenFlag:L,interactive:_,jsonMode:t,ai:m,promptCircuit:Jl,promptScreen:yi,promptGoal:Vl,promptSuiteName:Si,discoverScreens:jl})??fi(le.circuits,{contractName:le.name,suiteName:b,strategy:O,browser:Q,network:v}):fi(le.circuits,{contractName:le.name,suiteName:b,strategy:O,browser:Q,network:v});if(_&&!b){let B=await Si(C.suiteName);if(B!==C.suiteName)C.suiteName=B,C.suite.name=B}let N=Ol(C,{dappDir:y,force:R});if(t){P({subcommand:"create",contractName:le.name,suiteName:C.suiteName,strategy:O,aiAssisted:I&&C.suiteName!=="cli-default"&&C.suiteName!=="ui-default",written:N.written,excludedCircuits:C.excludedCircuits});return}process.stderr.write(`
|
|
1241
1241
|
`+j(`Test scaffold: ${le.name}`)+`
|
|
1242
1242
|
|
|
1243
1243
|
`);for(let B of N.written)process.stderr.write(` ${H("✓")} ${B}
|
|
1244
|
-
`);let
|
|
1244
|
+
`);let D=O==="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(C.excludedCircuits&&C.excludedCircuits.length>0){process.stderr.write(`
|
|
1245
1245
|
`+u(" Skipped (not CLI-testable):")+`
|
|
1246
1246
|
`);for(let B of C.excludedCircuits)process.stderr.write(` ${F("!")} ${B.name} ${u("— "+B.reason)}
|
|
1247
1247
|
`);process.stderr.write(u(` These need the dApp UI to populate private state first.
|
|
1248
1248
|
`)),process.stderr.write(u(` Cover them with a browser-strategy suite (mn test create --strategy ui).
|
|
1249
1249
|
`))}process.stderr.write(`
|
|
1250
1250
|
`+u(" Next:")+`
|
|
1251
|
-
`),process.stderr.write(u(" Edit ")+U(`tests/suites/${C.suiteName}/${
|
|
1252
|
-
`),process.stderr.write(u(" ")+u(
|
|
1251
|
+
`),process.stderr.write(u(" Edit ")+U(`tests/suites/${C.suiteName}/${D.file}`)+`
|
|
1252
|
+
`),process.stderr.write(u(" ")+u(D.hint)+`
|
|
1253
1253
|
`),process.stderr.write(u(" Run ")+U(`mn test run --suite ${C.suiteName}`)+`
|
|
1254
1254
|
`),process.stderr.write(u(" List ")+U("mn test list")+u(" (see every suite in this project)")+`
|
|
1255
1255
|
|
|
1256
|
-
`)}async function
|
|
1256
|
+
`)}async function Zy(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 Qy(e,t);return await eS(e,t)}catch(t){return process.stderr.write(`
|
|
1257
1257
|
${u("AI scaffold failed, falling back to deterministic:")} ${t.message}
|
|
1258
|
-
`),null}}async function
|
|
1258
|
+
`),null}}async function Su(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 Qy(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(() => Cs());let i=s(n,"utf-8"),a=e.info.witnesses.map((l)=>l.name),d=lr(i,a).byCircuit.get(r.name);if(d&&d.length>0)process.stderr.write(`
|
|
1259
1259
|
`+F("!")+` ${r.name} calls ${d.join(", ")} — a witness that reads private state.
|
|
1260
1260
|
`),process.stderr.write(u(` The CLI suite will deploy + run, but expect a "Cannot read properties of undefined" failure
|
|
1261
1261
|
`)+u(` unless the dApp UI populates that state first. Consider --strategy ui instead.
|
|
1262
|
-
`))}return
|
|
1262
|
+
`))}return Su("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 eS(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 Su("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 tS(e,t,r){let{config:n,dappDir:s}=bs(),o=di(s),i=x(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 Y(`Suite "${i}" not found. Available: ${g}`)}}else if(o.length>0)a=o[0];Ky(wu(s,"tests","results"),{recursive:!0});let c=Date.now(),d=new Date().toISOString();if(!t){if(process.stderr.write(`
|
|
1263
1263
|
`+j(`E2E Test: ${n.name}`)+`
|
|
1264
1264
|
|
|
1265
1265
|
`),process.stderr.write(A("Network",n.network??"undeployed")+`
|
|
1266
1266
|
`),n.port)process.stderr.write(A("Port",String(n.port))+`
|
|
1267
1267
|
`);if(a){if(process.stderr.write(A("Suite",a.suite.name)+`
|
|
1268
1268
|
`),process.stderr.write(A("Strategy",a.suite.strategy)+`
|
|
1269
|
-
`),a.suite.strategy==="browser"){let g=
|
|
1269
|
+
`),a.suite.strategy==="browser"){let g=li(a.suite);process.stderr.write(A("Browser Mode",g)+`
|
|
1270
1270
|
`)}}process.stderr.write(`
|
|
1271
|
-
`)}let l=
|
|
1272
|
-
`)};r?.addEventListener("abort",()=>
|
|
1273
|
-
`));let g=G("Starting prep..."),h=await
|
|
1274
|
-
`);let m=0,w="";if(a){let M=a.suite;if(M.strategy==="browser"){let O=
|
|
1271
|
+
`)}let l=cl(),p=[],f=(g)=>{if(!t)process.stderr.write(u(` [teardown] ${g}`)+`
|
|
1272
|
+
`)};r?.addEventListener("abort",()=>pi(l,f),{once:!0});try{if(!t)process.stderr.write(k(` Prep
|
|
1273
|
+
`));let g=G("Starting prep..."),h=await hl(n,s,l,{onStepStart(M){g.update(`[prep] ${M}...`)},onStepComplete(M,O,Q,le){if(O==="pass")g.stop(`${H("✓")} ${M} (${sS(Q)})`);else g.stop(`${V("✗")} ${M}: ${le??"failed"}`);g=G("")},onMessage(M){g.update(M)}});if(g.stop(""),p.push(...h),!t)process.stderr.write(`
|
|
1274
|
+
`);let m=0,w="";if(a){let M=a.suite;if(M.strategy==="browser"){let O=il(a.suiteDir);if(!O)throw Error(`No prompt.md found in ${a.suiteDir} — required for browser strategy`);if(w=wu(s,"tests","results",`${M.name}_${d.replace(/[:.]/g,"-")}_claude.log`),!t)process.stderr.write(k(` Browser Test
|
|
1275
1275
|
`)),process.stderr.write(u(` Claude will take over the terminal. Output is also logged.
|
|
1276
1276
|
|
|
1277
|
-
`));let Q=await
|
|
1277
|
+
`));let Q=await Sl({suite:M,prompt:O,dappDir:s,logFile:w,onMessage:(le)=>{if(!t)process.stderr.write(u(` ${le}`)+`
|
|
1278
1278
|
`)}});if(m=Q.exitCode,!t)if(process.stderr.write(`
|
|
1279
1279
|
`),Q.timedOut)process.stderr.write(` ${V("✗")} Browser test timed out
|
|
1280
1280
|
`);else process.stderr.write(` ${m===0?H("✓"):V("✗")} Claude exited with code ${m}
|
|
1281
|
-
`)}else if(M.strategy==="cli"){let O=
|
|
1281
|
+
`)}else if(M.strategy==="cli"){let O=ol(a.suiteDir);if(!O)throw Error(`No actions.json found in ${a.suiteDir} — required for CLI strategy`);if(!t)process.stderr.write(k(` CLI Test
|
|
1282
1282
|
`)),process.stderr.write(u(` Executing ${O.actions.length} action(s)
|
|
1283
1283
|
|
|
1284
|
-
`));await Promise.resolve().then(() =>
|
|
1284
|
+
`));await Promise.resolve().then(() => hu());await Promise.resolve().then(() => pe());let I=n.network??"undeployed",{config:C}=te({args:{command:"test",subcommand:"run",positionals:[],flags:{network:I}}});await Promise.resolve();let D=l.serveHandle?.port??At,B=T(e,"redeploy"),K=await mu({actions:O.actions,config:n,dappDir:s,suiteName:M.name,networkConfig:C,servePort:D,redeploy:B,onActionStart:(ee)=>{if(!t){let ae=G(`[${ee.id}] ${ee.type}${ee.circuit?` ${ee.circuit}`:""}...`);ee._spinner=ae}},onActionComplete:(ee,ae)=>{if(!t){let Ee=ee._spinner;if(Ee)if(ae.status==="pass")Ee.stop(`${H("✓")} ${ee.id}: ${ae.message??"pass"}`);else if(ae.status==="skip")Ee.stop(`${F("⊘")} ${ee.id}: ${ae.message??"skipped"}`);else Ee.stop(`${V("✗")} ${ee.id}: ${ae.message??"fail"}`);if(ae.stateBefore&&ae.stateAfter){let Ue=fu(ae.stateBefore,ae.stateAfter);if(Ue.length>0)for(let Ae of Ue)process.stderr.write(u(` ${Ae.field}: ${Ae.before} → `)+U(Ae.after)+`
|
|
1285
1285
|
`)}}},onMessage:(ee)=>{}});if(m=K.some((ee)=>ee.status==="fail")?1:0,!t){process.stderr.write(`
|
|
1286
|
-
`);let ee=K.filter((
|
|
1286
|
+
`);let ee=K.filter((Ae)=>Ae.status==="pass").length,ae=K.filter((Ae)=>Ae.status==="skip").length,Ee=K.filter((Ae)=>Ae.status==="fail").length,Ue=H(String(ee)+" passed");if(ae>0)Ue+=`, ${F(String(ae)+" skipped")}`;if(Ee>0)Ue+=`, ${V(String(Ee)+" failed")}`;process.stderr.write(` Actions: ${Ue}
|
|
1287
1287
|
`)}l._actionResults=K}}else if(!t)process.stderr.write(u(` No test suites found — only prep was run
|
|
1288
|
-
`));let y={processExitCode:m,agentLogPath:w},S=[];if(a){let M=
|
|
1288
|
+
`));let y={processExitCode:m,agentLogPath:w},S=[];if(a){let M=sl(a.suiteDir);if(M&&M.post.length>0){if(!t)process.stderr.write(`
|
|
1289
1289
|
`+k(` Assertions
|
|
1290
|
-
`));if(S=await
|
|
1291
|
-
`)}}}let b=Math.round((Date.now()-c)/1000),v=p.every((M)=>M.status==="pass"),R=S.every((M)=>M.status==="pass"),
|
|
1290
|
+
`));if(S=await vl(M.post,y),!t)for(let O of S){let Q=O.status==="pass"?H("✓"):V("✗"),le=O.message?u(` — ${O.message}`):"";process.stderr.write(` ${Q} ${O.id}${le}
|
|
1291
|
+
`)}}}let b=Math.round((Date.now()-c)/1000),v=p.every((M)=>M.status==="pass"),R=S.every((M)=>M.status==="pass"),_=v&&R&&m===0?"pass":"fail",Z=l._actionResults,L={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:_,prep:p,actions:Z?.map((M)=>({id:M.id,type:M.type,status:M.status,duration:M.duration,message:M.message,contractAddress:M.contractAddress})),assertions:S,testOutput:w?{exitCode:m,logFile:w}:void 0},J=Al(L,s);if(t)P(L);else process.stderr.write(`
|
|
1292
1292
|
`+z()+`
|
|
1293
|
-
`),process.stderr.write(` ${
|
|
1293
|
+
`),process.stderr.write(` ${_==="pass"?H(k("PASS")):V(k("FAIL"))} — ${n.name} (${b}s)
|
|
1294
1294
|
`),process.stderr.write(u(` Results: ${J}`)+`
|
|
1295
1295
|
|
|
1296
|
-
`);if(
|
|
1296
|
+
`);if(_==="fail")process.exitCode=1}finally{await pi(l,f)}}function rS(e){let{config:t,dappDir:r}=bs(),n=di(r);if(e){P({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
1297
|
`+j(`Tests: ${t.name}`)+`
|
|
1298
1298
|
|
|
1299
1299
|
`),n.length===0)process.stderr.write(u(` No test suites found.
|
|
@@ -1303,7 +1303,7 @@ Run from the root of a dApp project containing dapp.test.json.`);let n=T(e,"json
|
|
|
1303
1303
|
`),process.stderr.write(u(` strategy: ${s.strategy}`)+(s.timeout?u(`, timeout: ${s.timeout}s`):"")+`
|
|
1304
1304
|
|
|
1305
1305
|
`);process.stderr.write(`
|
|
1306
|
-
`)}function
|
|
1306
|
+
`)}function nS(e,t){let{config:r,dappDir:n}=bs(),s=T(e,"all"),o=x(e,"suite"),i=s?ui(n,o):(()=>{let a=El(n,o);return a?[a]:[]})();if(t){P(s?{dapp:r.name,results:i}:i[0]??{});return}if(process.stderr.write(`
|
|
1307
1307
|
`+j(`Results: ${r.name}`)+`
|
|
1308
1308
|
|
|
1309
1309
|
`),i.length===0)process.stderr.write(u(` No test results found.
|
|
@@ -1314,28 +1314,28 @@ Run from the root of a dApp project containing dapp.test.json.`);let n=T(e,"json
|
|
|
1314
1314
|
`);let p=a.assertions.filter((f)=>f.status==="fail");if(p.length>0)process.stderr.write(V(` assertions: ${p.length} failed`)+`
|
|
1315
1315
|
`);process.stderr.write(`
|
|
1316
1316
|
`)}process.stderr.write(`
|
|
1317
|
-
`)}function eS(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var fu;var Ci=x(()=>{We();ue();Je();nl();ml();hl();yl();kl();Cl();fu=["run","list","results","create"]});import{readFileSync as wu}from"node:fs";import{fileURLToPath as bu}from"node:url";import{Server as tS}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as rS}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as nS,CallToolRequestSchema as sS,ListResourcesRequestSchema as oS,ReadResourceRequestSchema as iS}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"?fr: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 se(e){let t=lS[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}function pS(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 xi(e){return{...e,_serverVersion:Be}}async function Su(e,t){let r=Cu.find((n)=>n.name===e);if(!r)return Ai(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(xi(n),null,2)}]}}catch(n){return Ai(n instanceof Error?n:Error(String(n)))}}function Ai(e){let{errorCode:t}=vr(e);return{content:[{type:"text",text:JSON.stringify(xi({error:!0,code:t,message:Na(e.message)}))}],isError:!0}}async function mS(){await Dr();let e=new rS;await tn.connect(e)}var vu="midnight-wallet://skill/core",ku="midnight-wallet://skill/full",aS="midnight-wallet://skill",cS,dS,lS,Cu,uS,yu,tn;var Au=x(()=>{pn();Us();Ar();Ia();Qs();cS=bu(new URL("../docs/SKILL-CORE.md",import.meta.url)),dS=bu(new URL("../docs/SKILL.md",import.meta.url));lS={generate:()=>Promise.resolve().then(() => (eo(),Pa)),info:()=>Promise.resolve().then(() => (to(),Oa)),balance:()=>Promise.resolve().then(() => ($o(),Nc)),address:()=>Promise.resolve().then(() => (_o(),Rc)),"genesis-address":()=>Promise.resolve().then(() => (Do(),Ic)),"inspect-cost":()=>Promise.resolve().then(() => (Po(),_c)),airdrop:()=>Promise.resolve().then(() => (jn(),Oc)),transfer:()=>Promise.resolve().then(() => (Oo(),Lc)),dust:()=>Promise.resolve().then(() => (Bn(),Wc)),cache:()=>Promise.resolve().then(() => (Mo(),Bc)),config:()=>Promise.resolve().then(() => (Fo(),Hc)),localnet:()=>Promise.resolve().then(() => (Ho(),rd)),wallet:()=>Promise.resolve().then(() => (Xn(),od)),status:()=>Promise.resolve().then(() => (ud(),ld)),contract:()=>Promise.resolve().then(() => (ys(),qd)),test:()=>Promise.resolve().then(() => (Ci(),hu))};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 se("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[fr]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await se("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 se("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[fr]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await se("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 se("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=we("info",e),r=await se("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=we("balance",e,t);delete r.flags.address;let n=await se("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=we("address",e),r=await se("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=we("genesis-address",e),r=await se("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=we("inspect-cost",{}),t=await se("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=we("airdrop",e,t);delete r.flags.amount;let n=await se("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=we("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await se("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=we("dust",e,"register"),r=await se("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=we("dust",e,"status"),r=await se("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 se("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 se("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=we("cache",e,"clear"),r=await se("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 se("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 se("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 se("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 se("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 se("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 se("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=we("contract",e,"inspect"),r=await se("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=we("contract",e,"state"),r=await se("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=we("contract",e,"deploy"),r=await se("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=we("contract",e,"call"),r=await se("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=we("test",e,"create"),r=await se("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=we("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await se("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")}}],uS=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),yu=Ra();tn=new tS({name:"midnight-wallet-cli",version:Be},{capabilities:{tools:{},resources:{}}});tn.setRequestHandler(oS,async()=>({resources:[{uri:vu,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:ku,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"}]}));tn.setRequestHandler(iS,async(e)=>{let t=e.params.uri;if(t===vu){let r=wu(cS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===ku||t===aS){let r=wu(dS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});tn.setRequestHandler(nS,async()=>({tools:Cu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));tn.setRequestHandler(sS,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=yu.redeem(s);if(!o)return Ai(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return Su(o.tool,o.args)}if(uS.has(t)){let s=yu.create({tool:t,args:n,description:pS(t,n)});return{content:[{type:"text",text:JSON.stringify(xi({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)});mS().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1318
|
-
`),process.exit(1)})});function
|
|
1319
|
-
`),n=Math.floor(e*100);if(t>=1)return xs;if(t<=0)return r.map((s,o)=>Array.from(s).map((i,a)=>
|
|
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:
|
|
1321
|
-
`)}var xs,pr,
|
|
1322
|
-
`),pr=["█▄ ▄█ █ █▀▄ █▄ █ █ █▀▀ █ █ ▀█▀","█ █ █ █ █ █ █ ██ █ █ █ █▀█ █ ","▀ ▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀▀ ▀ ▀ ▀ "];
|
|
1317
|
+
`)}function sS(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var yu;var xi=E(()=>{We();ue();Je();al();wl();bl();kl();xl();Tl();yu=["run","list","results","create"]});import{readFileSync as vu}from"node:fs";import{fileURLToPath as Au}from"node:url";import{Server as oS}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as iS}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as aS,CallToolRequestSchema as cS,ListResourcesRequestSchema as dS,ReadResourceRequestSchema as lS}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"?fr: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 se(e){let t=fS[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}function hS(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 Ni(e){return{...e,_serverVersion:Be}}async function Cu(e,t){let r=Tu.find((n)=>n.name===e);if(!r)return Ti(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(Ni(n),null,2)}]}}catch(n){return Ti(n instanceof Error?n:Error(String(n)))}}function Ti(e){let{errorCode:t}=vr(e);return{content:[{type:"text",text:JSON.stringify(Ni({error:!0,code:t,message:$a(e.message)}))}],isError:!0}}async function wS(){pn(),await _r();let e=new iS;await tn.connect(e)}var Eu="midnight-wallet://skill/core",xu="midnight-wallet://skill/full",uS="midnight-wallet://skill",pS,mS,fS,Tu,gS,ku,tn;var Nu=E(()=>{mn();js();Ar();_a();eo();ro();pS=Au(new URL("../docs/SKILL-CORE.md",import.meta.url)),mS=Au(new URL("../docs/SKILL.md",import.meta.url));fS={generate:()=>Promise.resolve().then(() => (no(),Fa)),info:()=>Promise.resolve().then(() => (so(),La)),balance:()=>Promise.resolve().then(() => (Po(),Dc)),address:()=>Promise.resolve().then(() => (Oo(),_c)),"genesis-address":()=>Promise.resolve().then(() => (Mo(),Pc)),"inspect-cost":()=>Promise.resolve().then(() => (Fo(),Mc)),airdrop:()=>Promise.resolve().then(() => (Wn(),Uc)),transfer:()=>Promise.resolve().then(() => (Lo(),Bc)),dust:()=>Promise.resolve().then(() => (Hn(),Kc)),cache:()=>Promise.resolve().then(() => (Uo(),Jc)),config:()=>Promise.resolve().then(() => (jo(),Vc)),localnet:()=>Promise.resolve().then(() => (Jo(),id)),wallet:()=>Promise.resolve().then(() => (Yn(),dd)),status:()=>Promise.resolve().then(() => (gd(),fd)),contract:()=>Promise.resolve().then(() => (Ss(),Qd)),test:()=>Promise.resolve().then(() => (xi(),bu))};Tu=[{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 se("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[fr]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await se("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 se("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[fr]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await se("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 se("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=we("info",e),r=await se("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=we("balance",e,t);delete r.flags.address;let n=await se("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=we("address",e),r=await se("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=we("genesis-address",e),r=await se("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=we("inspect-cost",{}),t=await se("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=we("airdrop",e,t);delete r.flags.amount;let n=await se("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=we("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await se("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=we("dust",e,"register"),r=await se("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=we("dust",e,"status"),r=await se("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 se("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 se("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=we("cache",e,"clear"),r=await se("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 se("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 se("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 se("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 se("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 se("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 se("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=we("contract",e,"inspect"),r=await se("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=we("contract",e,"state"),r=await se("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=we("contract",e,"deploy"),r=await se("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=we("contract",e,"call"),r=await se("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=we("test",e,"create"),r=await se("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=we("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await se("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")}}],gS=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),ku=Da();tn=new oS({name:"midnight-wallet-cli",version:Be},{capabilities:{tools:{},resources:{}}});tn.setRequestHandler(dS,async()=>({resources:[{uri:Eu,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:xu,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"}]}));tn.setRequestHandler(lS,async(e)=>{let t=e.params.uri;if(t===Eu){let r=vu(pS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===xu||t===uS){let r=vu(mS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});tn.setRequestHandler(aS,async()=>({tools:Tu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));tn.setRequestHandler(cS,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=ku.redeem(s);if(!o)return Ti(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return Cu(o.tool,o.args)}if(gS.has(t)){let s=ku.create({tool:t,args:n,description:hS(t,n)});return{content:[{type:"text",text:JSON.stringify(Ni({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 Cu(t,n)});wS().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1318
|
+
`),process.exit(1)})});function Iu(e){let t=Math.max(0,Math.min(1,e)),r=pr[0].length,n=Math.floor(t*r);return pr.map((s)=>s.slice(0,n).padEnd(r))}function $u(e){let t=Math.max(0,Math.min(1,e)),r=Math.floor(e*100);if(t>=1)return pr;return pr.map((n,s)=>Array.from(n).map((o,i)=>{if(o===" ")return" ";if(t<=0)return Ts(s+20,i,0);let a=((s+20)*131+i*997)%100/100;return t>=a?o:Ts(s+20,i,r)}).join(""))}function Ts(e,t,r){let n=(e*131+t*997+r*7919)%65537/65537;return Ru[Math.floor(n*Ru.length)]}function Du(e){let t=Math.max(0,Math.min(1,e)),r=xs.split(`
|
|
1319
|
+
`),n=Math.floor(e*100);if(t>=1)return xs;if(t<=0)return r.map((s,o)=>Array.from(s).map((i,a)=>Ts(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:Ts(o,a,n)}).join("")).join(`
|
|
1321
|
+
`)}var xs,pr,Ri,Ru;var Ii=E(()=>{xs=[" ████████████ "," ███ ███ "," ███ ██ ███ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ███ ███ "," ███ ███ "," ████████████ "].join(`
|
|
1322
|
+
`),pr=["█▄ ▄█ █ █▀▄ █▄ █ █ █▀▀ █ █ ▀█▀","█ █ █ █ █ █ █ ██ █ █ █ █▀█ █ ","▀ ▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀▀ ▀ ▀ ▀ "];Ri=[["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"]],Ru=["░","▒","▓","█","·"," "]});function Di(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 _u(e,t,r){let s=xs.split(`
|
|
1323
1323
|
`),o=s.length,i=36,a=Math.max(o,t?.length??0),c=3,d=r?.animated??!0;if(!lt()||!d){let m=lt();for(let w=0;w<a;w++){let y=w<o?s[w]:"",S=m?je(y).padEnd(45):y.padEnd(35),b=t?.[w]??"",v=m&&w<3&&b?k(je(b)):b;if(m)process.stderr.write(y?je(y)+"\x1B[36G"+v+`
|
|
1324
1324
|
`:"\x1B[36G"+v+`
|
|
1325
1325
|
`);else process.stderr.write(S+v+`
|
|
1326
1326
|
`)}return}function l(m,w){for(let y=0;y<a;y++){let S=y<m.length?je(m[y]):"",b=w[y]??"";if(b)process.stderr.write(S+"\x1B[36G"+b+`\x1B[K
|
|
1327
1327
|
`);else process.stderr.write(S+`\x1B[K
|
|
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=
|
|
1329
|
-
`);if(m>0)p();l(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=Du(w).split(`
|
|
1329
|
+
`);if(m>0)p();l(S,[]),await Di($i,e)}let f=20;for(let m=0;m<=f;m++){if(e?.aborted)break;let w=m/f,y=Iu(w);p();let S=Array(a).fill(null);for(let b=0;b<y.length;b++)S[b]=k(je(y[b]));l(s,S),await Di($i,e)}let g=12;for(let m=0;m<=g;m++){if(e?.aborted)break;let w=m/g,y=$u(w);p();let S=Array(a).fill(null);for(let b=0;b<y.length;b++)S[b]=k(je(y[b]));l(s,S),await Di($i,e)}p();let h=Array(a).fill(null);if(t)for(let m=0;m<t.length;m++)if(m<3)h[m]=k(je(t[m]));else h[m]=t[m];l(s,h)}var $i=80;var Pu=E(()=>{Ii()});import{existsSync as yS,writeFileSync as SS}from"node:fs";import{join as bS}from"node:path";import{tmpdir as vS}from"node:os";function kS(){return(process.env.TERM_SESSION_ID??process.env.ITERM_SESSION_ID??`pid-${process.ppid}`).replace(/[^a-zA-Z0-9-]/g,"_").slice(0,64)}function Ou(){return bS(vS(),`mn-intro-${kS()}`)}function Mu(){return yS(Ou())}function Fu(){try{SS(Ou(),String(Date.now()))}catch{}}var Lu=()=>{};function CS(){let e=[];for(let t of pr)e.push(t);e.push(""),e.push(k("Commands"));for(let[t,r]of Ri)e.push(`${U(t.padEnd(18))}${r}`);return e.push(""),e.push(u("midnight (or mn) help <command>")),e.push(u("--json flag available on all commands")),e.push(u("midnight help --agent")+u(" AI & MCP reference")),e}function AS(){process.stderr.write(`
|
|
1330
1330
|
Commands:
|
|
1331
1331
|
|
|
1332
|
-
`);for(let[e,t]of
|
|
1332
|
+
`);for(let[e,t]of Ri)process.stderr.write(` ${e.padEnd(18)}${t}
|
|
1333
1333
|
`);process.stderr.write(`
|
|
1334
1334
|
Usage: midnight <command> (or: mn <command>)
|
|
1335
1335
|
`),process.stderr.write(` --json flag available on all commands
|
|
1336
1336
|
`),process.stderr.write(` midnight help --agent AI & MCP reference
|
|
1337
1337
|
|
|
1338
|
-
`)}function
|
|
1338
|
+
`)}function ES(e){if(process.stdout.write(`
|
|
1339
1339
|
`+j(e.name)+`
|
|
1340
1340
|
|
|
1341
1341
|
`),process.stdout.write(` ${e.description}
|
|
@@ -1349,7 +1349,7 @@ Commands:
|
|
|
1349
1349
|
`)}if(e.examples&&e.examples.length>0){process.stdout.write(rt("Examples:")+`
|
|
1350
1350
|
`);for(let t of e.examples)process.stdout.write(` ${u("$")} ${t}
|
|
1351
1351
|
`);process.stdout.write(`
|
|
1352
|
-
`)}}function
|
|
1352
|
+
`)}}function xS(){let e={cli:{name:Cr,version:Be,description:fa,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:mr.map((t)=>({name:t.name,description:t.description,usage:t.usage,flags:t.flags,examples:t.examples,jsonFields:t.jsonFields}))};P(e)}function TS(){let e=`
|
|
1353
1353
|
MIDNIGHT CLI — AI Agent & MCP Reference
|
|
1354
1354
|
========================================
|
|
1355
1355
|
|
|
@@ -1528,6 +1528,7 @@ ERROR CODES
|
|
|
1528
1528
|
PROOF_FAILURE 6 Proof server failed to generate the ZK proof
|
|
1529
1529
|
INVALID_DUST_PROOF 6 Chain rejected the dust spend proof as malformed
|
|
1530
1530
|
DUST_REQUIRED 5 No dust tokens available for fees
|
|
1531
|
+
UNSUPPORTED_NODE 1 Node.js is older than 22; install a current one
|
|
1531
1532
|
CANCELLED 7 Operation cancelled (SIGINT)
|
|
1532
1533
|
UNKNOWN 1 Unclassified error
|
|
1533
1534
|
|
|
@@ -1740,17 +1741,17 @@ EXAMPLE CLI COMMANDS
|
|
|
1740
1741
|
# Start DApp connector
|
|
1741
1742
|
midnight serve --network preview --approve-all
|
|
1742
1743
|
# DApps connect at ws://localhost:9932
|
|
1743
|
-
`;process.stdout.write(e)}async function
|
|
1744
|
-
Available commands: ${mr.map((c)=>c.name).join(", ")}`);vS(a);return}if(!process.stderr.isTTY){bS();return}let r=SS(),n=T(e,"intro"),s=T(e,"no-intro"),o=_u(),i=n||!s&&!o;if(await Ru(void 0,r,{animated:i}),i)Du()}var mr;var $i=x(()=>{ue();Iu();Ti();Pu();We();Ar();mr=[{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${kt}`,"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 AS}from"node:child_process";function xS(e){return`${k(Ou)}
|
|
1744
|
+
`;process.stdout.write(e)}async function _i(e){if(T(e,"agent")){TS();return}if(T(e,"json")){xS();return}let t=e.subcommand;if(t){let a=mr.find((c)=>c.name===t);if(!a)throw new Y(`Unknown command: "${t}"
|
|
1745
|
+
Available commands: ${mr.map((c)=>c.name).join(", ")}`);ES(a);return}if(!process.stderr.isTTY){AS();return}let r=CS(),n=T(e,"intro"),s=T(e,"no-intro"),o=Mu(),i=n||!s&&!o;if(await _u(void 0,r,{animated:i}),i)Fu()}var mr;var Pi=E(()=>{ue();Pu();Ii();Lu();We();Ar();mr=[{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${kt}`,"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 NS}from"node:child_process";function RS(e){return`${k(Uu)}
|
|
1745
1746
|
${k(je(e))}
|
|
1746
|
-
${k(
|
|
1747
|
+
${k(Uu)}
|
|
1747
1748
|
`}function bt(e){return`
|
|
1748
|
-
${u(
|
|
1749
|
+
${u(ju)}
|
|
1749
1750
|
${k(je(e))}
|
|
1750
|
-
${u(
|
|
1751
|
-
`}function
|
|
1752
|
-
`)}function
|
|
1753
|
-
`)}function
|
|
1751
|
+
${u(ju)}
|
|
1752
|
+
`}function IS(e){let t=[];if(t.push(`${U(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(` ${F(n[2])}${n[3]}${n[4]}`);else if(/^[A-Za-z][\w -]*:/.test(r))t.push(` ${u(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(` ${u("$")} ${u(r)}`)}return t.join(`
|
|
1753
|
+
`)}function Oi(){let e=[];e.push(RS(`${Cr} manual v${Be}`)),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(` ${u("$")} ${u("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(bt("CONCEPTS")),e.push(` ${k("Networks")}`),e.push(` ${U("undeployed")} Local Docker network. Free dev tokens, fast iteration.`),e.push(` ${U("preprod")} Public testnet. Persistent, real ZK proofs.`),e.push(` ${U("preview")} Public testnet, smaller scale.`),e.push(""),e.push(` ${k("Tokens")}`),e.push(` ${F("NIGHT")} Native asset. Used for transfers and contract value.`),e.push(` ${F("DUST")} Fee token. Generated from registered NIGHT UTXOs.`),e.push(""),e.push(` ${k("Wallets")}`),e.push(` Stored at ${u("~/.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(` ${F("Unshielded")} addresses (mn_addr_*) are like UTXOs.`),e.push(` ${F("Shielded")} addresses (mn_shield-addr_*) hide amount and recipient.`),e.push(bt("COMMANDS"));for(let t of mr)e.push(IS(t)),e.push("");return e.push(bt("COMMON FLOWS")),e.push(` ${k("First wallet on undeployed")}`),e.push(` ${u("$")} ${u("mn localnet up")}`),e.push(` ${u("$")} ${u("mn wallet generate alice")}`),e.push(` ${u("$")} ${u("mn airdrop 1000 --wallet alice")}`),e.push(` ${u("$")} ${u("mn dust register --wallet alice")}`),e.push(` ${u("$")} ${u("mn balance --wallet alice")}`),e.push(""),e.push(` ${k("First wallet on preprod")}`),e.push(` ${u("$")} ${u("mn wallet generate alice --network preprod")}`),e.push(` ${u("# fund from the preprod faucet:")}`),e.push(` ${u("# https://faucet.preprod.midnight.network/")}`),e.push(` ${u("$")} ${u("mn dust register --wallet alice --network preprod")}`),e.push(` ${u("$")} ${u("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(` ${u("$")} ${u("mn contract deploy --wallet alice")}`),e.push(` ${u(" → Address: 64da9d71cb…")}`),e.push(` ${u("$")} ${u("mn contract state --address 64da9d71cb… --wallet alice")}`),e.push(` ${u(' → { "round": 0 }')}`),e.push(` ${u("$")} ${u("mn contract call --address 64da9d71cb… --circuit increment --wallet alice")}`),e.push(` ${u("$")} ${u("mn contract state --address 64da9d71cb… --wallet alice")}`),e.push(` ${u(' → { "round": 1 }')}`),e.push(""),e.push(" Same artifact on preprod — swap one flag:"),e.push(` ${u("$")} ${u("mn contract deploy --network preprod --wallet alice")}`),e.push(""),e.push(` ${k("Transfer NIGHT between wallets")}`),e.push(` ${u("$")} ${u("mn transfer bob 100 --wallet alice")}`),e.push(` ${u(" shielded variant:")}`),e.push(` ${u("$")} ${u("mn transfer bob 100 --shielded --wallet alice")}`),e.push(bt("CONFIGURATION")),e.push(` ${k("Files")}`),e.push(` ${u("~/.midnight/config.json")} Persistent CLI settings`),e.push(` ${u("~/.midnight/wallets/")} Per-wallet JSON files (mode 0600)`),e.push(` ${u("~/.midnight/cache/<network>/")} Wallet sync cache, per network`),e.push(""),e.push(` ${k("Config keys")}`),e.push(` ${F("network")} Default network when --network is omitted`),e.push(` ${F("wallet")} Default wallet when --wallet is omitted`),e.push(` ${F("proof-server")} Override proof server URL`),e.push(` ${F("node")} Override substrate RPC URL`),e.push(` ${F("indexer-ws")} Override indexer WebSocket URL`),e.push(""),e.push(` ${k("Compatibility alias")}`),e.push(` ${F("network-id")} Resolves transparently to ${F("network")}.`),e.push(""),e.push(` ${k("Examples")}`),e.push(` ${u("$")} ${u("mn config set network preprod")}`),e.push(` ${u("$")} ${u("mn config get network")}`),e.push(` ${u("$")} ${u("mn config unset proof-server")}`),e.push(bt("JSON OUTPUT")),e.push(` Every command accepts ${F("--json")} for structured output on stdout.`),e.push(" Stderr keeps the chrome (spinners, headers); stdout stays parseable."),e.push(""),e.push(` ${u("$")} ${u("mn balance <addr> --json | jq -r .NIGHT")}`),e.push(` ${u("$")} ${u("mn wallet info alice --json")}`),e.push(""),e.push(` Stable JSON shapes are documented in ${u("docs/JSON_CONTRACT.md")}.`),e.push(" We promise not to break those without a major version bump."),e.push(bt("EXIT CODES")),e.push(` ${$S("0")} Success`),e.push(` ${u("1")} Unknown error`),e.push(` ${DS("2")} Invalid arguments (usage error, see yellow box on stderr)`),e.push(` ${u("3")} Wallet not found`),e.push(` ${u("4")} Network error`),e.push(` ${u("5")} Insufficient balance / DUST_REQUIRED`),e.push(` ${u("6")} Transaction rejected / STALE_UTXO / PROOF_TIMEOUT`),e.push(` ${u("7")} Cancelled by user`),e.push(""),e.push(` ${k("Stable error code strings")} (in JSON ${F("--json")} error output):`),e.push(` ${F("DUST_REQUIRED")} No dust available to pay fees`),e.push(` ${F("STALE_UTXO")} UTXO consumed concurrently, retry`),e.push(` ${F("PROOF_TIMEOUT")} Proof generation exceeded deadline`),e.push(` ${F("PROOF_FAILURE")} Proof server rejected the proof`),e.push(` ${F("INVALID_DUST_PROOF")} Stale commitment tree, run ${u("mn cache clear")}`),e.push(` ${F("STALE_CACHE")} Local cache out of sync, run ${u("mn cache clear")}`),e.push(` ${F("SYNC_TIMEOUT")} Wallet sync exceeded its deadline`),e.push(bt("TROUBLESHOOTING")),e.push(` ${k('Sync hangs forever or "applied > highest" error')}`),e.push(" Stale cache after a chain reset. Recover with:"),e.push(` ${u("$")} ${u("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(` ${u("$")} ${u("mn dust register --wallet <name>")}`),e.push(" Then wait until status shows availability:"),e.push(` ${u("$")} ${u("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(` ${u("$")} ${u("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(` ${u("$")} ${u("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(` ${u("$")} ${u("pkill -f 'mn serve'")}`),e.push(bt("SEE ALSO")),e.push(` ${U("mn help")} Brief command list`),e.push(` ${U("mn help <command>")} Help for one command (flags and examples)`),e.push(` ${U("mn help --agent")} Comprehensive AI / MCP reference`),e.push(""),e.push(` Repository: ${u("github.com/nel349/midnight-wallet-cli")}`),e.push(` JSON contract: ${u("docs/JSON_CONTRACT.md")}`),e.push(""),e.join(`
|
|
1754
|
+
`)}function $S(e){return`\x1B[32m${e}\x1B[0m`}function DS(e){return`\x1B[33m${e}\x1B[0m`}async function _S(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=NS(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 Mi(e){let t=!T(e,"no-pager");if(T(e,"json")){await Promise.resolve();P({name:Cr,version:Be,manual:Oi()});return}if(T(e,"raw")){process.stdout.write(Oi().replace(/\x1b\[[0-9;]*m/g,""));return}await _S(Oi(),t)}var Uu,ju;var Wu=E(()=>{Pi();Ar();Uu="═".repeat(63),ju="─".repeat(64)});async function ji(e,t){dt(e);let r=x(e,"port"),n=r?parseInt(r,10):At;if(Number.isNaN(n)||n<1||n>65535)throw Error(`Invalid port: "${r}" — must be 1-65535`);let s=T(e,"approve-all"),o=s||!T(e,"no-auto-approve-reads"),i=T(e,"json"),a=de(oe(x(e,"wallet"))),c=Buffer.from(a.seed,"hex"),{name:d,config:l}=te({args:e}),p=a.addresses[d];Me(l,{proofServer:x(e,"proof-server"),node:x(e,"node"),indexerWS:x(e,"indexer-ws")},d),process.stderr.write(`
|
|
1754
1755
|
`+j("DApp Connector Server")+`
|
|
1755
1756
|
|
|
1756
1757
|
`),process.stderr.write(A("Network",d)+`
|
|
@@ -1760,13 +1761,13 @@ ${u(Mu)}
|
|
|
1760
1761
|
`),process.stderr.write(A("Auto-approve balancing",s?"yes":"no")+`
|
|
1761
1762
|
`),process.stderr.write(A("Auto-approve writes",s?"yes":"no")+`
|
|
1762
1763
|
`),process.stderr.write(`
|
|
1763
|
-
`);let f=he((m,w)=>{let y=
|
|
1764
|
-
`)}),g=
|
|
1765
|
-
`)},onDisconnect:(L)=>{process.stderr.write(u(` [${
|
|
1766
|
-
`),v?.revertPendingTxs(L.id).catch(()=>{})},onRequest:(L,J)=>{process.stderr.write(u(` [${
|
|
1767
|
-
`)},onResponse:(L,J,M,O,Q,le)=>{if(Q&&
|
|
1764
|
+
`);let f=he((m,w)=>{let y=Rc();if(y)y.log(u(` SDK: ${w}`));else process.stderr.write(u(` SDK: ${w}`)+`
|
|
1765
|
+
`)}),g=Ce();if(Ie(e))Pe();let h=G("Syncing wallet...");await me().withFacade(c,l,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 Le(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..."},_;if(v=as({bundle:m,networkConfig:l,approvalOptions:{approveAll:s,autoApproveReads:o},callbacks:{onPhaseStart:(L,J,M)=>{if(M==="approve")return;let O=R[M]??`${M}...`;if(_)_.update(O);else _=G(O)},onPhaseComplete:(L,J,M,O)=>{if(M==="approve")return;if(M==="proving"||M==="submitting")_?.stop(`${M} ${Ui(O)}`),_=void 0}}}),b=ns({port:n,handlers:v.handlers,onConnect:(L)=>{process.stderr.write(u(` [${Fi()}] `)+H("connected")+u(` ${L.id}`)+`
|
|
1766
|
+
`)},onDisconnect:(L)=>{process.stderr.write(u(` [${Fi()}] `)+V("disconnected")+u(` ${L.id}`)+`
|
|
1767
|
+
`),v?.revertPendingTxs(L.id).catch(()=>{})},onRequest:(L,J)=>{process.stderr.write(u(` [${Fi()}] ${L.id} #${L.requestCount} → ${J.method}`)+`
|
|
1768
|
+
`)},onResponse:(L,J,M,O,Q,le)=>{if(Q&&_)_.fail("Failed"),_=void 0;let Ft=Ui(M);if(Q){let I=Q.code==="Rejected"?"rejected by operator":Q.message;if(process.stderr.write(` ${V("✗")} ${u(`${L.id} ← ${J.method} (${Ft})`)} ${V(I)}
|
|
1768
1769
|
`),Q.code!=="Rejected"&&Q.message)process.stderr.write(` ${u(" error:")} ${Q.message}
|
|
1769
|
-
`)}else{let I=le?.phases,C=I&&I.length>0?": "+I.map((
|
|
1770
|
+
`)}else{let I=le?.phases,C=I&&I.length>0?": "+I.map((D)=>`${D.phase} ${Ui(D.durationMs)}`).join(", "):"";process.stderr.write(` ${H("✓")} ${u(`${L.id} ← ${J.method} (${Ft}${C})`)}
|
|
1770
1771
|
`);let N=O?.txHash;if(J.method==="submitTransaction"&&N)process.stderr.write(` ${u(" tx:")} ${U(String(N))}
|
|
1771
1772
|
`)}}}),process.stderr.write(`
|
|
1772
1773
|
`+z()+`
|
|
@@ -1777,18 +1778,18 @@ ${u(Mu)}
|
|
|
1777
1778
|
`+u(" Shutting down...")+`
|
|
1778
1779
|
`),!v.hasPendingTxs())try{await Le(p,d,m.facade)}catch{}try{await b.close()}catch{}v.dispose(),v=void 0,b=void 0,process.stderr.write(u(" Server stopped.")+`
|
|
1779
1780
|
|
|
1780
|
-
`)}catch(R){if(h.fail("Failed"),b)try{await b.close()}catch{}throw v?.dispose(),R}},{syncMode:Gt(d,T(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
|
|
1781
|
-
Run "mn dev" from a Midnight project directory (expected .compact files in ./, ./src, ./contract, or ./contract/src).`);let s=
|
|
1781
|
+
`)}catch(R){if(h.fail("Failed"),b)try{await b.close()}catch{}throw v?.dispose(),R}},{syncMode:Gt(d,T(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 Fi(){let e=new Date;return`${Li(e.getHours())}:${Li(e.getMinutes())}:${Li(e.getSeconds())}`}function Li(e){return e<10?"0"+e:String(e)}function Ui(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var Bu=E(()=>{st();ke();pe();De();Ge();wt();it();St();si();ss();bn();ue();Je()});import{existsSync as Ku,readFileSync as PS,readdirSync as OS,statSync as MS}from"node:fs";import{dirname as FS,join as Wi,resolve as Hu}from"node:path";function Ju(e){let t=Hu(e),r=new Set,n=new Set;for(let p of jS){let f=Hu(t,p);if(!Ku(f))continue;Xu(f,0,r,n)}if(r.size===0)throw Error(`No .compact source files found under ${t}
|
|
1782
|
+
Run "mn dev" from a Midnight project directory (expected .compact files in ./, ./src, ./contract, or ./contract/src).`);let s=GS([...n],t),o=s?.dir??t,i=s?.packageJson??zu(Wi(t,"package.json")),a=s?.script??Vu(i),c=[...r].filter((p)=>Gu(p,o)).sort(),d=[...n].filter((p)=>Gu(p,o)).sort(),l=HS(i);return{projectRoot:o,sourceFiles:c.length>0?c:[...r].sort(),sourceDirs:d.length>0?d:[...n].sort(),compileScript:a,hasNpmCompileScript:a!==null,testScript:l,packageJson:i}}function HS(e){for(let t of US)if(qu(e,t))return t;return null}function Gu(e,t){if(e===t)return!0;let r=t.endsWith("/")?t:t+"/";return e.startsWith(r)}function GS(e,t){for(let r of e){let n=r;while(!0){let s=Wi(n,"package.json"),o=zu(s),i=Vu(o);if(o&&i)return{dir:n,packageJson:o,script:i};if(n===t)break;let a=FS(n);if(a===n)break;n=a}}return null}function Vu(e){for(let t of LS)if(qu(e,t))return t;return null}function zu(e){if(!Ku(e))return null;try{let t=JSON.parse(PS(e,"utf-8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function qu(e,t){if(!e)return!1;let r=e.scripts;if(!r||typeof r!=="object")return!1;return typeof r[t]==="string"}function Xu(e,t,r,n){if(t>WS)return;let s;try{s=OS(e)}catch{return}for(let o of s){if(o.startsWith(".")||BS.has(o))continue;let i=Wi(e,o),a=!1;try{a=MS(i).isDirectory()}catch{continue}if(a)Xu(i,t+1,r,n);else if(o.endsWith(".compact"))r.add(i),n.add(e)}}var LS,US,jS,WS=4,BS;var Yu=E(()=>{LS=["compact","compile"],US=["test:dev","test"],jS=[".","contract/src","contract","src"],BS=new Set(["node_modules",".git","dist","build","managed","target"])});import{spawn as KS}from"node:child_process";async function Zu(e){let{bin:t,args:r,label:n}=JS(e),s=Date.now();return new Promise((o,i)=>{let a=KS(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 l=()=>{a.kill("SIGTERM")};if(e.signal)if(e.signal.aborted)l();else e.signal.addEventListener("abort",l,{once:!0});a.on("error",(p)=>{e.signal?.removeEventListener("abort",l),i(Error(`Failed to spawn "${n}": ${p.message}`))}),a.on("close",(p)=>{e.signal?.removeEventListener("abort",l),o({success:p===0,durationMs:Date.now()-s,command:n,stdout:c,stderr:d,exitCode:p??-1})})})}function JS(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.
|
|
1782
1783
|
Add one of:
|
|
1783
1784
|
"compact": "compact compile src/<your>.compact src/managed/<your>"
|
|
1784
1785
|
"compile": "compact compile src/<your>.compact src/managed/<your>"
|
|
1785
|
-
create-mn-app and midnight-starship templates ship with this script already wired.`)}var
|
|
1786
|
+
create-mn-app and midnight-starship templates ship with this script already wired.`)}var Qu=()=>{};import{spawn as VS}from"node:child_process";async function ep(e){let{bin:t,args:r,label:n}=zS(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 zS(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.
|
|
1786
1787
|
Add a "test:dev" or "test" script that runs your contract tests
|
|
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
|
|
1788
|
-
`)})};return t.on("data",s),{stop(){if(n)return;n=!0,t.off("data",s);try{t.setRawMode(r)}catch{}}}}var
|
|
1788
|
+
(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 tp=()=>{};import{watch as qS}from"node:fs";import{join as XS}from"node:path";function rp(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=qS(i,{persistent:!0},(c,d)=>{if(!d)return;if(!d.endsWith(e.extension))return;if(n.add(XS(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 np=()=>{};async function sp(e){if(ZS())return e?.("Localnet already running"),{state:"already-running"};return e?.("Writing compose file"),tr(),e?.("Starting localnet containers"),Ve("up -d"),e?.("Waiting for services to be healthy"),{state:rr(120000)?"started":"started-unhealthy"}}function YS(){try{return at()}catch{return[]}}function ZS(){let e=YS(),t=new Map(e.map((r)=>[r.name,r]));for(let r of Ko){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 op=E(()=>{qn()});import{existsSync as QS}from"node:fs";import{join as eb}from"node:path";import{homedir as tb}from"node:os";async function cp(e){let t=[],r=rb();try{for(let n of e.names){if(e.signal?.throwIfAborted(),dp(n)){e.onProgress?.(n,"done","reused"),t.push({name:n,state:"reused"});continue}e.onProgress?.(n,"creating","created"),await sb(n,e.signal),e.onProgress?.(n,"funding","created"),await ob(n,e.amountNight,e.signal),e.onProgress?.(n,"dust","created"),await ib(n,e.signal),e.onProgress?.(n,"done","created"),t.push({name:n,state:"created"})}}finally{nb(r)}return t}function rb(){try{return mt()}catch{return null}}function nb(e){if(!e)return;if(!dp(e))return;try{Dr(e)}catch{}}function dp(e){let t=eb(tb(),ce,Lt,`${e}.json`);return QS(t)}async function sb(e,t){let r={command:"wallet",subcommand:"generate",positionals:[e],flags:{network:"undeployed"}};await Promise.resolve().then(() => Yn());await q(nr,r,t)}async function ob(e,t,r){let n={command:"airdrop",subcommand:String(t),positionals:[],flags:{wallet:e,network:"undeployed"}};await Promise.resolve().then(() => Wn());await q(Qt,n,r)}async function ib(e,t){let r={command:"dust",subcommand:"register",positionals:[],flags:{wallet:e,network:"undeployed"}};await Promise.resolve().then(() => Hn());await q(er,r,t)}var ip,ap=1000;var lp=E(()=>{mn();ke();ip=["dev-alice","dev-bob","dev-carol"]});function up(e){if(!ab)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}
|
|
1789
|
+
`)})};return t.on("data",s),{stop(){if(n)return;n=!0,t.off("data",s);try{t.setRawMode(r)}catch{}}}}var ab;var pp=E(()=>{ab=typeof process.stdin.isTTY==="boolean"&&process.stdin.isTTY===!0});import{resolve as cb,relative as mp}from"node:path";async function Bi(e,t){let r=cb(e.positionals[0]??process.cwd());process.stderr.write(`
|
|
1789
1790
|
`+j("mn dev")+`
|
|
1790
1791
|
|
|
1791
|
-
`);let n=
|
|
1792
|
+
`);let n=Ju(r);if(!n.compileScript)throw Error(`No compile script found in ${n.projectRoot}/package.json.
|
|
1792
1793
|
mn dev looks for a "compact" or "compile" npm script that invokes the
|
|
1793
1794
|
Compact toolchain. Add one of:
|
|
1794
1795
|
"scripts": { "compact": "compact compile src/my.compact src/managed/my" }
|
|
@@ -1797,50 +1798,50 @@ create-mn-app and midnight-starship templates ship with this already wired.`);pr
|
|
|
1797
1798
|
`),process.stderr.write(A("Sources",`${n.sourceFiles.length} .compact file(s)`)+`
|
|
1798
1799
|
`),process.stderr.write(A("Compile",`npm run ${n.compileScript}`)+`
|
|
1799
1800
|
|
|
1800
|
-
`);let s=G("Checking localnet...");try{let S=await
|
|
1801
|
+
`);let s=G("Checking localnet...");try{let S=await sp((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 cp({names:ip,amountNight:ap,signal:t,onProgress:(_,Z)=>{let L={creating:"generating",funding:"airdropping",dust:"registering dust",done:"ready"}[Z];o.update(`${_}: ${L}`)}}),b=S.filter((_)=>_.state==="created").length,v=S.length-b,R=[b?`${b} created`:"",v?`${v} reused`:""].filter(Boolean).join(", ");o.stop(`Dev wallets: ${S.map((_)=>_.name).join(", ")} (${R})`)}catch(S){throw o.fail("Wallet provisioning failed"),S}let i=null,a=!1,c=!1,d=!1,l=!1;if(i=await hp(n,t),!i.success)process.stderr.write(u(`
|
|
1801
1802
|
Fix the errors above and save — mn dev will recompile automatically.
|
|
1802
|
-
`));let p=async()=>{if(a||c)return;if(d){l=!0;return}d=!0;try{i=await
|
|
1803
|
+
`));let p=async()=>{if(a||c)return;if(d){l=!0;return}d=!0;try{i=await hp(n,t)}finally{if(d=!1,l)l=!1,p()}},f=rp({dirs:n.sourceDirs,extension:".compact",onChange:async(S)=>{let b=S.map((v)=>mp(n.projectRoot,v)).join(", ");process.stderr.write(`
|
|
1803
1804
|
`+u(` Changed: ${b}`)+`
|
|
1804
1805
|
`),await p()},onError:(S)=>{process.stderr.write(V(" watch error: ")+S.message+`
|
|
1805
1806
|
`)}});process.stderr.write(`
|
|
1806
1807
|
`+z()+`
|
|
1807
|
-
`);let g=n.sourceDirs.map((S)=>
|
|
1808
|
+
`);let g=n.sourceDirs.map((S)=>mp(n.projectRoot,S)||".").join(", ");process.stderr.write(u(" Watching ")+U(g)+u(" — save to recompile.")+`
|
|
1808
1809
|
`);let h=n.testScript?k("[t]")+u(` test (${n.testScript}) `):"";process.stderr.write(u(" ")+k("[d]")+u(" deploy ")+h+k("[q]")+u(` quit
|
|
1809
1810
|
|
|
1810
|
-
`));let m=new AbortController,w=()=>{if(!m.signal.aborted)m.abort()},y=
|
|
1811
|
+
`));let m=new AbortController,w=()=>{if(!m.signal.aborted)m.abort()},y=up({actions:{d:async()=>{if(a){process.stderr.write(u(` Deploy already in flight — ignoring key press.
|
|
1811
1812
|
`));return}if(c){process.stderr.write(u(` Tests are running — wait for them to finish before deploying.
|
|
1812
1813
|
`));return}if(!i?.success){process.stderr.write(F(` Cannot deploy — last compile did not succeed. Fix and save first.
|
|
1813
|
-
`));return}a=!0;try{await
|
|
1814
|
+
`));return}a=!0;try{await db(n)}finally{a=!1}},t:async()=>{if(c){process.stderr.write(u(` Tests already in flight — ignoring key press.
|
|
1814
1815
|
`));return}if(a){process.stderr.write(u(` Deploy in flight — wait for it to finish before running tests.
|
|
1815
1816
|
`));return}if(!n.testScript){process.stderr.write(F(` No test script found. Add "test:dev" or "test" to package.json.
|
|
1816
1817
|
`));return}if(!i?.success){process.stderr.write(F(` Cannot run tests — last compile did not succeed. Fix and save first.
|
|
1817
|
-
`));return}c=!0;try{await
|
|
1818
|
+
`));return}c=!0;try{await lb(n,m.signal)}finally{c=!1}},q:()=>w()},onInterrupt:w});await new Promise((S)=>{let b=()=>{y.stop(),f.stop(),process.stderr.write(`
|
|
1818
1819
|
`+u(" mn dev stopped.")+`
|
|
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
|
|
1820
|
+
`),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 db(e){let t=process.cwd();if(t!==e.projectRoot)try{process.chdir(e.projectRoot)}catch{}try{let r=await ub(e.projectRoot);if(r.length>0&&!ls(e.projectRoot)){let s=us({projectRoot:e.projectRoot,witnessNames:r});process.stderr.write(F(` ✗ Cannot auto-deploy:
|
|
1820
1821
|
`));for(let o of s.split(`
|
|
1821
1822
|
`))process.stderr.write(u(` ${o}
|
|
1822
|
-
`));return}let n=G(`Deploying with ${
|
|
1823
|
+
`));return}let n=G(`Deploying with ${fp} on ${gp}...`);try{await Promise.resolve().then(() => Ss());let o=await q(ar,{command:"contract",subcommand:"deploy",positionals:[],flags:{wallet:fp,network:gp}});n.stop("Deployed");let i=typeof o.address==="string"?o.address:"(unknown)";process.stderr.write(` ${u("address")} ${U(i)}
|
|
1823
1824
|
`)}catch(s){n.fail("Deploy failed");let o=s instanceof Error?s.message:String(s);process.stderr.write(V(" "+o)+`
|
|
1824
|
-
`)}}finally{if(process.cwd()!==t)try{process.chdir(t)}catch{}}}async function
|
|
1825
|
+
`)}}finally{if(process.cwd()!==t)try{process.chdir(t)}catch{}}}async function lb(e,t){process.stderr.write(u(`
|
|
1825
1826
|
Running npm run ${e.testScript}...
|
|
1826
|
-
`));try{let r=await
|
|
1827
|
-
`);else process.stderr.write(` ${u("─")} ${V("Tests failed")} ${u(`(exit ${r.exitCode}, ${
|
|
1827
|
+
`));try{let r=await ep({project:e,signal:t});if(r.success)process.stderr.write(` ${u("─")} Tests passed ${u(`(${Ns(r.durationMs)})`)}
|
|
1828
|
+
`);else process.stderr.write(` ${u("─")} ${V("Tests failed")} ${u(`(exit ${r.exitCode}, ${Ns(r.durationMs)})`)}
|
|
1828
1829
|
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(V(" Test runner error: ")+n+`
|
|
1829
|
-
`)}}async function
|
|
1830
|
-
`),process.stderr.write(F(
|
|
1830
|
+
`)}}async function ub(e){try{await Promise.resolve().then(() => Vr());let{info:r}=ze(e);return r.witnesses.map((n)=>n.name)}catch{return[]}}async function hp(e,t){let r=G("Compiling...");try{let n=await Zu({project:e,signal:t});if(n.success)r.stop(`Compiled ${u(`(${Ns(n.durationMs)})`)}`);else if(r.fail(`Compile failed ${u(`(${Ns(n.durationMs)})`)}`),n.stderr.trim())process.stderr.write(u(" ─ stderr ─")+`
|
|
1831
|
+
`),process.stderr.write(F(pb(n.stderr.trim()," "))+`
|
|
1831
1832
|
`);return n}catch(n){r.fail("Compile error");let s=n instanceof Error?n.message:String(n);return process.stderr.write(V(" "+s)+`
|
|
1832
|
-
`),{success:!1,durationMs:0,command:"",stdout:"",stderr:s,exitCode:-1}}}function
|
|
1833
|
+
`),{success:!1,durationMs:0,command:"",stdout:"",stderr:s,exitCode:-1}}}function Ns(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(2)}s`}function pb(e,t){return e.split(`
|
|
1833
1834
|
`).map((r)=>t+r).join(`
|
|
1834
|
-
`)}var
|
|
1835
|
-
`),process.exit(0);if(T(e,"help")||T(e,"h"))e.command="help";let r=e.command??"help";if(
|
|
1835
|
+
`)}var fp="dev-alice",gp="undeployed";var wp=E(()=>{Yu();Qu();tp();np();op();lp();pp();ps();mn();ue();Je()});ue();js();We();Ar();ke();eo();ro();var yp=new Set(["airdrop","transfer","dust","balance","serve","test","contract","dev"]);if(process.argv.includes("--mcp"))await _r(),await Promise.resolve().then(() => (Nu(),{}));else{let o=function(){n.abort(),setTimeout(()=>process.exit(130),5000).unref()},e=Hi(),t=T(e,"json");if(T(e,"version")||T(e,"v"))process.stdout.write(Be+`
|
|
1836
|
+
`),process.exit(0);if(T(e,"help")||T(e,"h"))e.command="help";let r=e.command??"help";if(yp.has(r))await _r();Ra();let n=new AbortController,{signal:s}=n;process.on("SIGINT",o),process.on("SIGTERM",o);async function i(){if(r!=="help")pn();switch(r){case"help":{await Promise.resolve().then(() => Pi());return _i(e)}case"manual":{await Promise.resolve().then(() => Wu());return Mi(e)}case"wallet":{await Promise.resolve().then(() => Yn());return nr(e)}case"generate":{process.stderr.write(`
|
|
1836
1837
|
Note: "midnight generate" is deprecated.
|
|
1837
1838
|
Use "midnight wallet generate <name>" instead.
|
|
1838
1839
|
|
|
1839
|
-
`);await Promise.resolve().then(() =>
|
|
1840
|
-
Run "midnight help" to see available commands.`)}}i().then(()=>{if(
|
|
1841
|
-
`+
|
|
1840
|
+
`);await Promise.resolve().then(() => no());return gn(e)}case"info":{await Promise.resolve().then(() => so());return hn(e)}case"balance":{await Promise.resolve().then(() => Po());return Fn(e)}case"address":{await Promise.resolve().then(() => Oo());return Ln(e)}case"genesis-address":{await Promise.resolve().then(() => Mo());return Un(e)}case"inspect-cost":{await Promise.resolve().then(() => Fo());return jn(e)}case"config":{await Promise.resolve().then(() => jo());return Kn(e)}case"cache":{await Promise.resolve().then(() => Uo());return Gn(e)}case"airdrop":{await Promise.resolve().then(() => Wn());return Qt(e,s)}case"transfer":{await Promise.resolve().then(() => Lo());return Bn(e,s)}case"dust":{await Promise.resolve().then(() => Hn());return er(e,s)}case"localnet":{await Promise.resolve().then(() => Jo());return Xn(e)}case"status":throw Error('The "status" command is currently being reworked. Check back soon.');case"serve":{await Promise.resolve().then(() => Bu());return ji(e,s)}case"test":{await Promise.resolve().then(() => xi());return Es(e,s)}case"contract":{await Promise.resolve().then(() => Ss());return ar(e,s)}case"dev":{await Promise.resolve().then(() => wp());return Bi(e,s)}default:throw new Y(`Unknown command: "${r}"
|
|
1841
|
+
Run "midnight help" to see available commands.`)}}i().then(()=>{if(yp.has(r))process.exit(0)}).catch((a)=>{let c=ua(a.message);if(pa(a)){if(t)Bs(a,"INVALID_ARGS",Us);else process.stderr.write(`
|
|
1842
|
+
`+la(c,'Run "midnight manual" for the full reference, or "midnight help <command>" for one command.')+`
|
|
1842
1843
|
|
|
1843
|
-
`);process.exit(
|
|
1844
|
-
`+
|
|
1844
|
+
`);process.exit(Us)}else if(t){let{exitCode:d,errorCode:l}=vr(a);Bs(a,l,d),process.exit(d)}else{process.stderr.write(`
|
|
1845
|
+
`+da(c,'Run "midnight help" for usage information.')+`
|
|
1845
1846
|
|
|
1846
1847
|
`);let{exitCode:d}=vr(a);process.exit(d)}})}
|