midnight-wallet-cli 0.5.2 → 0.6.0-rc.1
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 +36 -24
- package/dist/mcp-server.js +497 -493
- package/dist/wallet.js +566 -531
- package/docs/SKILL-CORE.md +45 -0
- package/docs/SKILL.md +21 -11
- package/package.json +16 -26
package/dist/wallet.js
CHANGED
|
@@ -1,77 +1,82 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as nm}from"node:module";var em=Object.defineProperty;var tm=(e)=>e;function rm(e,t){this[e]=tm.bind(null,t)}var be=(e,t)=>{for(var r in t)em(e,r,{get:t[r],enumerable:!0,configurable:!0,set:rm.bind(t,r)})};var T=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var ia=nm(import.meta.url);function aa(e){let t=e??process.argv.slice(2),r=[],n={},s=0;while(s<t.length){let o=t[s];if(o.startsWith("--")){let i=o.slice(2),a=t[s+1];if(a!==void 0&&!a.startsWith("-"))n[i]=a,s+=2;else n[i]=!0,s+=1}else if(o.startsWith("-")&&o.length===2){let i=o.slice(1),a=t[s+1];if(a!==void 0&&!a.startsWith("-"))n[i]=a,s+=2;else n[i]=!0,s+=1}else r.push(o),s+=1}return{command:r[0],subcommand:r[1],positionals:r.slice(2),flags:n}}function A(e,t){let r=e.flags[t];if(r===void 0||r===!0)return;return r}function R(e,t){return t in e.flags}function We(e){return R(e,"verbose")}function vt(e){return R(e,kn)&&!R(e,_r)}function kt(e){if(R(e,"no-cache"))throw Error(`--no-cache is not supported on write commands (transfer, airdrop, dust register, serve).
|
|
3
3
|
`+`Writes always use the cache — the SDK's fresh-sync is too slow on hosted networks.
|
|
4
|
-
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function
|
|
5
|
-
`);for(let
|
|
6
|
-
`)}function
|
|
7
|
-
`).map((o
|
|
8
|
-
`)
|
|
9
|
-
`)
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
4
|
+
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function Cn(e,t,r){let n=A(e,t);if(n===void 0)throw Error(`Missing required flag: --${t} <${r}>`);return n}var kn="_minimal",_r="_full";function Ot(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 mt="0000000000000000000000000000000000000000000000000000000000000001",Pr="0000000000000000000000000000000000000000000000000000000000000000",Dr="/api/v4/graphql",Ct="/api/v4/graphql/ws",zs=6,Xs=1e6,ca=300000000000000n,da=5,Or=800000000000000n,la=5000000000n,ua=8267n,pa=10800n,ma=300000,Ys=30000,fa=1e4,Zs=120000,xn=300000,Qs=60000,ga=16384,ha=0.7,wa=512,En=10,ya=3,Sa=600000,eo=15000,ba=115,ie=".midnight",An="wallet.json",va="config.json",Te=448,Ne=384,ka="localnet",to=2,Be="cache",Yt="wallets",Mr="default",Fr=10,ro=3000,Ca=120000,Mt=9932,Tn="https://midnight-comp-tracker.vercel.app";function xt(){return!("NO_COLOR"in process.env)}function Zt(e,t){if(!xt())return e;return`\x1B[38;5;${t}m${e}\x1B[0m`}function k(e){if(!xt())return e;return`\x1B[1m${e}\x1B[0m`}function l(e){if(!xt())return e;return`\x1B[2m${e}\x1B[0m`}function L(e){return Zt(e,38)}function J(e){return Zt(e,196)}function B(e){return Zt(e,40)}function D(e){return Zt(e,226)}function Ye(e){return Zt(e,15)}function ft(e){return Zt(e,245)}function j(e,t=Ea){let r=` ${e} `,n=t-r.length;if(n<=0)return k(r);let s=Math.floor(n/2),o=n-s;return k("═".repeat(s)+r+"═".repeat(o))}function V(e=Ea){return l("─".repeat(e))}function C(e,t,r=16){let n=(e+":").padEnd(r);return` ${ft(n)}${t}`}function Ft(e){let t=e<0n,r=t?-e:e,n=BigInt(10**zs),s=r/n,i=(r%n).toString().padStart(zs,"0");return`${t?"-":""}${s}.${i}`}function Nn(e){return`${Ft(e)} NIGHT`}function Me(e){let t=e<0n,r=t?-e:e,n=10n**BigInt(xa),s=r/n,a=(r%n).toString().padStart(xa,"0").replace(/0+$/,"").padEnd(6,"0");return`${t?"-":""}${s}.${a}`}function Lr(e){return`${Me(e)} DUST`}function re(e,t=!1){let r=t&&e.length>20?e.slice(0,10)+"…"+e.slice(-8):e;return L(r)}function sm(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 om(e,t){if(Qt(e).length<=t)return[e];let n=e.split(/(\s+)/).flatMap((a)=>Qt(a).length>t?sm(a,t):[a]),s=[],o="",i=0;for(let a of n){let c=Qt(a).length;if(i+c>t&&i>0)s.push(o),o=a.trimStart(),i=Qt(o).length;else o+=a,i+=c}if(o.length>0)s.push(o);return s}function Aa(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 u of e){let g=u.split(`
|
|
5
|
+
`);for(let m of g)o.push(...om(m,s))}let i=Math.max(...o.map((u)=>Qt(u).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,p=o.map((u)=>{let g=Qt(u).length,m=a-g-2;return`${n.v} ${u}${" ".repeat(Math.max(0,m))} ${n.v}`});return[c,...p,d].join(`
|
|
6
|
+
`)}function Ta(e,t){let n=e.split(`
|
|
7
|
+
`).map((s,o)=>o===0?J(k("Error: "))+J(s):J(s));if(t)n.push(""),n.push(l("Suggestion: ")+t);return n.join(`
|
|
8
|
+
`)}function Na(e,t){let s=e.replace(/^Usage:\s*/i,"").split(`
|
|
9
|
+
`).map((o,i)=>i===0?D(k("Usage: "))+D(o):D(o));if(t)s.push(""),s.push(l("Hint: ")+t);return s.join(`
|
|
10
|
+
`)}function Et(e,t){let n=[`${B("✓")} ${e}`];if(t)n.push(C("Transaction",L(t)));return n.join(`
|
|
11
|
+
`)}var Ea=60,xa=15,Qt=(e)=>e.replace(/\x1b\[[0-9;]*m/g,"");var ue=()=>{};function Ra(e){return e instanceof H}var H;var Fe=T(()=>{H=class H extends Error{constructor(e){super(e);this.name="UsageError",Object.setPrototypeOf(this,H.prototype)}}});function Ur(e){let t=e.code;if(typeof t==="string"&&dm.has(t))return{exitCode:4,errorCode:t};let r=(e.message??"").toLowerCase();if(r.includes("operation cancelled")||r.includes("operation aborted")||r==="cancelled"||r==="aborted")return{exitCode:7,errorCode:he.CANCELLED};if(r.includes("wallet file not found")||r.includes("wallet")&&r.includes("not found"))return{exitCode:3,errorCode:he.WALLET_NOT_FOUND};if(r.includes("missing required flag")||r.includes("missing amount")||r.includes("missing recipient")||r.includes("missing config key")||r.includes("missing or invalid subcommand")||r.includes("unknown command")||r.includes("cannot specify both")||r.includes("invalid bip-39")||r.includes("seed must be")||r.includes("key index must be")||r.includes("shielded balances are private")||r.includes("shielded is unavailable")||r.includes("belongs to")&&r.includes("--network is")||r.includes("usage:"))return{exitCode:2,errorCode:he.INVALID_ARGS};if(r.includes("proof")&&r.includes("timeout"))return{exitCode:6,errorCode:he.PROOF_TIMEOUT};if(r.includes("stale utxo")||r.includes("error code 115")||r.includes("errorcode: 115"))return{exitCode:6,errorCode:he.STALE_UTXO};if(r.includes("error 170")||r.includes("errorcode: 170")||r.includes("invaliddustspendproof"))return{exitCode:6,errorCode:he.INVALID_DUST_PROOF};if(r.includes("stale cache")||r.includes("chain reset")||r.includes("chainid mismatch")||r.includes("applied > highest"))return{exitCode:6,errorCode:he.STALE_CACHE};if(r.includes("failed to prove"))return{exitCode:6,errorCode:he.PROOF_FAILURE};if(r.includes("wallet sync timed out")||r.includes("sync timed out")||r.includes("timed out waiting for dust")||r.includes("did not respond within")||r.includes("did not produce a block")||r.includes("did not report funds"))return{exitCode:4,errorCode:he.SYNC_TIMEOUT};if(r.includes("no dust")||r.includes("dust")&&(r.includes("required")||r.includes("available")||r.includes("insufficient")))return{exitCode:5,errorCode:he.DUST_REQUIRED};if(r.includes("insufficient")||r.includes("not enough"))return{exitCode:5,errorCode:he.INSUFFICIENT_BALANCE};if(r.includes("rejected")||r.includes("transaction failed"))return{exitCode:6,errorCode:he.TX_REJECTED};if(r.includes("econnrefused")||r.includes("enotfound")||r.includes("etimedout")||r.includes("websocket")||r.includes("connection refused")||r.includes("request to ")&&r.includes(" failed, reason:")||r.includes("network")&&r.includes("error"))return{exitCode:4,errorCode:he.NETWORK_ERROR};return{exitCode:1,errorCode:he.UNKNOWN}}function Ia(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 no=2,he,dm;var so=T(()=>{he={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_LEDGER:"UNSUPPORTED_LEDGER",LOCALNET_UNAVAILABLE:"LOCALNET_UNAVAILABLE",LOCAL_STACK_UNREACHABLE:"LOCAL_STACK_UNREACHABLE",AMBIGUOUS_LOCAL_STACKS:"AMBIGUOUS_LOCAL_STACKS",UNKNOWN:"UNKNOWN"},dm=new Set([he.UNSUPPORTED_LEDGER,he.LOCALNET_UNAVAILABLE,he.LOCAL_STACK_UNREACHABLE,he.AMBIGUOUS_LOCAL_STACKS])});function oo(e){jr=e}function _(e){let t=JSON.stringify(e)+`
|
|
12
|
+
`;if(jr)jr(t);else process.stdout.write(t)}function io(e,t,r){let n=JSON.stringify({error:!0,code:t,message:e.message,exitCode:r})+`
|
|
13
|
+
`;if(jr)jr(n);else process.stdout.write(n)}var jr=null;var Rn;var _a=T(()=>{Rn={name:"midnight-wallet-cli",version:"0.6.0-rc.1",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","docs/SKILL-CORE.md","NOTICE"],engines:{node:">=20",bun:">=1.3.0"},scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",link:"bun link",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/compact-runtime":"0.20.0","@midnight-ntwrk/ledger-v8":"^8.1.0","@midnight-ntwrk/midnight-js-contracts":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-http-client-proof-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-indexer-public-data-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-level-private-state-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-network-id":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-node-zk-config-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-protocol":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-types":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-utils":"5.0.0-rc.1","@midnightntwrk/dapp-connector-api":"4.1.0-beta.1","@midnightntwrk/ledger-v9":"1.0.0-rc.5","@midnightntwrk/onchain-runtime-v4":"4.0.0-rc.3","@midnightntwrk/wallet-sdk":"2.0.0-rc.0","@modelcontextprotocol/sdk":"^1.27.1","@scure/bip39":"^2.0.1",rxjs:"^7.8.1",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"}}});var Wr,Ze,Pa;var Br=T(()=>{_a();Wr=Rn.name,Ze=Rn.version,Pa=Rn.description});import{execSync as um}from"child_process";import{ProtocolVersion as pm}from"@midnightntwrk/wallet-sdk";function Le(e){return Da.includes(e)}function Hr(e){return{...mm[e]}}function Gr(){return Da}function fm(e){let t={node:new Set,indexer:new Set,proofServer:new Set};for(let n of e.split(`
|
|
14
|
+
`)){if(!n)continue;let[s="",o=""]=n.split("|"),i=(a)=>[...o.matchAll(new RegExp(`:(\\d+)->${a}/tcp`,"g"))].map((c)=>parseInt(c[1],10));if(s.includes("indexer"))i(8088).forEach((a)=>t.indexer.add(a));if(s.includes("midnight-node"))i(9944).forEach((a)=>t.node.add(a));if(s.includes("proof-server"))i(6300).forEach((a)=>t.proofServer.add(a))}let r=(n)=>[...n].sort((s,o)=>s-o);return{node:r(t.node),indexer:r(t.indexer),proofServer:r(t.proofServer)}}function hm(e,t=gm){if(t.node&&e.node.length>1||t.indexer&&e.indexer.length>1||t.proofServer&&e.proofServer.length>1)throw new Oa(e);return{nodePort:t.node?e.node[0]:void 0,indexerPort:t.indexer?e.indexer[0]:void 0,proofServerPort:t.proofServer?e.proofServer[0]:void 0}}function wm(){if(process.env.MN_NO_LOCAL_DETECT==="1")return{node:[],indexer:[],proofServer:[]};try{return fm(um('docker ps --format "{{.Image}}|{{.Ports}}"',{encoding:"utf-8",timeout:5000}))}catch{return{node:[],indexer:[],proofServer:[]}}}function Ma(e,t={}){let r=Hr(e),n=t.given??{},s={node:n.node===void 0,indexer:n.indexerWS===void 0,proofServer:n.proofServer===void 0};if(e==="undeployed"&&(s.node||s.indexer||s.proofServer)){let o=hm((t.detect??wm)(),s);if(o.indexerPort)r.indexer=`http://localhost:${o.indexerPort}${Dr}`,r.indexerWS=`ws://localhost:${o.indexerPort}${Ct}`;if(o.nodePort)r.node=`ws://localhost:${o.nodePort}`;if(o.proofServerPort)r.proofServer=`http://localhost:${o.proofServerPort}`}if(n.node!==void 0)r.node=n.node;if(n.proofServer!==void 0)r.proofServer=n.proofServer;if(n.indexerWS!==void 0)r.indexerWS=n.indexerWS,r.indexer=Fa(n.indexerWS);return r}function Fa(e){return e.replace(/^wss:/,"https:").replace(/^ws:/,"http:").replace(/\/ws$/,"")}function $n(e){let t={};if(e.node!==void 0)t.node=e.node;if(e.indexerWS!==void 0)t["indexer-ws"]=e.indexerWS;if(e.proofServer!==void 0)t["proof-server"]=e.proofServer;return t}function Re(e,t,r,n){let s=De(n),o=Kr(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"])e.indexer=Fa(e.indexerWS);return e}var gt,mm,Da,Oa,gm;var we=T(()=>{tr();gt=pm.V9NativeForkSchedule,mm={preprod:{indexer:`https://indexer.preprod.midnight.network${Dr}`,indexerWS:`wss://indexer.preprod.midnight.network${Ct}`,node:"wss://rpc.preprod.midnight.network",proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:`https://indexer.preview.midnight.network${Dr}`,indexerWS:`wss://indexer.preview.midnight.network${Ct}`,node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:`http://localhost:8088${Dr}`,indexerWS:`ws://localhost:8088${Ct}`,node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},Da=["preprod","preview","undeployed"];Oa=class Oa extends Error{code="AMBIGUOUS_LOCAL_STACKS";constructor(e){super(`Several local Midnight stacks are running (node ${e.node.join(", ")}; indexer ${e.indexer.join(", ")}; proof-server ${e.proofServer.join(", ")}), and mn won't guess which one to use.
|
|
15
|
+
Pick one per command: --node ws://localhost:<port> --indexer-ws ws://localhost:<port>${Ct} --proof-server http://localhost:<port>
|
|
16
|
+
or once: midnight config set network undeployed, then midnight config set node / indexer-ws / proof-server <url>
|
|
17
|
+
Commands without endpoint flags (cache, test, dev) use the saved config. MN_NO_LOCAL_DETECT=1 turns detection off.`);this.name="AmbiguousLocalStacksError"}};gm={node:!0,indexer:!0,proofServer:!0}});import*as ht from"fs";import*as ao from"path";import{homedir as ym}from"os";function co(e){return Sm[e]??e}function bm(e){return/^(https?|wss?):\/\/\S+/.test(e)}function La(e){return e??ao.join(ym(),ie)}function Ua(e){return ao.join(La(e),va)}function vm(e){let t=La(e);if(!ht.existsSync(t))ht.mkdirSync(t,{recursive:!0,mode:Te})}function De(e){let t=Ua(e);if(!ht.existsSync(t))return{...Jr};let r;try{r=ht.readFileSync(t,"utf-8")}catch{return{...Jr}}let n;try{n=JSON.parse(r)}catch{return{...Jr}}let s={network:n.network&&Le(n.network)?n.network:Jr.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(!Le(i)||!a||typeof a!=="object")continue;let c={};for(let d of Vr){let p=a[d];if(p&&typeof p==="string")c[d]=p}if(Object.keys(c).length>0)o[i]=c}if(Object.keys(o).length>0)s.networks=o}return s}function Kr(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 qr(e,t){vm(t);let r=Ua(t);ht.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
18
|
+
`,{mode:Ne})}function ja(e,t){let r=co(e),n=De(t);if(r==="network")return n.network;if(r==="wallet")return n.wallet??"(not set)";if(Vr.has(r)){let o=Kr(n,n.network)[r];return typeof o==="string"?o:"(not set)"}throw Error(`Unknown config key: "${e}"
|
|
19
|
+
Valid keys: ${In.join(", ")}`)}function km(e,t){let r={...e.networks?.[t]??{}},n=!1;for(let s of Vr){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 Wa(e,t,r){let n=co(e),s=De(r);if(n==="network"){if(!Le(t))throw Error(`Invalid network: "${t}"
|
|
20
|
+
Valid networks: preprod, preview, undeployed`);km(s,s.network),s.network=t}else if(n==="wallet"){if(!Ot(t))throw Error(`Invalid wallet name: "${t}"
|
|
21
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(Vr.has(n)){if(!bm(t))throw Error(`Invalid URL for "${e}": "${t}"
|
|
17
22
|
Must start with http://, https://, ws://, or wss://`);let o=n,i={...s.networks?.[s.network]??{}};i[o]=t,s.networks={...s.networks??{},[s.network]:i},delete s[o]}else throw Error(`Unknown config key: "${e}"
|
|
18
|
-
Valid keys: ${
|
|
19
|
-
Valid keys: ${
|
|
20
|
-
`,{mode:
|
|
21
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=
|
|
22
|
-
Run "midnight wallet list" to see available wallets.`);let r=
|
|
23
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t
|
|
24
|
-
Run "midnight wallet list" to see available wallets.`);let n=
|
|
23
|
+
Valid keys: ${In.join(", ")}`);qr(s,r)}function Ba(e,t){let r=co(e),n=De(t);if(r==="network")n.network=Jr.network;else if(r==="wallet")delete n.wallet;else if(Vr.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}"
|
|
24
|
+
Valid keys: ${In.join(", ")}`);qr(n,t)}function lo(){return In}var Jr,In,Sm,Vr;var tr=T(()=>{we();Jr={network:"undeployed"},In=["network","proof-server","node","indexer-ws","wallet"],Sm={"network-id":"network"};Vr=new Set(["proof-server","node","indexer-ws"])});import{HDWallet as Cm,Roles as uo}from"@midnightntwrk/wallet-sdk/hd";function po(e,t){let r=Cm.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 Lt(e){return po(e,uo.Zswap)}function Ha(e){return po(e,uo.NightExternal)}function At(e){return po(e,uo.Dust)}var Ut=()=>{};import{NetworkId as rr}from"@midnightntwrk/wallet-sdk";function He(e){let t=xm[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}function mo(e){return Em[e]}var xm,Em;var Tt=T(()=>{xm={PreProd:rr.NetworkId.PreProd,Preview:rr.NetworkId.Preview,Undeployed:rr.NetworkId.Undeployed},Em={preprod:rr.NetworkId.PreProd,preview:rr.NetworkId.Preview,undeployed:rr.NetworkId.Undeployed}});import{HDWallet as Am,Roles as Tm}from"@midnightntwrk/wallet-sdk/hd";import{createKeystore as Nm,PublicKey as Rm}from"@midnightntwrk/wallet-sdk/unshielded";import{MidnightBech32m as $m,ShieldedAddress as Im,ShieldedCoinPublicKey as _m,ShieldedEncryptionPublicKey as Pm}from"@midnightntwrk/wallet-sdk/address-format";import*as Ga from"@midnightntwrk/ledger-v9";function $e(e,t,r=0){let n=mo(t),s=Am.fromSeed(e);if(s.type!=="seedOk")throw Error("Invalid seed for HD wallet");let o=s.hdWallet.selectAccount(0).selectRole(Tm.NightExternal).deriveKeyAt(r);if(o.type==="keyOutOfBounds")throw Error(`Key index ${r} out of bounds`);let i=Nm({kind:"schnorr",secret:o.key},n);return Rm.fromKeyStore(i).address}function jt(e,t=0){let r={};for(let n of Gr())r[n]=$e(e,n,t);return r}function zr(e){let t=Xr(e),r={};for(let n of Gr()){let s=mo(n);r[n]=$m.encode(s,t).asString()}return r}function Xr(e){let t=Lt(e),r=Ga.ZswapSecretKeys.fromSeed(t);return new Im(new _m(Buffer.from(r.coinPublicKey,"hex")),new Pm(Buffer.from(r.encryptionPublicKey,"hex")))}var Qe=T(()=>{we();Ut();Tt()});import*as Z from"fs";import*as ve from"path";import{homedir as Dm}from"os";function nr(e,t,r){let n=ve.resolve(e);if(!Z.existsSync(n))return;try{let s=JSON.parse(Z.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;Z.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
25
|
+
`,{mode:Ne})}catch{}}function fo(){return ve.join(Dm(),ie)}function Wt(){return ve.join(fo(),Yt)}function go(){return ve.join(fo(),An)}function Ja(){let e=fo();if(!Z.existsSync(e))Z.mkdirSync(e,{recursive:!0,mode:Te})}function Om(){Ja();let e=Wt();if(!Z.existsSync(e))Z.mkdirSync(e,{recursive:!0,mode:Te})}function Mm(e){return e.includes("/")||e.includes("\\")||e.endsWith(".json")}function se(e){if(e!==void 0){if(Mm(e))return ve.resolve(e);return ve.join(Wt(),`${e}.json`)}let r=De().wallet??Mr;return ve.join(Wt(),`${r}.json`)}function Nt(){return De().wallet??Mr}function Yr(e){if(!Ot(e))throw Error(`Invalid wallet name: "${e}"
|
|
26
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=ve.join(Wt(),`${e}.json`);if(!Z.existsSync(t))throw Error(`Wallet "${e}" not found.
|
|
27
|
+
Run "midnight wallet list" to see available wallets.`);let r=De();r.wallet=e,qr(r)}function ho(){let e=Wt();if(!Z.existsSync(e))return[];let t=Nt();return Z.readdirSync(e).filter((n)=>n.endsWith(".json")).sort().map((n)=>{let s=n.replace(/\.json$/,""),o=ve.join(e,n);try{let i=JSON.parse(Z.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=jt(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=zr(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 Fm(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 Va(e){return Fm(ho(),e)}function qa(e){if(!Ot(e))throw Error(`Invalid wallet name: "${e}"
|
|
28
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=Wt(),r=ve.join(t,`${e}.json`);if(!Z.existsSync(r))throw Error(`Wallet "${e}" not found.
|
|
29
|
+
Run "midnight wallet list" to see available wallets.`);let n=Nt();if(e===n)throw Error(`Cannot remove the active wallet "${e}".
|
|
25
30
|
Switch to another wallet first: midnight wallet use <other-wallet>`);if(Z.readdirSync(t).filter((o)=>o.endsWith(".json")).length<=1)throw Error(`Cannot remove "${e}" — it is the only wallet.
|
|
26
|
-
`+"Create another wallet first: midnight wallet generate <name>");Z.unlinkSync(r)}function
|
|
31
|
+
`+"Create another wallet first: midnight wallet generate <name>");Z.unlinkSync(r)}function za(){let e=go();if(!Z.existsSync(e))return;let t=Wt();if(Z.existsSync(t)){if(Z.readdirSync(t).filter((o)=>o.endsWith(".json")).length>0)return}Om();let r=ve.join(t,`${Mr}.json`);Z.copyFileSync(e,r),Z.chmodSync(r,Ne),Z.unlinkSync(e);let n=De();n.wallet=Mr,qr(n)}function ae(e){let t=e?ve.resolve(e):go();if(!Z.existsSync(t))throw Error(`Wallet file not found: ${t}
|
|
27
32
|
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=Z.readFileSync(t,"utf-8")}catch(c){throw Error(`Failed to read wallet file: ${t}
|
|
28
|
-
${c.message}`)}let n;try{n=JSON.parse(r)}catch{throw Error(`Invalid JSON in wallet file: ${t}`)}if(!n.seed||!n.createdAt){let c=["seed","createdAt"];if(!n.addresses)c.push("address");let d=c.filter((
|
|
29
|
-
`,{mode:
|
|
30
|
-
`,{mode:
|
|
31
|
-
`,{mode:
|
|
33
|
+
${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((p)=>!n[p]);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=jt(c),p={seed:n.seed,addresses:d,createdAt:n.createdAt};if(n.mnemonic)p.mnemonic=n.mnemonic;let u=Ka(n,c);if(u)p.shieldedAddresses=u;let g={...n,addresses:d};if(u)g.shieldedAddresses=u,delete g.shieldedAddress;return Z.writeFileSync(t,JSON.stringify(g,null,2)+`
|
|
34
|
+
`,{mode:Ne}),p}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=Ka(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,Z.writeFileSync(t,JSON.stringify(c,null,2)+`
|
|
35
|
+
`,{mode:Ne})}catch{}return s}function Ka(e,t){let r;try{r=zr(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 _n(e,t){let r=t?ve.resolve(t):go();if(!t)Ja();else{let n=ve.dirname(r);if(!Z.existsSync(n))Z.mkdirSync(n,{recursive:!0,mode:Te})}return Z.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
36
|
+
`,{mode:Ne}),r}var Ie=T(()=>{tr();Qe()});import Lm from"node:v8";import Um from"node:os";import{spawn as jm}from"node:child_process";function Bm(e){let t=e.desiredMb??ga,r=e.ramFraction??ha,n=e.minGainMb??wa;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 Zr(){if(process.env[wo]){Gm();return}let e=process.env[Wm],t=e!==void 0?Number(e):void 0,r=Bm({totalMb:Math.floor(Um.totalmem()/Xa),currentLimitMb:Math.floor(Lm.getHeapStatistics().heap_size_limit/Xa),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=jm(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[wo]:"1"}});Hm(s),s.on("error",()=>{process.env[wo]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function Hm(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 Gm(){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 wo="MN_HEAP_BUMPED",Wm="MN_MAX_OLD_SPACE_MB",Xa=1048576;var yo=()=>{};async function q(e,t,r){let n=[];oo((s)=>n.push(s));try{if(t.flags.json=!0,!(kn in t.flags))t.flags[kn]=!0;await e(t,r);let s=n.join("").trim();if(!s)return{};return JSON.parse(s)}finally{oo(null)}}var Pn=()=>{};function Ya(e){let t=e.split(`
|
|
32
37
|
|
|
33
38
|
`)[0].trim(),r=t.split(`
|
|
34
39
|
`),n=[];for(let s of r){if(/(?:^|\s)(midnight|mn)\s+[a-z]/i.test(s))break;if(/^(Try|Run|See|Open):\s/i.test(s.trim()))break;n.push(s)}return n.join(`
|
|
35
|
-
`).trim()||t}import{randomUUID as
|
|
36
|
-
Valid networks: ${
|
|
37
|
-
|
|
40
|
+
`).trim()||t}import{randomUUID as Km}from"node:crypto";function Za(e={}){let t=e.ttlMs??Jm,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=Km(),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 Jm=300000;var Qa=()=>{};function ke(e){let t=A(e.args,"network");if(t!==void 0){if(!Le(t))throw Error(`Invalid network: "${t}"
|
|
41
|
+
Valid networks: ${Gr().join(", ")}`);return t}let r=De(e.configDir);if(r.network&&Le(r.network))return r.network;return"undeployed"}function de(e){let t=ke(e),r=Kr(De(e.configDir),t),n={node:A(e.args,"node")??r.node,indexerWS:A(e.args,"indexer-ws")??r["indexer-ws"],proofServer:A(e.args,"proof-server")??r["proof-server"]},s=Ma(t,{given:n});return{name:t,config:s}}var Ce=T(()=>{we();tr()});function Qr(e,t){let r=e.trim().replace(/^0x/,"");if(r.length!==64&&r.length!==128||!/^[0-9a-fA-F]+$/.test(r))throw new H(`${t} must be 64 or 128 hex characters (a 32-byte seed, or a 64-byte BIP-39 seed)`);return Buffer.from(r,"hex")}function So(e,t={}){let r=A(e,"seed"),n=r??process.env.MN_SEED;if(n)return{seed:Qr(n,r?"--seed":"MN_SEED"),walletPath:null,config:null};let s=A(e,"wallet");if(s===void 0&&t.requireExplicit)throw new H(`${t.label??"This command"} needs a seed source. Provide one of:
|
|
42
|
+
--seed <hex> seed as 64 hex chars (32-byte) or 128 (64-byte BIP-39)
|
|
43
|
+
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
44
|
+
--wallet <name> derive from a saved wallet`);let o=se(s),i=ae(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function Dn(e,t){return So(e,t).seed}var sr=T(()=>{Fe();Ie()});var nc={};be(nc,{default:()=>Mn});import*as rc from"fs";import*as On from"path";import{homedir as Vm}from"os";import{generateMnemonic as qm,mnemonicToSeedSync as ec,validateMnemonic as zm}from"@scure/bip39";import{wordlist as tc}from"@scure/bip39/wordlists/english.js";async function Mn(e){let t=ke({args:e}),r=A(e,"output"),n=A(e,"seed"),s=process.env.MN_SEED?.trim(),o=n??(s?s:void 0),i=A(e,"mnemonic");if(o!==void 0&&i!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let a=r?On.resolve(r):On.join(Vm(),ie,An);if(rc.existsSync(a)&&!R(e,"force"))throw Error(`Wallet file already exists: ${a}
|
|
45
|
+
Use --force to overwrite, or --output <file> to save to a different path.`);let c,d;if(o!==void 0)c=Qr(o,n!==void 0?"--seed":"MN_SEED");else if(i!==void 0){if(!zm(i,tc))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");d=i,c=Buffer.from(ec(d))}else d=qm(tc,256),c=Buffer.from(ec(d));let p=jt(c),u=p[t],g={seed:c.toString("hex"),addresses:p,createdAt:new Date().toISOString()};if(d)g.mnemonic=d;let m=_n(g,r);if(R(e,"json")){let h={addresses:p,activeAddress:u,activeNetwork:t,seed:c.toString("hex"),file:m,createdAt:g.createdAt};if(d)h.mnemonic=d;_(h);return}if(process.stdout.write(u+`
|
|
38
46
|
`),process.stderr.write(`
|
|
39
|
-
`+
|
|
47
|
+
`+j("Wallet Generated")+`
|
|
40
48
|
|
|
41
49
|
`),process.stderr.write(C("Network",t)+`
|
|
42
|
-
`),process.stderr.write(C("Address",re(
|
|
43
|
-
`),process.stderr.write(C("File",
|
|
50
|
+
`),process.stderr.write(C("Address",re(u))+`
|
|
51
|
+
`),process.stderr.write(C("File",m)+`
|
|
44
52
|
`),process.stderr.write(`
|
|
45
|
-
`),d)process.stderr.write(
|
|
53
|
+
`),d)process.stderr.write(D(k(" MNEMONIC (save securely!):"))+`
|
|
46
54
|
`),process.stderr.write(` ${d}
|
|
47
55
|
|
|
48
|
-
`);process.stderr.write(
|
|
56
|
+
`);process.stderr.write(D(k(" SEED (hex):"))+`
|
|
49
57
|
`),process.stderr.write(` ${c.toString("hex")}
|
|
50
58
|
|
|
51
|
-
`),process.stderr.write(
|
|
59
|
+
`),process.stderr.write(V()+`
|
|
52
60
|
`),process.stderr.write(l(" Next: midnight info | midnight balance")+`
|
|
53
61
|
|
|
54
|
-
`),process.stderr.write(
|
|
55
|
-
`)}var
|
|
62
|
+
`),process.stderr.write(B("✓")+` Wallet saved
|
|
63
|
+
`)}var bo=T(()=>{Qe();Ce();Ie();sr();ue()});var sc={};be(sc,{default:()=>Fn});async function Fn(e){let t=se(A(e,"wallet")),r=ae(t),n=ke({args:e}),s=r.addresses[n];if(R(e,"json")){let i={addresses:r.addresses,activeNetwork:n,activeAddress:s,createdAt:r.createdAt,file:t};if(r.shieldedAddresses)i.shieldedAddresses=r.shieldedAddresses;_(i);return}process.stdout.write(s+`
|
|
56
64
|
`),process.stderr.write(`
|
|
57
|
-
`+
|
|
65
|
+
`+j("Wallet Info")+`
|
|
58
66
|
|
|
59
|
-
`);let o=Object.keys(r.addresses);for(let i=0;i<o.length;i++){let a=o[i],c=a===n,d=r.addresses[a],
|
|
67
|
+
`);let o=Object.keys(r.addresses);for(let i=0;i<o.length;i++){let a=o[i],c=a===n,d=r.addresses[a],p=r.shieldedAddresses?.[a],u=c?k(L(a))+l(" (active)"):a;if(process.stderr.write(` ${u}
|
|
60
68
|
`),process.stderr.write(` ${l("unshielded")} ${re(d)}
|
|
61
|
-
`),
|
|
69
|
+
`),p)process.stderr.write(` ${l("shielded ")} ${re(p)}
|
|
62
70
|
`);else process.stderr.write(` ${l("shielded ")} ${l("(unavailable)")}
|
|
63
71
|
`);if(i<o.length-1)process.stderr.write(`
|
|
64
72
|
`)}process.stderr.write(`
|
|
65
|
-
`+
|
|
73
|
+
`+V()+`
|
|
66
74
|
|
|
67
75
|
`),process.stderr.write(` ${l("created")} ${r.createdAt}
|
|
68
76
|
`),process.stderr.write(` ${l("file ")} ${t}
|
|
69
77
|
|
|
70
|
-
`)}var
|
|
71
|
-
`)}var
|
|
72
|
-
--seed <hex> 32-byte seed as 64 hex characters
|
|
73
|
-
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
74
|
-
--wallet <name> derive from a saved wallet`);let o=ae(s),i=ce(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function En(e,t){return bo(e,t).seed}var xn=x(()=>{He();ve()});function um(e){return!lm.includes(e)}function tr(e,t=!1){return um(e)||t}function Tn(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var lm;var Nn=x(()=>{lm=["preview","preprod"]});import{NetworkId as vo}from"@midnight-ntwrk/wallet-sdk-abstractions";function _t(e){let t=pm[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}var pm;var Rn=x(()=>{pm={PreProd:vo.NetworkId.PreProd,Preview:vo.NetworkId.Preview,Undeployed:vo.NetworkId.Undeployed}});import mm from"ws";function rr(e,t,r){return new Promise((n,s)=>{let o=new mm(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,u=!1,p=!1,f,g=()=>{let w=new Map,y=0,S=0,b=0;for(let v of i.values())if(!v.spent){y++;let R=w.get(v.tokenType)??0n;if(w.set(v.tokenType,R+v.value),v.tokenType===rn)if(v.registeredForDustGeneration)S++;else b++}return{balances:w,utxoCount:y,txCount:a,highestTxId:c,registeredUtxos:S,unregisteredUtxos:b}},h=()=>{clearTimeout(f)},m=()=>{if(!p&&u&&(c===0||d>=c))p=!0,h(),o.send(JSON.stringify({id:"1",type:"complete"})),o.close(),n(g())};o.on("open",()=>{o.send(JSON.stringify({type:"connection_init"}))}),o.on("message",(w)=>{let y=JSON.parse(w.toString());switch(y.type){case"connection_ack":o.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:fm,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}`,D=i.get(R);if(D)D.spent=!0}if(r)r(d,c);m()}else if(S.__typename==="UnshieldedTransactionsProgress")c=S.highestTransactionId,u=!0,m();break}case"error":if(!p)p=!0,h(),o.close(),s(Error(`GraphQL subscription error: ${JSON.stringify(y.payload)}`));break;case"complete":break}}),o.on("error",(w)=>{if(!p){p=!0,h();let y=w.message?.trim()?w.message:`unable to reach ${t} (connection refused, DNS, or TLS error). Is the indexer running?`;s(Error(`WebSocket connection failed: ${y}`))}}),o.on("close",()=>{if(!p)p=!0,h(),s(Error(`Indexer closed the connection before balance sync completed. Indexer: ${t}`))}),f=setTimeout(()=>{if(!p)p=!0,o.close(),s(Error(`Balance check timed out after ${cn/1000}s. Indexer: ${t}`))},cn)})}function _r(e){return e===rn}var fm=`
|
|
78
|
+
`)}var vo=T(()=>{Ie();Ce();ue();ue()});function Ge(){oc=!0}function W(e,t){if(!oc)return;let r=new Date().toISOString().slice(11,23);process.stderr.write(l(` [${r}] ${e}: ${t}`)+`
|
|
79
|
+
`)}var oc=!1;var wt=()=>{};function Ym(e){return!Xm.includes(e)}function or(e,t=!1){return Ym(e)||t}function Ln(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var Xm;var Un=T(()=>{Xm=["preview","preprod"]});import Zm from"ws";function ir(e,t,r){return new Promise((n,s)=>{let o=new Zm(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,p=!1,u=!1,g,m=()=>{let y=new Map,S=0,w=0,b=0;for(let x of i.values())if(!x.spent){S++;let I=y.get(x.tokenType)??0n;if(y.set(x.tokenType,I+x.value),x.tokenType===Pr)if(x.registeredForDustGeneration)w++;else b++}return{balances:y,utxoCount:S,txCount:a,highestTxId:c,registeredUtxos:w,unregisteredUtxos:b}},h=()=>{clearTimeout(g)},f=()=>{if(!u&&p&&(c===0||d>=c))u=!0,h(),o.send(JSON.stringify({id:"1",type:"complete"})),o.close(),n(m())};o.on("open",()=>{o.send(JSON.stringify({type:"connection_init"}))}),o.on("message",(y)=>{let S=JSON.parse(y.toString());switch(S.type){case"connection_ack":o.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:Qm,variables:{address:e}}}));break;case"next":{if(S.payload?.errors){let b=S.payload.errors[0]?.message||"Unknown GraphQL error";if(!u)u=!0,h(),o.close(),s(Error(`GraphQL error: ${b}`));return}let w=S.payload?.data?.unshieldedTransactions;if(!w)return;if(w.__typename==="UnshieldedTransaction"){a++;let b=w;d=Math.max(d,b.transaction.id);for(let x of b.createdUtxos){let I=`${x.intentHash}:${x.outputIndex}`;i.set(I,{value:BigInt(x.value),tokenType:x.tokenType,spent:!1,registeredForDustGeneration:x.registeredForDustGeneration===!0})}for(let x of b.spentUtxos){let I=`${x.intentHash}:${x.outputIndex}`,O=i.get(I);if(O)O.spent=!0}if(r)r(d,c);f()}else if(w.__typename==="UnshieldedTransactionsProgress")c=w.highestTransactionId,p=!0,f();break}case"error":if(!u)u=!0,h(),o.close(),s(Error(`GraphQL subscription error: ${JSON.stringify(S.payload)}`));break;case"complete":break}}),o.on("error",(y)=>{if(!u){u=!0,h();let S=y.message?.trim()?y.message:`unable to reach ${t} (connection refused, DNS, or TLS error). Is the indexer running?`;s(Error(`WebSocket connection failed: ${S}`))}}),o.on("close",()=>{if(!u)u=!0,h(),s(Error(`Indexer closed the connection before balance sync completed. Indexer: ${t}`))}),g=setTimeout(()=>{if(!u)u=!0,o.close(),s(Error(`Balance check timed out after ${Qs/1000}s. Indexer: ${t}`))},Qs)})}function en(e){return e===Pr}var Qm=`
|
|
75
80
|
subscription UnshieldedTransactions($address: UnshieldedAddress!) {
|
|
76
81
|
unshieldedTransactions(address: $address) {
|
|
77
82
|
__typename
|
|
@@ -85,10 +90,14 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
85
90
|
}
|
|
86
91
|
}
|
|
87
92
|
}
|
|
88
|
-
`;var
|
|
89
|
-
`),
|
|
93
|
+
`;var tn=()=>{};import{existsSync as rn,mkdirSync as ef,writeFileSync as tf,readFileSync as ic,unlinkSync as jn,readdirSync as ko,renameSync as rf}from"node:fs";import{join as Bt,dirname as nf}from"node:path";import{homedir as ac}from"node:os";import{randomBytes as sf}from"node:crypto";import*as Wn from"@midnightntwrk/ledger-v9";function Co(e){return e.toString(16).padStart(64,"0")}function ct(e){let t=At(e),r=Wn.DustSecretKey.fromSeed(t);return Co(r.publicKey)}function xo(e,t){let r=t??Bt(ac(),ie,Be);return Bt(r,e)}function Eo(e,t,r){let n=t.slice(0,20);return Bt(xo(e,r),`dust-${n}.json`)}function nn(e,t,r){let n=Eo(e,t,r);if(!rn(n))return null;try{let s=JSON.parse(ic(n,"utf-8"));if(s.version!==cc)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:Wn.DustLocalState.deserialize(o),lastAppliedEventId:s.lastAppliedEventId,retention:{ownedGenerationIndices:s.ownedGenerationIndices,generationFrontier:s.generationFrontier}}}catch{return null}}function Ao(e,t,r,n,s,o,i=of){let a={version:cc,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=Eo(e,t,s),d=nf(c);if(!rn(d))ef(d,{recursive:!0,mode:Te});let p=c+`.tmp.${sf(4).toString("hex")}`;try{tf(p,JSON.stringify(a),{mode:Ne}),rf(p,c)}catch(u){try{jn(p)}catch{}throw u}}function dc(e,t,r){if(!t)return[];let n=xo(e,r);if(!rn(n))return[];let s=[],o;try{o=ko(n)}catch{return[]}for(let i of o){if(!i.startsWith("dust-")||!i.endsWith(".json"))continue;let a=Bt(n,i);try{let c=JSON.parse(ic(a,"utf-8"));if(!c.chainId)continue;if(c.chainId!==t)jn(a),s.push(a)}catch{}}return s}function Rt(e,t,r){let n=r??Bt(ac(),ie,Be);if(e&&t){let o=Eo(e,t,r);try{jn(o)}catch{}return}let s=(o)=>{if(!rn(o))return;try{for(let i of ko(o))if(i.startsWith("dust-")&&i.endsWith(".json"))try{jn(Bt(o,i))}catch{}}catch{}};if(e){s(xo(e,r));return}if(!rn(n))return;try{for(let o of ko(n))s(Bt(n,o))}catch{}}var cc=3,of;var Ht=T(()=>{Ut();of={ownedGenerationIndices:[],generationFrontier:0}});import{ShieldedWallet as lc}from"@midnightntwrk/wallet-sdk/shielded";import{UnshieldedWallet as uc,createKeystore as af,PublicKey as cf}from"@midnightntwrk/wallet-sdk/unshielded";import{DustWallet as pc}from"@midnightntwrk/wallet-sdk/dust";import{WalletFacade as mc,WalletEntrySchema as df,mergeWalletEntries as lf}from"@midnightntwrk/wallet-sdk/facade";import*as fc from"@midnightntwrk/ledger-v9";import{InMemoryTransactionHistoryStorage as uf}from"@midnightntwrk/wallet-sdk";import*as Ue from"rxjs";async function dt(e,t,r){let n=He(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={shielded:Lt(e),unshielded:Ha(e),dust:At(e)},o=af({kind:"schnorr",secret:s.unshielded},n),i={networkId:n,forks:gt,indexerClientConnection:{indexerHttpUrl:t.indexer,indexerWsUrl:t.indexerWS},costParameters:{additionalFeeOverhead:ca,feeBlocksMargin:da},txHistoryStorage:new uf(df,lf),provingServerUrl:new URL(t.proofServer),relayURL:new URL(t.node)},a,c,d=()=>mc.init({configuration:i,shielded:async(h)=>a=await lc(h).startWithSeed(s.shielded),unshielded:(h)=>uc(h).startWithPublicKey(cf.fromKeyStore(o)),dust:async(h)=>c=await pc(h).startWithSeed(s.dust)}),p=fc.DustSecretKey.fromSeed(s.dust).publicKey,u=r?mf(r,t,p):null,g=!1,m;if(u){W("facade","Restoring from cache...");try{m=await mc.init({configuration:i,shielded:(h)=>a=lc(h).restore(u.shielded),unshielded:(h)=>uc(h).restore(u.unshielded),dust:(h)=>c=pc(h).restore(u.dust)}),g=!0,W("facade","Cache restore successful")}catch(h){W("facade",`Cache restore failed: ${h.message}`),process.stderr.write(` Cache restore failed, building from scratch: ${h.message}
|
|
94
|
+
`),m=await d()}}else W("facade","No cache, building fresh"),m=await d();if(!a||!c)throw Error("Wallet facade was built without its shielded or dust wallet");return{facade:m,keystore:o,seeds:s,seedStartable:{shielded:a,dust:c},restoredFromCache:g}}async function pf(e){let{facade:t,seeds:r,seedStartable:n}=e;if(!e.restoredFromCache){await t.start(r);return}await Promise.all([n.shielded.startWithSeed(r.shielded),t.unshielded.start(),n.dust.startWithSeed(r.dust),t.pendingTransactionsService.start()])}function No(e,t){let r=JSON.parse(e);if(BigInt(r.protocolVersion)<gt.v9)throw Error(`Can't put a ledger-9 dust state into a snapshot at protocol version ${r.protocolVersion}: the wallet would read it as ledger 8 (fork at ${gt.v9}).`);return r.state=Buffer.from(t.state.serialize()).toString("hex"),r.offset=t.lastAppliedEventId.toString(),JSON.stringify(r)}function mf(e,t,r){try{let n=t.networkId.toLowerCase(),s=Co(r),o=nn(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:No(e.dust,o)}}catch(n){return W("facade",`Dust-direct bridge skipped: ${n.message}`),e}}function gc(e,t){if(e.isStrictlyComplete())return!0;if(e.highestRelevantWalletIndex>0n&&e.appliedIndex>=e.highestRelevantWalletIndex)return!0;return hc(e)&&t}function hc(e){return e.highestRelevantWalletIndex===0n&&e.appliedIndex===0n}function To(e,t="full"){let r=e.unshielded.progress.isStrictlyComplete(),n=t==="no-dust"||gc(e.dust.progress,r);if(t==="lite")return r&&n;let s=e.shielded.progress;return(s.isStrictlyComplete()||r&&hc(s))&&r&&n}function ff(e){return!gc(e.dust.progress,e.unshielded.progress.isStrictlyComplete())}async function $t(e,t={}){let{onProgress:r,onSyncDetail:n,timeoutMs:s,syncMode:o="full",requireStrictSync:i=!1}=t,{facade:a}=e;W("sync","Starting facade (connecting to node and indexer)..."),await pf(e),W("sync","Facade started, subscribing to state...");let c=s??ma;W("sync",`Sync timeout: ${c/1000}s, mode: ${o}`);let d=!i&&e.restoredFromCache,p=Date.now();return new Promise((u,g)=>{let m=!1,h=0,f="",y=null,S=setTimeout(()=>{if(!m){if(W("sync",`Sync timed out after ${c/1000}s (${h} emissions)`),y)try{let w=y.unshielded.progress;W("sync",` unshielded: applied=${w.appliedId} highest=${w.highestTransactionId} complete=${w.isStrictlyComplete()}`);let b=y.dust.progress;if(W("sync",` dust: applied=${b.appliedIndex} highest=${b.highestRelevantWalletIndex} complete=${b.isStrictlyComplete()} connected=${b.isConnected}`),o==="full"){let x=y.shielded.progress;W("sync",` shielded: complete=${x.isStrictlyComplete()}`)}}catch{}g(Error("Wallet sync timed out"))}},c);e.keepAlive=a.state().subscribe({next:(w)=>{if(m)return;if(h++,y=w,e.restoredFromCache){let x=hf(w);if(x){m=!0,clearTimeout(S),W("sync",`Stale cache detected: ${x}`),g(new Bn(x));return}}if(r){let x=w.unshielded.progress;if(x){let I=Number(x.appliedId),O=Number(x.highestTransactionId);r(Math.min(I,O),O)}}let b=[];try{if((o==="full"||o==="no-dust")&&!w.shielded.progress.isStrictlyComplete())b.push("shielded");if(o!=="no-dust"&&ff(w))b.push("dust");if(!w.unshielded.progress.isStrictlyComplete())b.push("unshielded")}catch{}if(b.length>0){n?.(b.join(", "));let x=b.join(",");if(h===1||x!==f||h%100===0)W("sync",`Waiting on: ${b.join(", ")} (emission #${h})`),f=x}if(To(w,o)){m=!0,clearTimeout(S),W("sync",`Sync complete after ${h} emissions`),u(w);return}if(d){let x=Date.now()-p;if(x>=gf&&To(w,"no-dust"))m=!0,clearTimeout(S),W("sync",`Sync resolved via cached-restore grace (${x}ms, ${h} emissions)`),u(w)}},error:(w)=>{if(!m)W("sync",`Sync error: ${w.message}`),clearTimeout(S),g(w)}})})}function hf(e){let{appliedId:t,highestTransactionId:r}=e.unshielded.progress;if(r>0n&&t>r)return`unshielded cache applied=${t} but chain highest=${r}.`;return}async function wc(e){let t=(r)=>{let n=r.unshielded.progress.isStrictlyComplete(),s=r.dust.progress.isStrictlyComplete();return n&&s};try{return await Ue.firstValueFrom(e.facade.state().pipe(Ue.filter(t),Ue.timeout(15000)))}catch{return await Ue.firstValueFrom(e.facade.state())}}function yt(e){return e.dust.availableCoins.length>0||e.dust.balance(new Date)>0n}async function ar(e,t=60000){try{return await Ue.firstValueFrom(e.facade.state().pipe(Ue.filter(yt),Ue.timeout(t)))}catch{return await Ue.firstValueFrom(e.facade.state())}}async function Ro(e,t="full"){return Ue.firstValueFrom(e.facade.state().pipe(Ue.filter((r)=>To(r,t)),Ue.timeout(fa)))}async function Ke(e){e.keepAlive?.unsubscribe(),await Promise.race([e.facade.stop(),new Promise((t)=>setTimeout(t,5000))])}function xe(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 gf=1e4,Bn;var ze=T(()=>{we();Tt();Ut();Ht();wt();Bn=class Bn extends Error{code="STALE_CACHE";constructor(e){super(`Cached wallet state is stale (from a previous chain). ${e}
|
|
90
95
|
Run: midnight cache clear --wallet <name> --network <name>
|
|
91
|
-
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function
|
|
96
|
+
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function wf(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 yc(e){let t=new Set,r=[e];while(r.length>0){let n=r.pop();if(!n||typeof n!=="object"||t.has(n))continue;t.add(n);let s=n;if(s._tag==="Wallet.InsufficientFunds"&&s.tokenType==="dust")return!0;if(typeof s.message==="string"&&/no dust tokens|dust.*unavailable/i.test(s.message))return!0;r.push(s.cause,s[yf],s.error,s.defect,s.left,s.right)}return!1}function Hn(e){let t=e?.message?.toLowerCase()??"";return t.includes("not enough dust")||t.includes("dust generated")||t.includes("insufficient generated dust")||t.includes("insufficient funds")||t.includes("no dust tokens")||wf(e)}function sn(e){let t=e?.message?.toLowerCase()??"";if(e?._tag==="Wallet.InsufficientFunds")return!0;return t==="insufficient funds"||t.startsWith("insufficient funds")}var yf;var on=T(()=>{yf=Symbol.for("effect/Runtime/FiberFailure/Cause")});import{existsSync as cn,mkdirSync as Sf,writeFileSync as bf,readFileSync as Sc,unlinkSync as an,readdirSync as Gn,renameSync as vf}from"node:fs";import{join as lt,dirname as kf}from"node:path";import{homedir as $o}from"node:os";import{randomBytes as Cf}from"node:crypto";function Io(e,t,r){let n=r??lt($o(),ie,Be),s=e.slice(0,20);return lt(n,t,`${s}.json`)}function It(e,t,r){let n=Io(e,t,r);if(!cn(n))return null;try{let s=Sc(n,"utf-8"),o=JSON.parse(s);if(o.version!==to)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 Xe(e,t,r,n,s){let[o,i,a]=await Promise.all([r.shielded.serializeState(),r.unshielded.serializeState(),r.dust.serializeState()]),c={version:to,network:t,address:e,timestamp:new Date().toISOString(),wallets:{shielded:o,unshielded:i,dust:a},...s?{chainId:s}:{}},d=Io(e,t,n),p=kf(d);if(!cn(p))Sf(p,{recursive:!0,mode:Te});let u=d+`.tmp.${Cf(4).toString("hex")}`;try{bf(u,JSON.stringify(c),{mode:Ne}),vf(u,d)}catch(g){try{an(u)}catch{}throw g}}function bc(e,t,r){if(!t)return[];let n=r??lt($o(),ie,Be),s=lt(n,e);if(!cn(s))return[];let o=[],i;try{i=Gn(s)}catch{return[]}for(let a of i){if(!a.endsWith(".json"))continue;let c=lt(s,a);try{let d=JSON.parse(Sc(c,"utf-8"));if(!d.chainId)continue;if(d.chainId!==t)an(c),o.push(c)}catch{}}return o}function et(e,t,r){let n=r??lt($o(),ie,Be);if(e&&t){let s=Io(e,t,r);try{an(s)}catch{}return}if(t){let s=lt(n,t);if(!cn(s))return;try{for(let o of Gn(s))if(o.endsWith(".json"))an(lt(s,o))}catch{}return}if(!cn(n))return;try{for(let s of Gn(n)){let o=lt(n,s);try{for(let i of Gn(o))if(i.endsWith(".json"))an(lt(o,i))}catch{}}}catch{}}var _t=()=>{};import xf from"ws";async function cr(e,t,r=[]){let n=e.timeoutMs??Ef;return new Promise((s,o)=>{let i=new xf(e.url),a=!1,c=(p)=>{if(!a)a=!0,p()},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(p){clearTimeout(d),c(()=>o(p instanceof Error?p:Error(String(p))))}}),i.on("message",(p)=>{clearTimeout(d),c(()=>{try{let u=JSON.parse(p.toString());try{i.close()}catch{}if(u.error)o(Error(`RPC ${t}: ${u.error.message}`));else s(u.result)}catch(u){o(u instanceof Error?u:Error(String(u)))}})}),i.on("error",(p)=>{clearTimeout(d),c(()=>o(p instanceof Error?p:Error(String(p))))})})}var Ef=5000;var Kn=()=>{};async function dr(e){let t=vc.get(e);if(t&&Date.now()-t.fetchedAt<Af)return t.hash;try{let r=await cr({url:e,timeoutMs:5000},"chain_getBlockHash",[0]);if(typeof r!=="string"||!r.startsWith("0x"))return null;return vc.set(e,{hash:r,fetchedAt:Date.now()}),r}catch{return null}}var vc,Af=60000;var Jn=T(()=>{Kn();vc=new Map});async function Vn(e,t,r,n){let s;try{s=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r?{query:t,variables:r}:{query:t}),signal:AbortSignal.timeout(n)})}catch(i){throw new Gt(i.message)}if(!s.ok)throw new Gt(`HTTP ${s.status} ${s.statusText}`.trim());let o;try{o=await s.json()}catch(i){throw new Gt(`the answer is not JSON: ${i.message}`)}if(o.errors?.length)throw new Gt(o.errors.map((i)=>i.message).join("; "));if(o.data==null)throw new Gt("the answer has no data");return o.data}var Gt;var _o=T(()=>{Gt=class Gt extends Error{constructor(e){super(e);this.name="IndexerQueryError",Object.setPrototypeOf(this,Gt.prototype)}}});function Cc(e,t){if(t!==null&&t<gt.v9)throw new kc(e,t)}async function qn(e){try{let r=(await Vn(e,"{ block { protocolVersion } }",void 0,Tf)).block?.protocolVersion;return typeof r==="number"?BigInt(r):null}catch{return null}}async function ut(e,t,r=qn){Cc(e,await r(t.indexer))}async function zn(e,t,r={}){let n=await(r.fetchVersion??qn)(t.indexer);if(n===null)throw new Po("indexer",t.indexer);if(Cc(e,n),await(r.fetchGenesis??dr)(t.node)===null)throw new Po("node",t.node)}function xc(e){return["shielded","unshielded","dust"].filter((t)=>e[t]<gt.v9)}var kc,Tf=5000,Po;var Kt=T(()=>{we();Jn();_o();kc=class kc extends Error{code="UNSUPPORTED_LEDGER";constructor(e,t){super(`${e} is on ledger 8 (protocol version ${t}), and this build of mn supports ledger 9 only.
|
|
97
|
+
Use midnight-wallet-cli 0.5.x for ledger-8 networks.`);this.name="UnsupportedLedgerError"}};Po=class Po extends Error{code="LOCAL_STACK_UNREACHABLE";constructor(e,t){super(`No ledger-9 stack is reachable: the ${e} at ${t} did not answer.
|
|
98
|
+
This build of mn can't start a localnet (no published indexer image runs ledger 9 yet).
|
|
99
|
+
Start a ledger-9 stack (node 2.1.0-rc.2, proof-server 9.0.0-rc.8, a 4.4 indexer) and point mn at it:
|
|
100
|
+
midnight config set network undeployed, then midnight config set node / indexer-ws / proof-server <url>`);this.name="LocalStackUnreachableError"}}});function Nf(e,t){if(t<=0n)return[];let r=[...new Set(e)].filter((o)=>o>=0n&&o<t).sort((o,i)=>o<i?-1:o>i?1:0),n=[],s=-1n;for(let o of r){if(o>s+1n)n.push([s+1n,o-1n]);s=o}if(t-1n>s)n.push([s+1n,t-1n]);return n}function Xn(e,t,r){let n=Nf(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 Rf from"ws";function Yn(e,t){let{query:r,variables:n,onNext:s,buildResult:o,timeoutMs:i,idleMs:a,idleBeforeFirstEvent:c,initialSilenceMs:d,signal:p}=t;return new Promise((u,g)=>{let m=new Rf(e,["graphql-transport-ws"]),h=!1,f=!1,y,S,w,b=()=>{if(clearTimeout(y),S)clearTimeout(S);if(w)clearTimeout(w);try{m.close()}catch{}p?.removeEventListener("abort",O)},x=(Q,K)=>{if(f)return;f=!0,b();try{u(o(K))}catch(M){g(M instanceof Error?M:Error(String(M)))}},I=(Q)=>{if(f)return;f=!0,b(),g(Q)},O=()=>I(Error("Operation cancelled"));p?.addEventListener("abort",O,{once:!0});let z=()=>{if(S)clearTimeout(S);S=setTimeout(()=>{if(!f&&(h||c))x("idle",!1)},a)};m.on("open",()=>{m.send(JSON.stringify({type:"connection_init"}))}),m.on("message",(Q)=>{let K;try{K=JSON.parse(Q.toString())}catch{return}if(K.type==="connection_ack"){if(m.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:r,variables:n}})),c)z();if(d&&d>0)w=setTimeout(()=>{if(!h&&!f)x("initial-silence",!1)},d);return}if(K.type==="error"){I(Error(`GraphQL subscription error: ${JSON.stringify(K.payload)?.slice(0,300)}`));return}if(K.type!=="next")return;if(K.payload?.errors){I(Error(`GraphQL error: ${K.payload.errors[0]?.message||"unknown"}`));return}if(h=!0,w)clearTimeout(w),w=void 0;let M;try{M=s(K.payload?.data)}catch(F){I(F instanceof Error?F:Error(String(F)));return}if(z(),M)x("caught-up",!1)}),m.on("error",(Q)=>I(Error(`WebSocket error: ${Q.message}`))),m.on("close",()=>{if(f)return;x(h?"closed-early":"graceful-close",h)}),y=setTimeout(()=>x("timeout",!0),i)})}var Do=()=>{};import*as lr from"@midnightntwrk/ledger-v9";function If(){let e=new lr.DustParameters(la,ua,pa);return new lr.DustLocalState(e)}function Ec(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:p=0,initialRetention:u,collapse:g}=r,m=g!==!1&&process.env[Oo]!=="1",h=500,f=d??If(),y=[],S=e.publicKey,w=new Set((u?.ownedGenerationIndices??[]).map(BigInt)),b=BigInt(u?.generationFrontier??0),x=(M)=>{let F=M.content;if(F?.tag!=="dustInitialUtxo"||F.generationIndex===void 0)return;let ee=F.generationIndex;if(ee+1n>b)b=ee+1n;if(F.generation?.owner===S)w.add(ee)},I=()=>({ownedGenerationIndices:[...w].map(Number),generationFrontier:Number(b)}),O=0,z=p-1,Q=-1,K=()=>{if(y.length===0)return;if(f=f.replayEvents(e,y),O+=y.length,y.length=0,m)f=Xn(f,w,b).state;if(s&&z>=0)try{s(f,z,I())}catch{}};return Yn(t,{query:$f,variables:{id:p},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(M)=>{let F=M?.dustLedgerEvents;if(!F)return!1;let ee;try{ee=lr.Event.deserialize(Buffer.from(F.raw,"hex"))}catch(pe){throw Error(`Failed to deserialize dust event ${F.id}: ${pe.message}`)}if(x(ee),y.push(ee),z=F.id,F.maxId>Q)Q=F.maxId;if(y.length>=500)try{K()}catch(pe){throw Error(`Failed applying dust events: ${pe.message}`)}return n?.(O+y.length,Q),z>=Q},buildResult:(M)=>{try{K();let F=new Date;return f=f.processTtls(F),{balance:f.walletBalance(F),availableCoins:f.utxos.length,eventCount:O,ownedUtxoCount:f.utxos.length,syncTime:f.syncTime,state:f,retention:I(),lastAppliedEventId:z,partial:M}}catch(F){throw Error(`Failed to build dust state: ${F.message}`)}}})}var Oo="MN_DISABLE_DUST_COLLAPSE",$f=`
|
|
92
101
|
subscription DustLedgerEvents($id: Int) {
|
|
93
102
|
dustLedgerEvents(id: $id) {
|
|
94
103
|
type: __typename
|
|
@@ -97,9 +106,9 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
97
106
|
maxId
|
|
98
107
|
}
|
|
99
108
|
}
|
|
100
|
-
`;var
|
|
101
|
-
`),
|
|
102
|
-
`).filter(Boolean).pop(),S
|
|
109
|
+
`;var Mo=T(()=>{Do()});import{spawn as _f}from"node:child_process";import{existsSync as Jt,mkdirSync as Pf,readFileSync as Rc,readdirSync as Ac,unlinkSync as Tc,writeFileSync as Df}from"node:fs";import{homedir as $c}from"node:os";import{dirname as Nc,join as St}from"node:path";import{fileURLToPath as Of}from"node:url";import*as Ic from"@midnightntwrk/ledger-v9";function _c(){let e=process.env.MN_DUST_SYNC_BIN;if(e&&Jt(e))return e;let t=process.platform==="win32"?"dust-sync.exe":"dust-sync",r=Nc(Of(import.meta.url));for(let n of[["..",".."],[".."]]){let s=St(r,...n,"sidecar","dust-sync","target","release",t);if(Jt(s))return s}try{let n=`@nel349/dust-sync-${process.platform}-${process.arch}`,s=Mf(import.meta.url),o=St(Nc(s.resolve(`${n}/package.json`)),t);if(Jt(o))return o}catch{}return null}function Mf(e){return globalThis.require??ia("node:module").createRequire(e)}function Pc(){if(Ff!==Lf)return!1;if(process.env.MN_DISABLE_NATIVE_DUST==="1")return!1;return _c()!==null}function Uf(e,t,r){if(e+1>=t)return"existing";if(r)return"seed";return"fresh"}function jf(e){if(!Jt(e))return-2;try{let t=JSON.parse(Rc(e,"utf-8"));return typeof t.last_applied_event_id==="number"?t.last_applied_event_id:-2}catch{return-2}}function Wf(e,t){let r=St($c(),ie,Be,e);if(!Jt(r))Pf(r,{recursive:!0,mode:Te});return St(r,`dust-native-${t.slice(0,20)}.json`)}function Zn(e,t){let r=St($c(),ie,Be);if(e&&t){try{Tc(St(r,e,`dust-native-${t.slice(0,20)}.json`))}catch{}return}let n=(s)=>{if(!Jt(s))return;try{for(let o of Ac(s))if(o.startsWith("dust-native-")&&o.endsWith(".json"))try{Tc(St(s,o))}catch{}}catch{}};if(e){n(St(r,e));return}if(!Jt(r))return;try{for(let s of Ac(r))n(St(r,s))}catch{}}function Dc(e,t,r){return new Promise((n,s)=>{let o=_c();if(!o){s(Error("dust-sync sidecar not found"));return}let i=t.networkId.toLowerCase(),a=ct(e),c=Wf(i,a),d=["--indexer-ws",t.indexerWS,"--out",c],p=Uf(jf(c),r.startFromId,!!r.initialState);if(p==="seed"){let y={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};Df(c,JSON.stringify(y),{mode:Ne})}if(p!=="fresh")d.push("--resume",c);let u=_f(o,d,{stdio:["pipe","pipe","pipe"]}),g=()=>{try{u.kill("SIGINT")}catch{}};r.signal?.addEventListener("abort",g,{once:!0}),u.stdin.on("error",()=>{});let m=Buffer.from(At(e)).toString("hex");u.stdin.write(m+`
|
|
110
|
+
`),u.stdin.end();let h="",f="";u.stdout.on("data",(y)=>{h+=y.toString()}),u.stderr.on("data",(y)=>{let S=y.toString();f=(f+S).slice(-2000);for(let w of S.matchAll(/applied (\d+) \/ (\d+)/g))r.onProgress?.(Number(w[1]),Number(w[2]))}),u.on("error",(y)=>{r.signal?.removeEventListener("abort",g),s(y)}),u.on("close",(y)=>{if(r.signal?.removeEventListener("abort",g),y!==0){s(Error(`dust-sync exited ${y}: ${f.trim().slice(-300)}`));return}try{let S=h.trim().split(`
|
|
111
|
+
`).filter(Boolean).pop(),w=S?JSON.parse(S):JSON.parse(Rc(c,"utf-8"));n(Bf(w))}catch(S){s(Error(`dust-sync output parse failed: ${S.message}`))}})})}function Bf(e){let t=new Date,r=Ic.DustLocalState.deserialize(new Uint8Array(Buffer.from(e.dust_state,"hex")));if(process.env[Oo]!=="1"){let s=new Set(e.owned_generation_indices.map((o)=>BigInt(o)));r=Xn(r,s,BigInt(e.generation_frontier)).state}r=r.processTtls(t);let n=r.utxos.length;return{balance:r.walletBalance(t),availableCoins:n,eventCount:e.events_applied,ownedUtxoCount:n,syncTime:r.syncTime instanceof Date?r.syncTime:new Date(String(r.syncTime)),state:r,retention:{ownedGenerationIndices:e.owned_generation_indices,generationFrontier:e.generation_frontier},lastAppliedEventId:e.last_applied_event_id,partial:e.partial}}var Ff=8,Lf=9;var Fo=T(()=>{Ut();Mo();Ht()});import*as Mc from"@midnightntwrk/ledger-v9";class Fc{now;fetchTip;fetchUnshielded;fetchDust;fetchChainId;fetchProtocolVersion;cacheDir;dustMemo=new Map;unshieldedMemo=new Map;tipMemo=new Map;constructor(e={}){this.now=e.now??Date.now,this.fetchTip=e.fetchTip??qf,this.fetchUnshielded=e.fetchUnshielded??zf,this.fetchDust=e.fetchDust??Yf,this.fetchChainId=e.fetchChainId??dr,this.fetchProtocolVersion=e.fetchProtocolVersion??qn,this.cacheDir=e.cacheDir}async dust(e,t,r={}){let n=Qn(t);await ut(n,t,this.fetchProtocolVersion);let s=ct(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);dc(n,i,this.cacheDir);let a=i??void 0,c=r.forceFresh?null:nn(n,s,this.cacheDir),d=c!==null,p=0,u=c?.lastAppliedEventId??-1,g=null;for(let h=0;h<Gf;h++){if(r.signal?.aborted)throw Error("Operation cancelled");let f=c?c.lastAppliedEventId+1:0;if(r.onStatus?.(h>0?`Resuming dust from event ${f} (continuation ${h+1})…`:c?`Resuming dust from event ${f}…`:"Reading dust events…"),g=await this.fetchDust(e,t,{startFromId:f,initialState:c?.state,initialRetention:c?.retention,signal:r.signal,onProgress:(y,S)=>{let w=Math.max(1,S+1-f);r.onStatus?.(`Reading dust events… ${y}/${w}`),r.onProgress?.(y,S)},onCheckpoint:(y,S,w)=>{try{Ao(n,s,y,S,this.cacheDir,a,w)}catch{}}}),u=g.lastAppliedEventId>=0?g.lastAppliedEventId:c?.lastAppliedEventId??-1,g.lastAppliedEventId>=0||!c)try{Ao(n,s,g.state,u,this.cacheDir,a,g.retention)}catch{}if(p+=g.eventCount,!g.partial)break;c=nn(n,s,this.cacheDir)}if(!g)throw Error("Dust sync exhausted retries without producing a result");let m={state:g.state,balance:g.balance,availableCoins:g.availableCoins,ownedUtxoCount:g.ownedUtxoCount,syncTime:g.syncTime,fromCache:d,eventsApplied:p,lastAppliedEventId:u,partial:g.partial,fetchedAt:this.now()};return await this.memoize(this.dustMemo,o,m,t,r.signal),m}async unshielded(e,t,r={}){let n=Qn(t),s=typeof e==="string"?e:$e(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=Qn(t),c=$e(e,a),d=t.networkId!=="Undeployed",p=n.syncTimeoutMs??(d?Jf:Kf);await ut(a,t,this.fetchProtocolVersion);let u=await this.fetchChainId(t.node).catch(()=>null);bc(a,u,this.cacheDir);let g=u??void 0;if(i&&!n.noPrime&&!n.forceFresh)try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch(S){n.onSyncWarning?.("PrePrime",S.message)}let m,h,f=!1,y=async()=>{if(f||!m)return;f=!0;try{await Ke(m)}catch{}};try{for(let b=1;b<=dn;b++){if(n.signal?.aborted)throw Error("Operation cancelled");let x=n.forceFresh?null:It(c,a,this.cacheDir);m=await dt(e,t,x);try{h=await $t(m,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:p,syncMode:s,requireStrictSync:o});break}catch(I){if(n.signal?.aborted)throw Error("Operation cancelled");if(I instanceof Bn&&b<dn&&i){n.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${b+1}/${dn})...`),await Ke(m).catch(()=>{}),m=void 0,et(c,a,this.cacheDir),Rt(a,ct(e),this.cacheDir);try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch{}continue}if(b<dn&&String(I?.message??"").includes("timed out")){try{await Xe(c,a,m.facade,this.cacheDir,g)}catch{}n.onStatus?.(`Sync timed out, retrying (attempt ${b+1}/${dn})...`),await Ke(m).catch(()=>{}),m=void 0;continue}throw I}}if(!m||!h)throw Error("Sync failed: no facade state after retries");let S,w=0;while(!0){if(w++,n.signal?.aborted)throw Error("Operation cancelled");try{S=await r({bundle:m,state:h});break}catch(b){if(!(i&&w<Oc&&sn(b)))throw b;if(n.onStatus?.(`Refreshing wallet state (attempt ${w+1}/${Oc})...`),await Ke(m).catch(()=>{}),m=void 0,await new Promise((O)=>setTimeout(O,Vf)),n.signal?.aborted)throw Error("Operation cancelled");let I=It(c,a,this.cacheDir);m=await dt(e,t,I),h=await $t(m,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:p,syncMode:s,requireStrictSync:o})}}if(!n.skipAutoSave)try{await Xe(c,a,m.facade,this.cacheDir,g)}catch{}if(!n.readOnly)this.invalidate({network:t,seed:e});return S}finally{await y()}}invalidate(e){let t=Qn(e.network),r=e.kinds??["dust","unshielded","facade"];if(r.includes("dust"))if(e.seed){let n=ct(e.seed);this.dustMemo.delete(`${t}:${n}`)}else this.deleteByPrefix(this.dustMemo,`${t}:`);if(r.includes("unshielded")){let n=e.address??(e.seed?$e(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=$e(e.seed,t);try{et(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<Hf)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 qf(e){return cr({url:e.node,timeoutMs:3000},"chain_getBlockHash",[])}function zf(e,t,r){return ir(e,t.indexerWS,r)}function Xf(e,t,r){let n=At(e),s=Mc.DustSecretKey.fromSeed(n);return Ec(s,t.indexerWS,r)}async function Yf(e,t,r){if(Pc())try{return await Dc(e,t,r)}catch(n){W("dust",`native sidecar failed, using WASM: ${n.message}`)}return Xf(e,t,r)}function Qn(e){let t=e.networkId.toLowerCase();if(Le(t))return t;throw Error(`Unsupported network: ${e.networkId}`)}function ye(){if(!Lo)Lo=new Fc;return Lo}var Hf=5000,Gf=6,Kf=30000,Jf=120000,dn=3,Oc=5,Vf=5000,Lo=null;var bt=T(()=>{we();ze();on();Ht();_t();Jn();Kt();tn();Mo();Fo();wt();Kn();Ut();Qe()});import*as ur from"@midnightntwrk/ledger-v9";function Qf(e){let t=ur.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 Lc(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:p=0}=r,u=500,g=d??new ur.ZswapLocalState,m=[],h=0,f=p-1,y=-1,S=()=>{if(m.length===0)return;if(g=g.replayEventsWithChanges(e,m).state,h+=m.length,m.length=0,s&&f>=0)try{s(g,f)}catch{}};return Yn(t,{query:Zf,variables:{id:p},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(w)=>{let b=w?.zswapLedgerEvents;if(!b)return!1;let x;try{x=ur.Event.deserialize(new Uint8Array(Buffer.from(b.raw,"hex")))}catch(I){throw Error(`Failed to deserialize zswap event ${b.id}: ${I.message}`)}if(m.push(x),f=b.id,b.maxId>y)y=b.maxId;if(m.length>=500)try{S()}catch(I){throw Error(`Failed applying zswap events: ${I.message}`)}return n?.(h+m.length,y),f>=y},buildResult:(w)=>{try{S();let{balance:b,count:x}=Qf(g);return{balance:b,availableCoins:x,eventCount:h,state:g,lastAppliedEventId:f,partial:w}}catch(b){throw Error(`Failed to build shielded state: ${b.message}`)}}})}var Zf=`
|
|
103
112
|
subscription ZswapLedgerEvents($id: Int) {
|
|
104
113
|
zswapLedgerEvents(id: $id) {
|
|
105
114
|
id
|
|
@@ -107,26 +116,26 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
107
116
|
maxId
|
|
108
117
|
}
|
|
109
118
|
}
|
|
110
|
-
`;var
|
|
111
|
-
Expected a bech32m address for network "${t.networkId}"`)}}function
|
|
112
|
-
Available: ${
|
|
119
|
+
`;var Uc=T(()=>{Do()});import{existsSync as es,mkdirSync as eg,writeFileSync as tg,readFileSync as rg,unlinkSync as jo,readdirSync as jc,renameSync as ng}from"node:fs";import{join as pr,dirname as sg}from"node:path";import{homedir as Wc}from"node:os";import{randomBytes as og}from"node:crypto";import*as ln from"@midnightntwrk/ledger-v9";function Hc(e){return ln.ZswapSecretKeys.fromSeed(Lt(e)).coinPublicKey}function Gc(e,t){let r=t??pr(Wc(),ie,Be);return pr(r,e)}function Wo(e,t,r){let n=t.slice(0,20);return pr(Gc(e,r),`shielded-${n}.json`)}function ig(e,t,r,n){let s=Wo(e,t,r);if(!es(s))return null;try{let o=JSON.parse(rg(s,"utf-8"));if(o.version!==Bc)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:ln.ZswapLocalState.deserialize(new Uint8Array(Buffer.from(o.zswapState,"hex"))),lastAppliedEventId:o.lastAppliedEventId}}catch{return null}}function Uo(e,t,r,n,s,o){let i={version:Bc,network:e,coinPublicKeyHex:t,lastAppliedEventId:n,timestamp:new Date().toISOString(),zswapState:Buffer.from(r.serialize()).toString("hex"),...o?{chainId:o}:{}},a=Wo(e,t,s),c=sg(a);if(!es(c))eg(c,{recursive:!0,mode:Te});let d=a+`.tmp.${og(4).toString("hex")}`;try{tg(d,JSON.stringify(i),{mode:Ne}),ng(d,a)}catch(p){try{jo(d)}catch{}throw p}}function ts(e,t,r){let n=r??pr(Wc(),ie,Be);if(e&&t){let o=Wo(e,t,r);try{jo(o)}catch{}return}let s=(o)=>{if(!es(o))return;try{for(let i of jc(o))if(i.startsWith("shielded-")&&i.endsWith(".json"))try{jo(pr(o,i))}catch{}}catch{}};if(e){s(Gc(e,r));return}if(!es(n))return;try{for(let o of jc(n))s(pr(n,o))}catch{}}async function Kc(e,t,r,n={}){let s=ln.ZswapSecretKeys.fromSeed(Lt(e)),o=s.coinPublicKey,i=n.forceFresh?null:ig(t,o,void 0,n.chainId),a=i?i.lastAppliedEventId+1:0,c=await Lc(s,r,{initialState:i?.state,startFromId:a,onProgress:n.onProgress,signal:n.signal,timeoutMs:n.timeoutMs,onCheckpoint:(d,p)=>{try{Uo(t,o,d,p,void 0,n.chainId)}catch{}}});if(c.lastAppliedEventId>=0)Uo(t,o,c.state,c.lastAppliedEventId,void 0,n.chainId);else if(!i)Uo(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 Bc=2;var Bo=T(()=>{Ut();Uc()});function Jc(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,p=null;if(r.length>=2){let u=i.applied-a.applied,g=i.t-a.t;if(g>=1000&&u>0){d=u/(g/1000);let m=Math.max(0,i.highest-i.applied);p=m>0?m/d:0}}return{applied:i.applied,highest:i.highest,percent:c,ratePerSec:d,etaSec:p}};return{sample(i){return r.push(i),s(i.t),n=o(),n},snapshot(){return n},reset(){r.length=0,n=null}}}function Vc(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 ${ag(e.etaSec)}`);if(e.ratePerSec!==null&&e.ratePerSec>0)r.push(`${Math.round(e.ratePerSec)} evt/s`);return r.join(" · ")}function ag(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 Ko from"@midnightntwrk/ledger-v9";import{MidnightBech32m as cg,UnshieldedAddress as dg}from"@midnightntwrk/wallet-sdk/address-format";function mr(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 un(e){let t=e.trim(),r=/^(\d*)(?:\.(\d*))?$/.exec(t);if(!r||r[1]===""&&!r[2])throw Error(`Invalid amount: "${e}" — must be a positive number, e.g. 1.5`);let n=r[2]??"";if(n.length>Ho)throw Error(`Invalid amount: "${e}" — NIGHT has ${Ho} decimals, this has ${n.length}`);let s=Number(t);if(s<=0)throw Error(`Invalid amount: "${e}" — must be greater than 0`);let o=BigInt((r[1]||"0")+n.padEnd(Ho,"0"));if(mr(s)!==o)throw Error(`Invalid amount: "${e}" — too many digits to handle exactly`);return s}function lg(e,t){let r=He(t.networkId);try{return cg.parse(e).decode(dg,r)}catch(n){throw Error(`Invalid recipient address: ${n.message}
|
|
120
|
+
Expected a bech32m address for network "${t.networkId}"`)}}function rs(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 Go(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 _e(){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 ug(e,t,r,n){await Promise.race([e.facade.dust.waitForSyncedState(),new Promise((a,c)=>setTimeout(()=>c(Error("Insufficient funds: dust wallet sync timed out")),Ys))]);let{fee:s}=await e.facade.estimateRegistration(t);await e.facade.waitForGeneratedDust(t,s,{timeoutMs:n});let o=await e.facade.registerNightUtxosForDustGeneration(t,e.keystore.getPublicKey(),e.keystore.signDataAsync,r),i;try{i=await e.facade.finalizeRecipe(o)}catch(a){try{await e.facade.revert(o)}catch{}throw a}return await e.facade.submitTransaction(i)}async function pg(e,t,r,n){let s=Date.now(),o=s+Sa,i,a=!1,c=setInterval(()=>{if(a&&n){let d=Go(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 ug(e,t,r,o-Date.now())}catch(d){if(i=d,Hn(d)&&Date.now()+eo<o){a=!0;let p=Go(Date.now()-s);n?.(`Waiting for dust generation capacity (${p} elapsed, ~5 min on fresh wallets)...`),await new Promise((u)=>setTimeout(u,eo));continue}throw d}throw i??Error("Dust registration timed out")}finally{clearInterval(c)}}async function pt(e,t,r){let n=r??await e.facade.waitForSyncedState();if(yt(n))return t?.("Dust available"),{alreadyAvailable:!0};if(n.unshielded.availableCoins.length===0&&(n.unshielded.pendingCoins?.length??0)===0)throw Error("This wallet has no NIGHT, so it generates no Dust to pay fees. Fund it first (on undeployed: midnight airdrop <amount>), then run: midnight dust register");let s=n.unshielded.availableCoins.filter((a)=>!a.meta.registeredForDustGeneration),o;if(s.length>0)t?.(`Registering ${s.length} UTXO(s) for dust generation...`),o=await pg(e,s,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<Zs){try{if((await Promise.race([e.facade.waitForSyncedState(),new Promise((c,d)=>setTimeout(()=>d(Error("Poll sync timed out")),Ys))])).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 mg(e,t,r,n,s,o,i){let a=Date.now(),c=a+Zs,d,p=0;while(!0)try{if(d)await Ro(e,"lite");let u=new Date(Date.now()+En*60*1000);W("transfer","Building transfer transaction...");let g=await e.facade.transferTransaction([{type:"unshielded",outputs:[{amount:r,receiverAddress:t,type:Ko.unshieldedToken().raw}]}],{ttl:u,payFees:!0});W("transfer","Signing recipe...");let m=await e.facade.signRecipe(g,e.keystore.signDataAsync);W("transfer","Generating ZK proof..."),n?.();let h=await Promise.race([e.facade.finalizeRecipe(m),new Promise((w,b)=>{setTimeout(()=>b(Error("ZK proof generation timed out")),xn)})]);W("transfer","Submitting transaction to node..."),s?.();let f=Date.now(),y=i?setInterval(()=>i(Date.now()-f),1000):void 0,S;try{S=await e.facade.submitTransaction(h)}finally{if(y)clearInterval(y)}return W("transfer",`Transaction submitted: ${S}`),S}catch(u){if(d=u,(u?.code===ba||u?.message?.includes("115")||u?.message?.toLowerCase().includes("stale"))&&++p<ya)continue;if(sn(u))throw u;if(Hn(u)&&Date.now()<c){let m=Go(Date.now()-a);o?.(`Dust insufficient, re-ensuring (${m} elapsed)...`);try{let h=await Ro(e,"lite"),f=h.dust.balance(new Date);if(f>0n&&f<Or)throw Error(`Insufficient dust for transaction fees.
|
|
121
|
+
Available: ${rs(f)} DUST, need ≥${rs(Or)} DUST.
|
|
113
122
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
114
|
-
Check status: midnight dust status`);await
|
|
115
|
-
Available: ${
|
|
123
|
+
Check status: midnight dust status`);await pt(e,o,h)}catch(h){if(String(h?.message).startsWith("Insufficient dust"))throw h;await new Promise((f)=>setTimeout(f,5000))}continue}throw u}}async function fr(e){let{seedBuffer:t,networkConfig:r,recipientAddress:n,amountNight:s,signal:o,onSync:i,onSyncDetail:a,onDust:c,onProving:d,onSubmitting:p,onSubmittingTick:u,onSyncWarning:g}=e,m=mr(s),h=lg(n,r),f=xe(g),y=_e();try{return await ye().withFacade(t,r,async({bundle:S,state:w})=>{if(o?.aborted)throw Error("Operation cancelled");W("transfer","Sync complete, checking balance...");let b=w.unshielded.balances[Ko.unshieldedToken().raw]??0n,x=w.unshielded.availableCoins?.length??0;if(W("transfer",`Balance: ${Number(b)/Xs} NIGHT, coins: ${x}`),b<m){let z=Number(b)/Xs;throw Error(`Insufficient balance: ${z.toFixed(6)} NIGHT available, ${s} NIGHT requested`)}let I=w.dust.balance(new Date);if(I>0n&&I<Or)throw Error(`Insufficient dust for transaction fees.
|
|
124
|
+
Available: ${rs(I)} DUST, need ≥${rs(Or)} DUST.
|
|
116
125
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
117
|
-
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(
|
|
118
|
-
`)},fail(d){if(t)return;t=!0,
|
|
126
|
+
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(W("transfer","Ensuring dust availability..."),await pt(S,c,w),W("transfer","Dust available"),o?.aborted)throw Error("Operation cancelled");return W("transfer","Building and submitting transaction..."),{txHash:await mg(S,h,m,d,p,c,u),amountMicroNight:m}},{syncMode:"lite",requireStrictSync:!0,signal:o,onStatus:c,onSyncProgress:i,onSyncDetail:a,onSyncWarning:g})}finally{y(),f()}}var Ho=6;var Pt=T(()=>{Tt();ze();bt();wt();on();on()});function Xc(){return Vt}function zc(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function G(e){let t=!1;if(!xt()){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,Vt=null,process.stderr.write(`\r✓ ${d??a}\x1B[K
|
|
127
|
+
`)},fail(d){if(t)return;t=!0,Vt=null,process.stderr.write(`\r✗ ${d??a}\x1B[K
|
|
119
128
|
`)},log(d){process.stderr.write(`\r\x1B[K${d}
|
|
120
|
-
`),process.stderr.write(`⠋ ${a}`)}};return
|
|
121
|
-
`)},fail(a){if(t)return;t=!0,clearInterval(o),
|
|
129
|
+
`),process.stderr.write(`⠋ ${a}`)}};return Vt=c,c}let r=0,n=e,s=()=>{let a=L(qc[r]),d=(process.stderr.columns||80)-4,p=n;if(zc(p).length>d)p=zc(p).slice(0,d);process.stderr.write(`\r${a} ${p}\x1B[K`),r=(r+1)%qc.length};s();let o=setInterval(s,fg),i={update(a){n=a},stop(a){if(t)return;t=!0,clearInterval(o),Vt=null;let c=a??n;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${c}\x1B[K
|
|
130
|
+
`)},fail(a){if(t)return;t=!0,clearInterval(o),Vt=null;let c=a??n;process.stderr.write(`\r\x1B[31m✗\x1B[0m ${c}\x1B[K
|
|
122
131
|
`)},log(a){process.stderr.write(`\r\x1B[K${a}
|
|
123
|
-
`),s()}};return
|
|
124
|
-
Drop --network (we'll infer from the address) or pass an address for ${n}.`);if(!n&&r)e={...e,flags:{...e.flags,network:r}};let{name:s,config:o}=
|
|
132
|
+
`),s()}};return Vt=i,i}async function ns(e,t,r){let n=Date.now(),s=(a)=>{let c=Math.floor(a/1000),d=Math.floor(c/60).toString().padStart(2,"0"),p=(c%60).toString().padStart(2,"0");return`${d}:${p}`},o=()=>e.update(`${t} ${s(Date.now()-n)}`);o();let i=setInterval(o,1000);try{return await r}finally{clearInterval(i)}}var qc,fg=80,Vt=null;var tt=T(()=>{qc=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var Qc={};be(Qc,{default:()=>ss});import*as Yc from"@midnightntwrk/ledger-v9";import{MidnightBech32m as gg}from"@midnightntwrk/wallet-sdk/address-format";async function ss(e){if(e.subcommand)return wg(e);return Zc(e)}function hg(e){let t=e.match(/^mn_addr_([a-z]+)1/);if(!t)return null;let r=t[1];return Le(r)?r:null}async function wg(e){if(We(e))Ge();let t=e.subcommand;W("balance",`address=${t}`);let r=hg(t),n=A(e,"network");if(n&&r&&n!==r)throw Error(`Address belongs to ${r} but --network is ${n}.
|
|
133
|
+
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}=de({args:e});if(R(e,"shielded")){let a=Va(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 Zc(c)}throw Error("Shielded balances are private — they can only be read with the wallet's secret key, "+`not from an address alone.
|
|
125
134
|
This address isn't one of your wallets. Check its shielded balance from the wallet that owns it:
|
|
126
|
-
midnight balance --wallet <name> --shielded --network ${s}`)}
|
|
127
|
-
`);else for(let[c,d]of a.balances)process.stdout.write(`${
|
|
135
|
+
midnight balance --wallet <name> --shielded --network ${s}`)}Re(o,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},s);let i=G(`Checking balance on ${s}...`);try{let a=await ye().unshielded(t,o,{forceFresh:R(e,"no-cache"),onProgress:(c,d)=>{if(d>0){let p=Math.round(c/d*100);i.update(`Syncing transactions... ${p}%`)}}});if(i.stop(`Synced ${a.txCount} transactions`),R(e,"json")){let c={};for(let[p,u]of a.balances){let g=en(p)?"NIGHT":p;c[g]=en(p)?Ft(u):u.toString()}let d=c.NIGHT!==void 0?{NIGHT:c.NIGHT}:{};if(vt(e)){_({network:s,balances:c,...d,utxoCount:a.utxoCount});return}_({address:t,network:s,balances:c,...d,utxoCount:a.utxoCount,txCount:a.txCount});return}if(a.balances.size===0)process.stdout.write(`0
|
|
136
|
+
`);else for(let[c,d]of a.balances)process.stdout.write(`${en(c)?"NIGHT":c}=${d}
|
|
128
137
|
`);if(process.stderr.write(`
|
|
129
|
-
`+
|
|
138
|
+
`+j("Balance")+`
|
|
130
139
|
|
|
131
140
|
`),process.stderr.write(C("Address",re(t))+`
|
|
132
141
|
`),process.stderr.write(C("Network",s)+`
|
|
@@ -134,85 +143,83 @@ This address isn't one of your wallets. Check its shielded balance from the wall
|
|
|
134
143
|
`),process.stderr.write(C("Transactions",a.txCount.toString())+`
|
|
135
144
|
`),process.stderr.write(`
|
|
136
145
|
`),a.balances.size===0)process.stderr.write(` ${l("No balance found")}
|
|
137
|
-
`);else for(let[c,d]of a.balances)if(
|
|
138
|
-
`);else{let
|
|
146
|
+
`);else for(let[c,d]of a.balances)if(en(c))process.stderr.write(C("NIGHT",k(Nn(d)))+`
|
|
147
|
+
`);else{let p=c.slice(0,8)+"…"+c.slice(-8);process.stderr.write(C(`Token ${p}`,k(d.toString()))+`
|
|
139
148
|
`)}process.stderr.write(`
|
|
140
|
-
`+
|
|
149
|
+
`+V()+`
|
|
141
150
|
|
|
142
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
143
|
-
`+
|
|
151
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Zc(e){if(We(e))Ge();let{name:t,config:r}=de({args:e});W("balance",`network=${t} indexerWS=${r.indexerWS}`);let{seed:n,walletPath:s,config:o}=So(e);W("balance",`wallet path=${s??"(from --seed/MN_SEED)"}`);let i=o?.addresses[t]??$e(n,t),a=o?.shieldedAddresses?.[t]??"";Re(r,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},t);let c=xe(),d=_e(),p=R(e,"no-cache"),u=R(e,"json"),g=Yc.unshieldedToken().raw,m=null;try{if(!u){if(process.stderr.write(`
|
|
152
|
+
`+j("Balance")+`
|
|
144
153
|
|
|
145
154
|
`),process.stderr.write(C("Address",re(i))+`
|
|
146
155
|
`),a)process.stderr.write(C("Shielded",re(a))+`
|
|
147
156
|
`);process.stderr.write(C("Network",t)+`
|
|
148
157
|
`),process.stderr.write(`
|
|
149
158
|
`+k("Unshielded")+`
|
|
150
|
-
`)}if(!
|
|
151
|
-
`),process.stderr.write(C(" UTXOs",
|
|
159
|
+
`)}if(!u)m=G("Checking unshielded...");W("balance",`phase=unshielded forceFresh=${p}`);let h=await ye().unshielded(i,r,{forceFresh:p}),f=h.balances.get(g)??0n,y=h.utxoCount;if(W("balance",`unshielded fromCache=${h.fromCache} utxos=${y} txs=${h.txCount}`),m)if(m.stop("Unshielded ready"),m=null,f>0n)process.stderr.write(C(" NIGHT",k(Nn(f)))+`
|
|
160
|
+
`),process.stderr.write(C(" UTXOs",y.toString())+`
|
|
152
161
|
`);else process.stderr.write(` ${l("No unshielded balance")}
|
|
153
|
-
`);if(!
|
|
162
|
+
`);if(!u)process.stdout.write(`NIGHT=${f}
|
|
154
163
|
`),process.stderr.write(`
|
|
155
164
|
`+k("Shielded")+`
|
|
156
|
-
`);let
|
|
157
|
-
`),process.stderr.write(C(" Coins",`${
|
|
165
|
+
`);let S=or(t,R(e,"force-shielded")),w=a,b=0n,x=0,I=0;if(S){if(!u)m=G("Syncing shielded...");let O=Jc(),z=He(r.networkId);if(w=gg.encode(z,Xr(n)).asString(),s)nr(s,t,w);await ut(t,r);let Q=await dr(r.node).catch(()=>null)??void 0,K=await Kc(n,t,r.indexerWS,{forceFresh:p,chainId:Q,onProgress:(M,F)=>{if(!m)return;let ee=O.sample({applied:M,highest:F,t:Date.now()});m.update(Vc(ee,"Syncing shielded"))}});if(b=K.balance,x=K.availableCoins,I=0,m)if(m.stop("Shielded ready"),m=null,b>0n)process.stderr.write(C(" NIGHT",k(Nn(b)))+`
|
|
166
|
+
`),process.stderr.write(C(" Coins",`${x} available, ${I} pending`)+`
|
|
158
167
|
`);else process.stderr.write(` ${l("No shielded balance")}
|
|
159
|
-
`)}else if(!
|
|
160
|
-
`);if(
|
|
168
|
+
`)}else if(!u)process.stderr.write(` ${l("Skipped — "+Ln(t))}
|
|
169
|
+
`);if(u){if(vt(e)){_({network:t,unshielded:{NIGHT:Ft(f),utxoCount:y},shielded:{NIGHT:Ft(b),availableCoins:x,pendingCoins:I},shieldedSynced:S});return}_({address:i,shieldedAddress:w,network:t,unshielded:{NIGHT:Ft(f),utxoCount:y},shielded:{NIGHT:Ft(b),availableCoins:x,pendingCoins:I},shieldedSynced:S});return}process.stdout.write(`SHIELDED_NIGHT=${S?b:"skipped"}
|
|
161
170
|
`),process.stderr.write(`
|
|
162
|
-
`+
|
|
171
|
+
`+V()+`
|
|
163
172
|
|
|
164
|
-
`)}catch(h){throw
|
|
173
|
+
`)}catch(h){throw m?.fail("Failed"),h}finally{d(),c()}}var Jo=T(()=>{wt();we();Ie();sr();Ce();we();Un();Tt();tn();bt();Bo();Kt();Qe();Jn();ze();Pt();ue();tt()});var ed={};be(ed,{default:()=>os});async function os(e){let t=Dn(e,{requireExplicit:!0,label:"address"}),r=A(e,"index"),n=r!==void 0?parseInt(r,10):0;if(isNaN(n)||n<0||!Number.isInteger(Number(r??"0")))throw Error("Key index must be a non-negative integer");let s=ke({args:e}),o=$e(t,s,n),i=`m/44'/2400'/0'/NightExternal/${n}`;if(R(e,"json")){_({address:o,network:s,index:n,path:i});return}process.stdout.write(o+`
|
|
165
174
|
`),process.stderr.write(`
|
|
166
175
|
`),process.stderr.write(C("Network",s)+`
|
|
167
176
|
`),process.stderr.write(C("Index",n.toString())+`
|
|
168
177
|
`),process.stderr.write(C("Address",re(o))+`
|
|
169
178
|
`),process.stderr.write(C("Path",l(i))+`
|
|
170
|
-
`),process.stderr.write(
|
|
179
|
+
`),process.stderr.write(V()+`
|
|
171
180
|
|
|
172
|
-
`)}var Vo=
|
|
181
|
+
`)}var Vo=T(()=>{sr();Qe();Ce();ue()});var td={};be(td,{default:()=>is});async function is(e){let t=ke({args:e}),r=Buffer.from(mt,"hex"),n=$e(r,t);if(R(e,"json")){_({address:n,network:t});return}process.stdout.write(n+`
|
|
173
182
|
`),process.stderr.write(`
|
|
174
183
|
`),process.stderr.write(C("Network",t)+`
|
|
175
184
|
`),process.stderr.write(C("Address",re(n))+`
|
|
176
185
|
`),process.stderr.write(C("Seed",l("0x01 (genesis)"))+`
|
|
177
|
-
`),process.stderr.write(
|
|
186
|
+
`),process.stderr.write(V()+`
|
|
178
187
|
|
|
179
|
-
`)}var qo=
|
|
188
|
+
`)}var qo=T(()=>{Qe();Ce();ue()});var nd={};be(nd,{default:()=>as});import*as rd from"@midnightntwrk/ledger-v9";function pn(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 yg(e){return{readTime:pn(e,"readTime",1000000000n),computeTime:pn(e,"computeTime",1000000000n),blockUsage:pn(e,"blockUsage",10000n),bytesWritten:pn(e,"bytesWritten",10000n),bytesChurned:pn(e,"bytesChurned",1000000n)}}async function as(e){let t=rd.LedgerParameters.initialParameters(),r=yg(t);if(R(e,"json")){_(r);return}for(let[n,s]of Object.entries(r))process.stdout.write(`${n}=${s}
|
|
180
189
|
`);process.stderr.write(`
|
|
181
|
-
`+
|
|
190
|
+
`+j("Block Limits")+`
|
|
182
191
|
|
|
183
192
|
`),process.stderr.write(l(" Derived from LedgerParameters.initialParameters()")+`
|
|
184
193
|
|
|
185
|
-
`);for(let[n,s]of Object.entries(r)){let o=
|
|
194
|
+
`);for(let[n,s]of Object.entries(r)){let o=Sg[n]??"";process.stderr.write(C(n,`${k(s.toLocaleString())} ${l(o)}`)+`
|
|
186
195
|
`)}process.stderr.write(`
|
|
187
|
-
`+
|
|
196
|
+
`+V()+`
|
|
188
197
|
`),process.stderr.write(l(" bytesWritten is typically the tightest constraint")+`
|
|
189
198
|
`),process.stderr.write(l(" for large contract deployments.")+`
|
|
190
199
|
|
|
191
|
-
`)}var
|
|
200
|
+
`)}var Sg;var zo=T(()=>{ue();Sg={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});var id={};be(id,{default:()=>gr});import*as sd from"@midnightntwrk/ledger-v9";import{MidnightBech32m as od,ShieldedAddress as bg}from"@midnightntwrk/wallet-sdk/address-format";async function gr(e,t){kt(e);let r=e.subcommand;if(!r)throw Error(`Missing amount.
|
|
192
201
|
Usage: midnight airdrop <amount> [--wallet <name|file|address>]
|
|
193
202
|
Example: midnight airdrop 1000
|
|
194
203
|
Example: midnight airdrop 1000 --wallet alice
|
|
195
|
-
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=
|
|
204
|
+
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=un(r),{name:s,config:o}=de({args:e});if(Re(o,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},s),s!=="undeployed")throw Error(`Airdrop is only available on the "undeployed" network (local devnet).
|
|
196
205
|
Current network: "${s}"
|
|
197
|
-
On preprod/preview, use a faucet or transfer from another wallet.`);let i=
|
|
206
|
+
On preprod/preview, use a faucet or transfer from another wallet.`);let i=A(e,"wallet"),a=R(e,"shielded")||i!==void 0&&i.startsWith("mn_shield-addr_"),c=kg(e,s,o,a);if(a)return Eg(e,c,n,s,o,t);return xg(e,c,n,s,o,t)}function vg(e){return e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_")}function kg(e,t,r,n){let s=A(e,"wallet");if(s!==void 0&&vg(s))return Cg(s,t,r,n);let o=se(s),i=ae(o);if(n){let a=He(r.networkId),c=Buffer.from(i.seed,"hex"),d=Xr(c),p=od.encode(a,d).asString();return{kind:"wallet",raw:d,bech32m:p,walletPath:o}}return{kind:"address",address:i.addresses[t]}}function Cg(e,t,r,n){let s=e.startsWith("mn_shield-addr_");if(n&&!s)throw Error(`--shielded was passed but --wallet is an unshielded address.
|
|
198
207
|
Pass a shielded address (mn_shield-addr_...) or drop --shielded.
|
|
199
|
-
Got: ${e}`);if(!n&&s)throw Error(`--wallet is a shielded address but --shielded was not passed.
|
|
200
|
-
Add --shielded, or pass an unshielded address (mn_addr_...).
|
|
201
208
|
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
209
|
Expected prefix: ${o}
|
|
203
|
-
Got: ${e}`);if(n){let i=
|
|
204
|
-
`+
|
|
210
|
+
Got: ${e}`);if(n){let i=He(r.networkId),a;try{a=od.parse(e).decode(bg,i)}catch(c){throw Error(`Invalid shielded address: ${c.message}`)}return{kind:"address",raw:a,bech32m:e}}return{kind:"address",address:e}}async function xg(e,t,r,n,s,o){if(We(e))Ge();let i=t.address,a=Buffer.from(mt,"hex");process.stderr.write(`
|
|
211
|
+
`+j("Airdrop")+`
|
|
205
212
|
|
|
206
213
|
`),process.stderr.write(C("Network",n)+`
|
|
207
214
|
`),process.stderr.write(C("From",l("genesis (seed 0x01)"))+`
|
|
208
215
|
`),process.stderr.write(C("To",re(i,!0))+`
|
|
209
216
|
`),process.stderr.write(C("Amount",k(r+" NIGHT"))+`
|
|
210
217
|
`),process.stderr.write(`
|
|
211
|
-
`);let c=
|
|
218
|
+
`);let c=G("Starting genesis wallet...");try{let d=await fr({seedBuffer:a,networkConfig:s,recipientAddress:i,amountNight:r,signal:o,onSync(p,u){if(u>0){let g=Math.round(p/u*100);c.update(`Syncing genesis wallet... ${g}%`)}},onDust(p){c.update(`Dust: ${p}`)},onProving(){c.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){c.update("Submitting and waiting for finalization (typically 12 to 30s)...")},onSubmittingTick(p){let u=Math.floor(p/1000),g=Math.floor(u/60).toString().padStart(2,"0"),m=(u%60).toString().padStart(2,"0");c.update(`Submitting and waiting for finalization... ${g}:${m} elapsed (typically 12 to 30s)`)},onSyncWarning(p,u){c.update(`Syncing genesis wallet... (${u}, retrying)`)}});if(c.stop("Transaction submitted"),R(e,"json")){_({txHash:d.txHash,amount:r,recipient:i,network:n});return}process.stdout.write(d.txHash+`
|
|
212
219
|
`),process.stderr.write(`
|
|
213
|
-
`+
|
|
220
|
+
`+Et(`Airdropped ${r} NIGHT to your wallet`,d.txHash)+`
|
|
214
221
|
`),process.stderr.write(`
|
|
215
|
-
`+
|
|
222
|
+
`+V()+`
|
|
216
223
|
`),process.stderr.write(l(" Verify: midnight balance")+`
|
|
217
224
|
`),process.stderr.write(l(" Register dust: midnight dust register")+`
|
|
218
225
|
`),process.stderr.write(l(" Note: Dust generation takes a few minutes on a fresh wallet.")+`
|
|
@@ -221,79 +228,79 @@ Got: ${e}`);if(n){let i=_t(r.networkId),a;try{a=Pc.parse(e).decode(_f,i)}catch(c
|
|
|
221
228
|
`)}catch(d){if(c.fail("Failed"),d instanceof Error&&d.message.toLowerCase().includes("dust"))throw Error(`${d.message}
|
|
222
229
|
|
|
223
230
|
On a fresh localnet, the minimum airdrop is ~1 NIGHT.
|
|
224
|
-
Try: midnight airdrop 1`);throw d}}async function
|
|
225
|
-
`+
|
|
231
|
+
Try: midnight airdrop 1`);throw d}}async function Eg(e,t,r,n,s,o){let i=mr(r);if(We(e))Ge();let a=Buffer.from(mt,"hex"),c=sd.unshieldedToken().raw,{raw:d,bech32m:p}=t;if(t.kind==="wallet")nr(t.walletPath,n,p);process.stderr.write(`
|
|
232
|
+
`+j("Shielded Airdrop")+`
|
|
226
233
|
|
|
227
234
|
`),process.stderr.write(C("Network",n)+`
|
|
228
235
|
`),process.stderr.write(C("From",l("genesis shielded (seed 0x01)"))+`
|
|
229
|
-
`),process.stderr.write(C("To",re(
|
|
236
|
+
`),process.stderr.write(C("To",re(p,!0))+`
|
|
230
237
|
`),process.stderr.write(C("Amount",k(r+" NIGHT (shielded)"))+`
|
|
231
238
|
`),process.stderr.write(`
|
|
232
|
-
`);let
|
|
239
|
+
`);let u=xe(),g=_e(),m=G("Syncing genesis wallet...");try{let h=await ye().withFacade(a,s,async({bundle:f,state:y})=>{let S=y.shielded.balances[c]??0n;if(S<i){let O=Number(S)/1e6;throw Error(`Genesis wallet has insufficient shielded balance: ${O.toFixed(6)} NIGHT available, ${r} NIGHT requested`)}if(m.update("Checking dust..."),await pt(f,(O)=>m.update(O)),o?.aborted)throw Error("Operation cancelled");m.update("Building shielded transaction...");let w=await f.facade.transferTransaction([{type:"shielded",outputs:[{type:c,amount:i,receiverAddress:d}]}],{ttl:new Date(Date.now()+3600000)});m.update("Signing...");let b=await f.facade.signRecipe(w,f.keystore.signDataAsync);m.update("Generating ZK proof (this may take a few minutes)...");let x=await f.facade.finalizeRecipe(b),I=await ns(m,"Submitting and waiting for finalization (typically 12 to 30s)...",f.facade.submitTransaction(x));return String(I)},{syncMode:"full",requireStrictSync:!0,signal:o,onStatus:(f)=>m.update(f),onSyncProgress:(f,y)=>{if(y>0){let S=Math.min(Math.round(f/y*100),100);m.update(S>=100?"Syncing genesis wallet...":`Syncing genesis wallet... ${S}%`)}},onSyncDetail:(f)=>m.update(`Syncing genesis wallet... (waiting on: ${f})`)});if(m.stop("Transaction submitted"),R(e,"json")){_({txHash:h,amount:r,shieldedAddress:p,network:n,type:"shielded"});return}process.stdout.write(h+`
|
|
233
240
|
`),process.stderr.write(`
|
|
234
|
-
`+
|
|
241
|
+
`+Et(`Airdropped ${r} shielded NIGHT to your wallet`,h)+`
|
|
235
242
|
`),process.stderr.write(`
|
|
236
|
-
`+
|
|
243
|
+
`+V()+`
|
|
237
244
|
`),process.stderr.write(l(" Verify: midnight balance --shielded")+`
|
|
238
245
|
|
|
239
|
-
`)}catch(h){throw
|
|
246
|
+
`)}catch(h){throw m.fail("Failed"),h}finally{g(),u()}}var cs=T(()=>{wt();Ie();Ce();we();Tt();Qe();Pt();ze();bt();ue();tt()});var dd={};be(dd,{default:()=>ds});import*as cd from"@midnightntwrk/ledger-v9";import{MidnightBech32m as ad,ShieldedAddress as Ag}from"@midnightntwrk/wallet-sdk/address-format";async function ds(e,t){kt(e);let r=e.subcommand,n=e.positionals[0];if(!r)throw Error(`Missing recipient address.
|
|
240
247
|
Usage: midnight transfer <to> <amount>
|
|
241
248
|
Example: midnight transfer mn_addr_undeployed1... 100
|
|
242
249
|
Example: midnight transfer alice 100`);if(!n)throw Error(`Missing amount.
|
|
243
250
|
Usage: midnight transfer <to> <amount>
|
|
244
|
-
Example: midnight transfer mn_addr_undeployed1... 100`);let s=
|
|
245
|
-
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function
|
|
246
|
-
`+
|
|
251
|
+
Example: midnight transfer mn_addr_undeployed1... 100`);let s=R(e,"shielded"),o=Tg(r,e,s);if(s)return Rg(e,o,n,t);return Ng(e,o,n,t)}function Tg(e,t,r){if(e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_"))return e;let n=se(e),s=ae(n),o=ke({args:t});if(r){let i=s.shieldedAddresses?.[o];if(!i)throw Error(`Wallet "${e}" has no shielded address for network "${o}".
|
|
252
|
+
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function Ng(e,t,r,n){let s=un(r),o=se(A(e,"wallet")),i=ae(o),a=Buffer.from(i.seed,"hex"),{name:c,config:d}=de({args:e}),p=i.addresses[c];if(Re(d,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},c),process.stderr.write(`
|
|
253
|
+
`+j("Transfer")+`
|
|
247
254
|
|
|
248
255
|
`),process.stderr.write(C("Network",c)+`
|
|
249
|
-
`),process.stderr.write(C("From",re(
|
|
256
|
+
`),process.stderr.write(C("From",re(p,!0))+`
|
|
250
257
|
`),process.stderr.write(C("To",re(t,!0))+`
|
|
251
258
|
`),process.stderr.write(C("Amount",k(s+" NIGHT"))+`
|
|
252
259
|
`),process.stderr.write(`
|
|
253
|
-
`),
|
|
260
|
+
`),We(e))Ge();let u=G("Starting wallet...");try{let g=await fr({seedBuffer:a,networkConfig:d,recipientAddress:t,amountNight:s,signal:n,onSync(m,h){if(h>0){let f=Math.min(Math.round(m/h*100),100);u.update(f>=100?"Syncing wallet...":`Syncing wallet... ${f}%`)}},onSyncDetail(m){u.update(`Syncing wallet... (waiting on: ${m})`)},onDust(m){u.update(`Dust: ${m}`)},onProving(){u.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){u.update("Submitting and waiting for finalization (typically 12 to 30s)...")},onSubmittingTick(m){let h=Math.floor(m/1000),f=Math.floor(h/60).toString().padStart(2,"0"),y=(h%60).toString().padStart(2,"0");u.update(`Submitting and waiting for finalization... ${f}:${y} elapsed (typically 12 to 30s)`)},onSyncWarning(m,h){u.update(`Syncing wallet... (${h}, retrying)`)}});if(u.stop("Transaction submitted"),R(e,"json")){_({txHash:g.txHash,amount:s,recipient:t,network:c});return}process.stdout.write(g.txHash+`
|
|
254
261
|
`),process.stderr.write(`
|
|
255
|
-
`+
|
|
262
|
+
`+Et(`Transferred ${s} NIGHT`,g.txHash)+`
|
|
256
263
|
`),process.stderr.write(`
|
|
257
|
-
`+
|
|
264
|
+
`+V()+`
|
|
258
265
|
`),process.stderr.write(l(" Verify: midnight balance")+`
|
|
259
266
|
|
|
260
|
-
`)}catch(
|
|
261
|
-
Expected a shielded address (mn_shield-addr_...) for network "${
|
|
262
|
-
`+
|
|
267
|
+
`)}catch(g){throw u.fail("Failed"),g}}async function Rg(e,t,r,n){let s=un(r),o=mr(s),i=se(A(e,"wallet")),a=ae(i),c=Buffer.from(a.seed,"hex"),{name:d,config:p}=de({args:e});if(!or(d,R(e,"force-shielded")))throw Error(Ln(d));let u=a.addresses[d],g=He(p.networkId),m=cd.unshieldedToken().raw;Re(p,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},d);let h;try{h=ad.parse(t).decode(Ag,g)}catch(w){throw Error(`Invalid shielded address: ${w.message}
|
|
268
|
+
Expected a shielded address (mn_shield-addr_...) for network "${p.networkId}"`)}if(process.stderr.write(`
|
|
269
|
+
`+j("Shielded Transfer")+`
|
|
263
270
|
|
|
264
271
|
`),process.stderr.write(C("Network",d)+`
|
|
265
272
|
`),process.stderr.write(C("To",re(t,!0))+`
|
|
266
273
|
`),process.stderr.write(C("Amount",k(s+" NIGHT (shielded)"))+`
|
|
267
274
|
`),process.stderr.write(`
|
|
268
|
-
`),
|
|
269
|
-
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(
|
|
275
|
+
`),We(e))Ge();let f=xe(),y=_e(),S=G("Syncing wallet...");try{let w=await ye().withFacade(c,p,async({bundle:b,state:x})=>{let I=ad.encode(g,x.shielded.address).asString();nr(i,d,I);let O=x.shielded.balances[m]??0n;if(O<o){let F=Number(O)/1e6;throw Error(`Insufficient shielded balance: ${F.toFixed(6)} NIGHT available, ${s} NIGHT requested.
|
|
276
|
+
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(S.update("Checking dust..."),await pt(b,(F)=>S.update(F)),n?.aborted)throw Error("Operation cancelled");S.update("Building shielded transaction...");let z=await b.facade.transferTransaction([{type:"shielded",outputs:[{type:m,amount:o,receiverAddress:h}]}],{ttl:new Date(Date.now()+3600000)});S.update("Signing...");let Q=await b.facade.signRecipe(z,b.keystore.signDataAsync);S.update("Generating ZK proof (this may take a few minutes)...");let K=await b.facade.finalizeRecipe(Q),M=await ns(S,"Submitting and waiting for finalization (typically 12 to 30s)...",b.facade.submitTransaction(K));return String(M)},{syncMode:"full",requireStrictSync:!0,signal:n,onStatus:(b)=>S.update(b),onSyncProgress:(b,x)=>{if(x>0){let I=Math.min(Math.round(b/x*100),100);S.update(I>=100?"Syncing wallet...":`Syncing wallet... ${I}%`)}},onSyncDetail:(b)=>S.update(`Syncing wallet... (waiting on: ${b})`)});if(S.stop("Transaction submitted"),R(e,"json")){_({txHash:w,amount:s,recipient:t,network:d,type:"shielded"});return}process.stdout.write(w+`
|
|
270
277
|
`),process.stderr.write(`
|
|
271
|
-
`+
|
|
278
|
+
`+Et(`Transferred ${s} shielded NIGHT`,w)+`
|
|
272
279
|
`),process.stderr.write(`
|
|
273
|
-
`+
|
|
280
|
+
`+V()+`
|
|
274
281
|
`),process.stderr.write(l(" Verify: midnight balance --shielded")+`
|
|
275
282
|
|
|
276
|
-
`)}catch(
|
|
283
|
+
`)}catch(w){throw S.fail("Failed"),w}finally{y(),f()}}var Xo=T(()=>{wt();Ie();Ce();we();Un();Tt();Pt();ze();bt();ue();tt()});async function $g(e,t){let r=await dt(e,t,null);try{return await r.facade.dust.serializeState()}finally{await Ke(r)}}async function ld(e,t,r,n={}){let s=ct(e),i=await(n.repository??ye()).dust(e,r,{signal:n.signal,onProgress:n.onProgress}),a=await(n.buildBaseDust??$g)(e,r),c=i.lastAppliedEventId>=0?No(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 ud=T(()=>{Ht();ze();bt()});var pd={};be(pd,{default:()=>hr});async function hr(e,t){let r=e.subcommand;if(!r||r!=="register"&&r!=="status"&&r!=="export")throw new H(`Missing or invalid subcommand.
|
|
277
284
|
Usage:
|
|
278
285
|
midnight dust register Register NIGHT UTXOs for dust generation
|
|
279
286
|
midnight dust status Check dust registration status
|
|
280
|
-
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=
|
|
287
|
+
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=de({args:e});if(Re(s,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},n),We(e))Ge();let o=R(e,"json"),i=vt(e);if(r==="export"){await Ig(Dn(e),n,s,o,i,t);return}let a=ae(se(A(e,"wallet"))),c=Buffer.from(a.seed,"hex"),d=a.addresses[n];if(r==="status"){let m=await _g(d,n,s.indexerWS,t);if(!m.isRegistered){Pg(n,m,o,i);return}let h=!R(e,"no-cache");await Og(c,s,m,o,i,h,t);return}kt(e);let p={},u=xe((m,h)=>p.current?.(m,h)),g=_e();try{await Dg(c,s,o,t,p)}finally{g(),u()}}async function Ig(e,t,r,n,s,o){let i=G(`Reading dust events from ${t}...`);try{let a=await ld(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){_({subcommand:"export",network:a.network,dustPublicKey:a.dustPublicKey,offset:a.offset,dustBalance:Me(a.balance),eventCount:a.eventCount,fromCache:a.fromCache,partial:a.partial,snapshot:a.snapshot});return}if(process.stdout.write(a.snapshot+`
|
|
281
288
|
`),s)return;if(process.stderr.write(`
|
|
282
289
|
`+C("Network",a.network)+`
|
|
283
|
-
`),process.stderr.write(C("Dust balance",
|
|
290
|
+
`),process.stderr.write(C("Dust balance",Lr(a.balance))+`
|
|
284
291
|
`),process.stderr.write(C("Snapshot offset",String(a.offset))+`
|
|
285
292
|
`),a.partial)process.stderr.write(`
|
|
286
|
-
`+
|
|
293
|
+
`+D(k("⚠ Snapshot is INCOMPLETE — the sync did not reach the chain tip."))+`
|
|
287
294
|
`+l(" Restoring it still beats a cold start, but the wallet has events left to catch up on.")+`
|
|
288
295
|
`+l(" Re-run `mn dust export` to resume from this checkpoint and finish.")+`
|
|
289
296
|
`);process.stderr.write(`
|
|
290
297
|
`+l("Restore with the wallet SDK dustSerializedState to skip the cold dust sync.")+`
|
|
291
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
292
|
-
`+
|
|
298
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function _g(e,t,r,n){process.stderr.write(`
|
|
299
|
+
`+j("Dust Status")+`
|
|
293
300
|
|
|
294
301
|
`),process.stderr.write(C("Network",t)+`
|
|
295
302
|
|
|
296
|
-
`);let s=
|
|
303
|
+
`);let s=G(`Checking registration on ${t}...`);try{let o=await ir(e,r,(c,d)=>{if(d>0){let p=Math.min(Math.round(c/d*100),100);s.update(p>=100?"Checking registration...":`Checking registration... ${p}%`)}});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 Pg(e,t,r,n){let{registeredUtxos:s,unregisteredUtxos:o}=t,i=s+o;if(r){if(n){_({network:e,registered:!1,registeredUtxos:s,unregisteredUtxos:o});return}_({subcommand:"status",registered:!1,registeredUtxos:s,unregisteredUtxos:o,network:e});return}if(process.stdout.write(`registered=no
|
|
297
304
|
`),process.stdout.write(`registered_utxos=${s}
|
|
298
305
|
`),process.stdout.write(`unregistered_utxos=${o}
|
|
299
306
|
`),process.stderr.write(C("Registered",k("no"))+`
|
|
@@ -303,46 +310,46 @@ Usage:
|
|
|
303
310
|
`);else process.stderr.write(`
|
|
304
311
|
`+l("Not generating dust. Run: midnight dust register")+`
|
|
305
312
|
`);process.stderr.write(`
|
|
306
|
-
`+
|
|
313
|
+
`+V()+`
|
|
307
314
|
|
|
308
|
-
`)}async function
|
|
309
|
-
`+
|
|
315
|
+
`)}async function Dg(e,t,r,n,s){let o=t.networkId.toLowerCase();process.stderr.write(`
|
|
316
|
+
`+j("Dust Register")+`
|
|
310
317
|
|
|
311
318
|
`),process.stderr.write(C("Network",o)+`
|
|
312
319
|
|
|
313
|
-
`);let i=
|
|
320
|
+
`);let i=G("Syncing wallet...");if(s)s.current=(a,c)=>i.update(`Syncing wallet... (${c}, retrying)`);try{let{result:a,dustBal:c}=await ye().withFacade(e,t,async({bundle:d,state:p})=>{if(n?.aborted)throw Error("Operation cancelled");i.update("Checking dust status...");let u=await pt(d,(m)=>i.update(m),p);if(n?.aborted)throw Error("Operation cancelled");let g=await wc(d);return{result:u,dustBal:g.dust.balance(new Date)}},{syncMode:"lite",requireStrictSync:!0,signal:n,onStatus:(d)=>i.update(d),onSyncProgress:(d,p)=>{if(p>0){let u=Math.min(Math.round(d/p*100),100);i.update(u>=100?"Syncing wallet...":`Syncing wallet... ${u}%`)}},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:Me(c)};if(a.txHash)d.txHash=a.txHash;_(d);return}process.stdout.write(c.toString()+`
|
|
314
321
|
`),process.stderr.write(`
|
|
315
|
-
`+
|
|
322
|
+
`+Et(a.alreadyAvailable?`Dust tokens already available: ${Lr(c)}`:`Dust tokens available: ${Lr(c)}`)+`
|
|
316
323
|
|
|
317
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
324
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Og(e,t,r,n,s,o,i){let a=t.networkId.toLowerCase(),c=G(`Reading dust events from ${a}...`);try{let d=await ye().dust(e,t,{forceFresh:!o,signal:i,onStatus:(g)=>c.update(g)});c.stop(d.fromCache&&d.eventsApplied===0?"Cache up to date":"Dust events applied");let{registeredUtxos:p,unregisteredUtxos:u}=r;if(n){if(s){_({network:a,registered:!0,registeredUtxos:p,unregisteredUtxos:u,dustBalance:Me(d.balance),dustAvailable:d.availableCoins>0});return}_({subcommand:"status",registered:!0,registeredUtxos:p,unregisteredUtxos:u,dustBalance:Me(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
325
|
`),process.stdout.write(`dust=${d.balance}
|
|
319
|
-
`),process.stdout.write(`registered_utxos=${
|
|
320
|
-
`),process.stdout.write(`unregistered_utxos=${
|
|
326
|
+
`),process.stdout.write(`registered_utxos=${p}
|
|
327
|
+
`),process.stdout.write(`unregistered_utxos=${u}
|
|
321
328
|
`),process.stderr.write(C("Registered",k("yes"))+`
|
|
322
|
-
`),process.stderr.write(C("UTXOs",`${
|
|
323
|
-
`),process.stderr.write(C("Dust Balance",k(
|
|
329
|
+
`),process.stderr.write(C("UTXOs",`${p} registered, ${u} unregistered`)+`
|
|
330
|
+
`),process.stderr.write(C("Dust Balance",k(Lr(d.balance)))+`
|
|
324
331
|
`),process.stderr.write(C("Dust Available",d.availableCoins>0?"yes":"no")+`
|
|
325
332
|
`),process.stderr.write(C("Events applied",d.eventsApplied.toString()+(d.fromCache?" (delta)":""))+`
|
|
326
|
-
`),
|
|
327
|
-
`+l(`${
|
|
333
|
+
`),u>0)process.stderr.write(`
|
|
334
|
+
`+l(`${u} UTXO(s) not yet registered. Run: midnight dust register`)+`
|
|
328
335
|
`);process.stderr.write(`
|
|
329
|
-
`+
|
|
330
|
-
|
|
331
|
-
`)}catch(d){throw c.fail("Failed"),d}}var
|
|
332
|
-
`)}else if(n){if(et(void 0,n),
|
|
333
|
-
`)}else{if(et(),
|
|
334
|
-
`)}}var
|
|
335
|
-
Valid keys: ${
|
|
336
|
-
Valid keys: ${
|
|
337
|
-
`)}else if(t==="unset"){
|
|
338
|
-
`)}else{let n=e.positionals[1];if(n===void 0)throw new
|
|
339
|
-
Usage: midnight config set ${r} <value>`);if(
|
|
340
|
-
`)}}var
|
|
336
|
+
`+V()+`
|
|
337
|
+
|
|
338
|
+
`)}catch(d){throw c.fail("Failed"),d}}var ls=T(()=>{Fe();wt();Ie();sr();Ce();we();ze();Pt();tn();ud();bt();ue();tt()});var md={};be(md,{default:()=>us});async function us(e){if(e.subcommand!=="clear")throw new H("Usage: midnight cache clear [--network <name>] [--wallet <name|file>]");let r=A(e,"wallet"),n=A(e,"network"),s=R(e,"json");if(r){let o=se(r),i=ae(o),a=ke({args:e}),c=i.addresses[a];et(c,a);let d=ct(Buffer.from(i.seed,"hex"));Rt(a,d),Zn(a,d);let p=Hc(Buffer.from(i.seed,"hex"));if(ts(a,p),s){_({action:"clear",scope:"wallet",wallet:r,network:a});return}process.stderr.write(B("✓")+` Cache cleared for wallet "${r}" on ${a}
|
|
339
|
+
`)}else if(n){if(et(void 0,n),Rt(n),Zn(n),ts(n),s){_({action:"clear",scope:"network",network:n});return}process.stderr.write(B("✓")+` Cache cleared for network "${n}"
|
|
340
|
+
`)}else{if(et(),Rt(),Zn(),ts(),s){_({action:"clear",scope:"all"});return}process.stderr.write(B("✓")+` Cache cleared
|
|
341
|
+
`)}}var Yo=T(()=>{Fe();_t();Ht();Bo();Fo();Ie();Ce()});var fd={};be(fd,{default:()=>ps});async function ps(e){let t=e.subcommand;if(!t||!["get","set","unset"].includes(t))throw new H(`Usage: midnight config <get|set|unset> <key> [value]
|
|
342
|
+
Valid keys: ${lo().join(", ")}`);let r=e.positionals[0];if(!r)throw new H(`Missing config key.
|
|
343
|
+
Valid keys: ${lo().join(", ")}`);if(t==="get"){let n=ja(r);if(R(e,"json")){_({action:"get",key:r,value:n});return}process.stdout.write(n+`
|
|
344
|
+
`)}else if(t==="unset"){Ba(r);let n=r==="network"?"(default)":"(removed)";if(R(e,"json")){_({action:"unset",key:r,value:n});return}process.stderr.write(B("✓")+` ${r} ${n}
|
|
345
|
+
`)}else{let n=e.positionals[1];if(n===void 0)throw new H(`Missing value for config set.
|
|
346
|
+
Usage: midnight config set ${r} <value>`);if(Wa(r,n),R(e,"json")){_({action:"set",key:r,value:n});return}process.stderr.write(B("✓")+` ${r} = ${n}
|
|
347
|
+
`)}}var Zo=T(()=>{Fe();tr()});import{execSync as mn}from"child_process";import{existsSync as gd,mkdirSync as Mg,readFileSync as Fg,writeFileSync as hd}from"fs";import{homedir as Lg}from"os";import{join as ei}from"path";function yd(){try{return mn("docker compose version",{...fs,timeout:1e4}).trim()}catch{try{throw mn("docker --version",{...fs,timeout:5000}),Error(`Docker Compose v2 is required.
|
|
341
348
|
Install it from https://docs.docker.com/compose/install/`)}catch(e){if(e instanceof Error&&e.message.includes("Docker Compose v2"))throw e;throw Error(`Docker is required but was not found.
|
|
342
|
-
Install Docker from https://docs.docker.com/get-docker/`)}}}function
|
|
343
|
-
`),r=[];for(let n of t){if(!n.trim())continue;try{let s=JSON.parse(n),o=s.Service??"unknown";r.push({name:o,state:s.State??"unknown",health:s.Health??"",port:
|
|
349
|
+
Install Docker from https://docs.docker.com/get-docker/`)}}}function bd(){if(!Hg)throw new Sd;if(gd(Qo)&&gd(ms)&&Fg(Qo,"utf-8").trim()===wd)return!1;return Mg(ti,{recursive:!0,mode:Te}),hd(ms,Bg,"utf-8"),hd(Qo,wd,"utf-8"),!0}function wr(e){return mn(`docker compose -f "${ms}" ${e}`,fs)}function gs(){try{let e=wr("ps --format json");if(!e.trim())return[];let t=e.trim().split(`
|
|
350
|
+
`),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:Gg[o]??"",image:s.Image??""})}catch{}}return r}catch{return[]}}function vd(e=120000,t=3000){let r=Date.now()+e;while(Date.now()<r){let n=gs();if(n.length===3&&n.every((o)=>o.state==="running")){if(n.every((i)=>i.health==="healthy"||i.health===""))return!0}mn(`sleep ${t/1000}`,{timeout:t+1000})}return!1}function ri(){return ms}function kd(){let e=[];for(let t of Kg)try{mn(`docker rm -f "${t}"`,{...fs,timeout:1e4}),e.push(t)}catch{}return e}var wd="3.0.6",Ug="midnightntwrk/midnight-node:1.0.0",jg="midnightntwrk/indexer-standalone:4.3.3",Wg="midnightntwrk/proof-server:8.1.0",ti,ms,Qo,Bg,fs,Hg=!1,Sd,Gg,Kg;var Cd=T(()=>{ti=ei(Lg(),ie,ka),ms=ei(ti,"compose.yml"),Qo=ei(ti,".version"),Bg=`services:
|
|
344
351
|
proof-server:
|
|
345
|
-
image: '${
|
|
352
|
+
image: '${Wg}'
|
|
346
353
|
container_name: "proof-server"
|
|
347
354
|
# Self-heal across Docker Desktop restarts and transient stops. Without this,
|
|
348
355
|
# a stopped node/proof-server never comes back while the indexer (below) does,
|
|
@@ -353,7 +360,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function ur(){if(Gc(
|
|
|
353
360
|
- "6300:6300"
|
|
354
361
|
|
|
355
362
|
indexer:
|
|
356
|
-
image: '${
|
|
363
|
+
image: '${jg}'
|
|
357
364
|
container_name: "indexer"
|
|
358
365
|
# unless-stopped covers two cases: (1) indexer >=4.3.x runs an SPO sub-indexer
|
|
359
366
|
# that queries block #1 at startup and exits the whole process if it isn't there
|
|
@@ -389,7 +396,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function ur(){if(Gc(
|
|
|
389
396
|
condition: service_started
|
|
390
397
|
|
|
391
398
|
node:
|
|
392
|
-
image: '${
|
|
399
|
+
image: '${Ug}'
|
|
393
400
|
container_name: "node"
|
|
394
401
|
# Self-heal across Docker Desktop restarts / transient stops (see proof-server).
|
|
395
402
|
restart: unless-stopped
|
|
@@ -403,116 +410,119 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function ur(){if(Gc(
|
|
|
403
410
|
start_period: 5s
|
|
404
411
|
environment:
|
|
405
412
|
CFG_PRESET: "dev"
|
|
406
|
-
`,
|
|
407
|
-
|
|
408
|
-
|
|
413
|
+
`,fs={encoding:"utf-8",timeout:30000};Sd=class Sd extends Error{code="LOCALNET_UNAVAILABLE";constructor(){super(`mn localnet can't start a ledger-9 network yet: no published indexer image runs ledger 9.
|
|
414
|
+
Run a ledger-9 stack yourself (node 2.1.0-rc.2, proof-server 9.0.0-rc.8, a 4.4 indexer) and point mn at it:
|
|
415
|
+
per command: --node ws://localhost:9944 --indexer-ws ws://localhost:8088/api/v4/graphql/ws --proof-server http://localhost:6300
|
|
416
|
+
or once: midnight config set node <url>; midnight config set indexer-ws <url>; midnight config set proof-server <url>`);this.name="LocalnetUnavailableError"}};Gg={node:"9944",indexer:"8088","proof-server":"6300"};Kg=["node","indexer","proof-server"]});async function xd(e,t={}){let r=t.timeoutMs??30000,n=t.pollIntervalMs??1000,s=Date.now()+r;while(Date.now()<s){try{let o=await cr({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 Ed=T(()=>{Kn()});async function Ad(e,t,r={}){let n=r.timeoutMs??30000,s=r.pollIntervalMs??1000,o=Date.now()+n;while(Date.now()<o){try{if((await ir(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=T(()=>{tn()});async function Nd(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 _d={};be(_d,{default:()=>hs});import{spawn as Rd}from"child_process";import{existsSync as Jg,rmSync as Vg}from"node:fs";import{resolve as qg}from"node:path";function zg(e){return $d.includes(e)}function Id(e){let t=[];for(let r of e){let n=r.state==="running"?B:J,s=r.health?` (${r.health})`:"",o=r.port?`:${r.port}`:"",i=r.image?` ${l(r.image)}`:"";if(t.push(` ${r.name.padEnd(16)}${n(r.state)}${l(s)}${l(o)}`),i)t.push(i)}return t.join(`
|
|
417
|
+
`)}async function Xg(e){if(bd())process.stderr.write(l(` Wrote compose.yml to ${ri()}`)+`
|
|
418
|
+
`);let r=G("Starting local network...");try{if(wr("up -d"),r.update("Waiting for services to be healthy..."),!vd(120000))r.stop(D("Services started but not all healthy yet")),process.stderr.write(`
|
|
409
419
|
`+l(" Tip: run ")+k("midnight localnet logs")+l(" to check for errors")+`
|
|
410
|
-
`);else{r.update("Waiting for chain to produce first block...");try{
|
|
420
|
+
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() => Ed());await Promise.resolve().then(() => Td());await Promise.resolve();await Promise.resolve().then(() => we());await Promise.resolve().then(() => Qe());await Promise.resolve();let u=Hr("undeployed");await xd(u.node,{timeoutMs:30000}),r.update("Waiting for indexer to ingest genesis state...");let g=$e(Buffer.from(mt,"hex"),"undeployed");await Ad(u.indexerWS,g,{timeoutMs:30000}),r.update("Waiting for proof server..."),await Nd(u.proofServer,{timeoutMs:30000}),r.stop("Local network is running")}catch(o){r.stop(D("Services running but chain/indexer/proof-server not fully ready yet")),process.stderr.write(`
|
|
411
421
|
`+l(" Tip: give it a few more seconds then retry. Run ")+k("midnight localnet logs")+l(" if this persists.")+`
|
|
412
422
|
`)}}}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
423
|
`+`(likely from a previous midnight-local-network setup).
|
|
414
424
|
|
|
415
425
|
Run "midnight localnet clean" to remove them, then try again.`);if(s.message.includes("address already in use"))throw Error(`Port conflict detected — another process is using a required port.
|
|
416
|
-
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=
|
|
417
|
-
`+
|
|
426
|
+
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=gs();if(e){_({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(`
|
|
427
|
+
`+Id(n)+`
|
|
418
428
|
`);for(let s of n)process.stdout.write(`${s.name}=${s.state}:${s.port}
|
|
419
429
|
`);process.stderr.write(`
|
|
420
430
|
`+l(" Next: ")+k("midnight wallet generate dev --network undeployed")+`
|
|
421
|
-
`)}async function
|
|
422
|
-
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function
|
|
423
|
-
`+
|
|
431
|
+
`)}async function Yg(e){let t=G("Stopping local network...");try{if(wr("stop"),t.stop("Local network stopped (containers preserved)"),e){_({subcommand:"stop",status:"stopped"});return}}catch(r){throw t.fail("Failed to stop local network"),r}}async function Zg(e){let t=G("Tearing down local network...");try{wr("down --volumes");await Promise.resolve().then(() => _t());await Promise.resolve().then(() => Ht());et(void 0,"undeployed"),Rt("undeployed");let s=Qg();if(t.stop("Local network removed (containers, networks, volumes, caches)"),e){_({subcommand:"down",status:"removed",cachesCleared:!0,dappLevelDbWiped:s});return}if(s)process.stderr.write(l(" Also cleared dapp leveldb at ./midnight-level-db (private state from old chain)")+`
|
|
432
|
+
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function Qg(){let e=qg(process.cwd(),"midnight-level-db");if(!Jg(e))return!1;try{return Vg(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function eh(e){let t=gs();if(e){_({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(`
|
|
433
|
+
`+j("Localnet Status")+`
|
|
424
434
|
|
|
425
435
|
`),process.stderr.write(l(" No services running.")+`
|
|
426
|
-
`),process.stderr.write(l("
|
|
436
|
+
`),process.stderr.write(l(" ")+k("midnight localnet up")+l(" is refused on this ledger-9 build; see ")+k("midnight help localnet")+l(".")+`
|
|
427
437
|
|
|
428
438
|
`);return}process.stderr.write(`
|
|
429
|
-
`+
|
|
439
|
+
`+j("Localnet Status")+`
|
|
430
440
|
|
|
431
|
-
`),process.stderr.write(
|
|
441
|
+
`),process.stderr.write(Id(t)+`
|
|
432
442
|
`),process.stderr.write(`
|
|
433
|
-
`+
|
|
443
|
+
`+V()+`
|
|
434
444
|
|
|
435
445
|
`);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",
|
|
446
|
+
`)}async function th(e){let t=G("Removing conflicting containers...");try{try{wr("down")}catch{}let r=kd();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){_({subcommand:"clean",status:"cleaned",removed:r});return}}catch(r){throw t.fail("Failed to clean up"),r}}async function rh(e){let t=ri(),r=A(e,"tail"),n=R(e,"json");if(r!==void 0||n){let o=r??"200",i=Rd("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,p)=>{i.on("close",(u)=>{if(u!==0&&u!==null){p(Error(`docker compose logs exited with code ${u}: ${c.trim()}`));return}if(n)_({tail:Number(o),lines:a.split(`
|
|
447
|
+
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",p)})}let s=Rd("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 hs(e){let t=e.subcommand;if(!t||!zg(t))throw new H(`Usage: midnight localnet <${$d.join("|")}>
|
|
438
448
|
|
|
439
449
|
Subcommands:
|
|
440
|
-
up Start the local network
|
|
450
|
+
up Start the local network (refused on this ledger-9 build)
|
|
441
451
|
stop Stop containers (preserves state)
|
|
442
452
|
down Remove containers, networks, volumes
|
|
443
453
|
status Show service status
|
|
444
454
|
logs Stream service logs
|
|
445
455
|
clean Remove conflicting containers
|
|
446
456
|
|
|
447
|
-
Example: midnight localnet
|
|
448
|
-
`+
|
|
457
|
+
Example: midnight localnet status`);yd();let r=R(e,"json");switch(process.stderr.write(`
|
|
458
|
+
`+j("Localnet")+`
|
|
449
459
|
|
|
450
|
-
`),t){case"up":return
|
|
460
|
+
`),t){case"up":return Xg(r);case"stop":return Yg(r);case"down":return Zg(r);case"status":return eh(r);case"logs":return rh(e);case"clean":return th(r)}}var $d;var ni=T(()=>{Fe();Cd();ue();tt();$d=["up","stop","down","status","logs","clean"]});var Od={};be(Od,{default:()=>yr});import*as Dd from"fs";import*as si from"path";import{homedir as nh}from"os";import{generateMnemonic as sh,mnemonicToSeedSync as Pd,mnemonicToEntropy as oh,validateMnemonic as ih}from"@scure/bip39";import{wordlist as oi}from"@scure/bip39/wordlists/english.js";async function yr(e){let t=e.subcommand;switch(t){case"generate":return ah(e);case"list":case"ls":return ch(e);case"use":return dh(e);case"info":return lh(e);case"remove":case"rm":return uh(e);case"seed":return ph(e);default:throw new H(`Unknown wallet subcommand: "${t??"(none)"}"
|
|
451
461
|
Available: generate, list, use, info, remove, seed
|
|
452
|
-
Run "midnight help wallet" for usage.`)}}async function
|
|
453
|
-
Usage: midnight wallet generate <name> [--network <name>]`);if(!
|
|
454
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=
|
|
455
|
-
Use --force to overwrite.`);let a,c;if(n!==void 0)
|
|
462
|
+
Run "midnight help wallet" for usage.`)}}async function ah(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
463
|
+
Usage: midnight wallet generate <name> [--network <name>]`);if(!Ot(t))throw Error(`Invalid wallet name: "${t}"
|
|
464
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=ke({args:e}),n=A(e,"seed"),s=A(e,"mnemonic");if(n!==void 0&&s!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let o=si.join(nh(),ie,Yt),i=si.join(o,`${t}.json`);if(Dd.existsSync(i)&&!R(e,"force"))throw Error(`Wallet "${t}" already exists: ${i}
|
|
465
|
+
Use --force to overwrite.`);let a,c;if(n!==void 0)a=Qr(n,"--seed");else if(s!==void 0){if(!ih(s,oi))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");c=s,a=Buffer.from(Pd(c))}else c=sh(oi,256),a=Buffer.from(Pd(c));let d=jt(a),p=zr(a),u=d[r],g={seed:a.toString("hex"),addresses:d,shieldedAddresses:p,createdAt:new Date().toISOString()};if(c)g.mnemonic=c;let m=_n(g,i);if(Yr(t),R(e,"json")){let f={name:t,addresses:d,shieldedAddresses:p,activeAddress:u,activeNetwork:r,seed:a.toString("hex"),file:m,createdAt:g.createdAt,active:!0};if(c)f.mnemonic=c;_(f);return}process.stdout.write(u+`
|
|
456
466
|
`),process.stderr.write(`
|
|
457
|
-
`+
|
|
467
|
+
`+j("Wallet Generated")+`
|
|
458
468
|
|
|
459
469
|
`),process.stderr.write(C("Name",t)+`
|
|
460
470
|
`),process.stderr.write(C("Network",r)+`
|
|
461
|
-
`),process.stderr.write(C("Address",re(
|
|
462
|
-
`);let h=
|
|
463
|
-
`);if(process.stderr.write(C("File",
|
|
471
|
+
`),process.stderr.write(C("Address",re(u))+`
|
|
472
|
+
`);let h=p[r];if(h)process.stderr.write(C("Shielded",re(h))+`
|
|
473
|
+
`);if(process.stderr.write(C("File",m)+`
|
|
464
474
|
`),process.stderr.write(C("Active","yes")+`
|
|
465
475
|
`),process.stderr.write(`
|
|
466
|
-
`),c)process.stderr.write(
|
|
476
|
+
`),c)process.stderr.write(D(k(" MNEMONIC (save securely!):"))+`
|
|
467
477
|
`),process.stderr.write(` ${c}
|
|
468
478
|
|
|
469
|
-
`);process.stderr.write(
|
|
479
|
+
`);process.stderr.write(D(k(" SEED (hex):"))+`
|
|
470
480
|
`),process.stderr.write(` ${a.toString("hex")}
|
|
471
481
|
|
|
472
|
-
`),process.stderr.write(
|
|
482
|
+
`),process.stderr.write(V()+`
|
|
473
483
|
`),process.stderr.write(l(" Next: midnight wallet list | midnight balance")+`
|
|
474
484
|
|
|
475
|
-
`),process.stderr.write(
|
|
476
|
-
`)}async function
|
|
485
|
+
`),process.stderr.write(B("✓")+` Wallet saved
|
|
486
|
+
`)}async function ch(e){let t=ho(),r=ke({args:e});if(R(e,"json")){if(vt(e)){_({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}_({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
487
|
No wallets found.
|
|
478
488
|
`),process.stderr.write(l(" Create one: midnight wallet generate <name> --network <name>")+`
|
|
479
489
|
|
|
480
490
|
`);return}process.stderr.write(`
|
|
481
|
-
`+
|
|
491
|
+
`+j("Wallets")+`
|
|
482
492
|
|
|
483
493
|
`);let n=Math.max(...t.map((a)=>a.name.length)),s=19,o=19,i=" ".repeat(n-4);process.stderr.write(` ${l("name")}${i} ${l("unshielded".padEnd(s))} ${l("shielded")}
|
|
484
|
-
`);for(let a of t){let c=a.isActive?
|
|
494
|
+
`);for(let a of t){let c=a.isActive?B("●"):" ",d=a.isActive?k(L(a.name)):L(a.name),p=" ".repeat(n-a.name.length),u=a.addresses[r]??"(unknown)",g=a.shieldedAddresses?.[r],m=g?re(g,!0):l("—".padEnd(o));process.stderr.write(` ${c} ${d}${p} ${re(u,!0)} ${m}
|
|
485
495
|
`)}process.stderr.write(`
|
|
486
|
-
`+
|
|
496
|
+
`+V()+`
|
|
487
497
|
`),process.stderr.write(l(` ● = active wallet · network: ${r} · details: midnight wallet info <name>`)+`
|
|
488
498
|
|
|
489
|
-
`)}async function
|
|
490
|
-
Usage: midnight wallet use <name>`);if(
|
|
491
|
-
`)}async function
|
|
499
|
+
`)}async function dh(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
500
|
+
Usage: midnight wallet use <name>`);if(Yr(t),R(e,"json")){_({wallet:t,active:!0});return}process.stderr.write(B("✓")+` Active wallet set to "${t}"
|
|
501
|
+
`)}async function lh(e){let t=A(e,"wallet")??e.positionals[0]??Nt(),r=se(t),n=ae(r),s=t===Nt(),o=ke({args:e}),i=n.addresses[o];if(R(e,"json")){if(vt(e)){_({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;_(c);return}process.stdout.write(i+`
|
|
492
502
|
`),process.stderr.write(`
|
|
493
|
-
`+
|
|
503
|
+
`+j(`Wallet: ${t}`)+`
|
|
494
504
|
|
|
495
|
-
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],
|
|
496
|
-
`),process.stderr.write(` ${l("unshielded")} ${re(
|
|
497
|
-
`),
|
|
505
|
+
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],p=d===o,u=n.addresses[d],g=n.shieldedAddresses?.[d],m=p?k(L(d))+l(" (active)"):d;if(process.stderr.write(` ${m}
|
|
506
|
+
`),process.stderr.write(` ${l("unshielded")} ${re(u)}
|
|
507
|
+
`),g)process.stderr.write(` ${l("shielded ")} ${re(g)}
|
|
498
508
|
`);else process.stderr.write(` ${l("shielded ")} ${l("(unavailable)")}
|
|
499
509
|
`);if(c<a.length-1)process.stderr.write(`
|
|
500
510
|
`)}process.stderr.write(`
|
|
501
|
-
`+
|
|
511
|
+
`+V()+`
|
|
502
512
|
|
|
503
513
|
`),process.stderr.write(` ${l("created")} ${n.createdAt}
|
|
504
514
|
`),process.stderr.write(` ${l("file ")} ${r}
|
|
505
|
-
`),process.stderr.write(` ${l("active ")} ${s?
|
|
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(
|
|
511
|
-
`),process.stderr.write(
|
|
512
|
-
`),process.stderr.write(
|
|
513
|
-
`),process.stderr.write(
|
|
515
|
+
`),process.stderr.write(` ${l("active ")} ${s?B("yes"):"no"}
|
|
516
|
+
|
|
517
|
+
`)}async function uh(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
518
|
+
Usage: midnight wallet remove <name>`);if(qa(t),R(e,"json")){_({wallet:t,removed:!0});return}process.stderr.write(B("✓")+` Wallet "${t}" removed
|
|
519
|
+
`)}async function ph(e){let t=A(e,"wallet")??e.positionals[0]??Nt(),r=se(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=R(e,"entropy"),i;if(o){if(!s.mnemonic)throw Error(`Wallet "${t}" has no mnemonic on file — cannot derive BIP-39 entropy.
|
|
520
|
+
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(oh(s.mnemonic,oi)).toString("hex")}if(R(e,"json")){let c={name:t,seed:s.seed};if(s.mnemonic)c.mnemonic=s.mnemonic;if(i)c.entropy=i;_(c);return}if(process.stderr.write(`
|
|
521
|
+
`),process.stderr.write(D(k(" ⚠ WARNING: This will display your wallet seed and mnemonic."))+`
|
|
522
|
+
`),process.stderr.write(D(" Anyone with this seed can access your funds.")+`
|
|
523
|
+
`),process.stderr.write(D(" Never share it. Never paste it into a website.")+`
|
|
514
524
|
`),process.stderr.write(`
|
|
515
|
-
`),!await
|
|
525
|
+
`),!await mh(" Show seed? (y/N) ")){process.stderr.write(l(" Cancelled.")+`
|
|
516
526
|
|
|
517
527
|
`);return}if(process.stdout.write(s.seed+`
|
|
518
528
|
`),process.stderr.write(`
|
|
@@ -525,52 +535,58 @@ Usage: midnight wallet remove <name>`);if(po(t),N(e,"json")){P({wallet:t,removed
|
|
|
525
535
|
`),process.stderr.write(l(" Note: seed and entropy derive DIFFERENT Midnight wallets from the")+`
|
|
526
536
|
`),process.stderr.write(l(" same mnemonic. Use the value your target project accepts.")+`
|
|
527
537
|
`);process.stderr.write(`
|
|
528
|
-
`)}function
|
|
538
|
+
`)}function mh(e){return new Promise((t)=>{let r=ia("readline"),n=r.createInterface({input:process.stdin,output:process.stderr});n.question(e,(s)=>{n.close(),t(s.trim().toLowerCase()==="y")})})}var ws=T(()=>{Fe();Qe();Ce();sr();Ie();ue()});var jd={};be(jd,{default:()=>Ud});function ai(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 ii(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 ys(e){let t=`${Tn}${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 wh(e){let t=A(e,"network");if(t)return t;try{await Promise.resolve().then(() => tr());let n=De();if(n.network&&Le(n.network))return n.network}catch{}return}async function bs(e,t={}){let r=new AbortController,n=setTimeout(()=>r.abort(),hh),s=Date.now();try{return{response:await fetch(e,{...t,signal:r.signal}),latencyMs:Date.now()-s}}finally{clearTimeout(n)}}async function yh(e){let t=new Date().toISOString();try{let{response:r,latencyMs:n}=await bs(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>Ss?"degraded":"up",latencyMs:n,lastChecked:t,...o!==void 0?{blockHeight:o}:{},...n>Ss?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function Sh(e){let t=new Date().toISOString(),r=e.replace(/^wss:/,"https:").replace(/^ws:/,"http:");try{let{response:n,latencyMs:s}=await bs(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",p;if(c)d="degraded",p="Node is syncing";else if(a===0)d="degraded",p="No peers";return{status:d,latencyMs:s,lastChecked:t,peers:a,isSyncing:c,...p?{notes:p}:{}}}catch(n){return{status:"down",latencyMs:0,lastChecked:t,notes:n.message}}}async function bh(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 bs(e);if(!r.ok)return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`};return{status:n>Fd?"degraded":"up",latencyMs:n,lastChecked:t,...n>Fd?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function vh(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 bs(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>Ss?"degraded":"up",latencyMs:n,lastChecked:t,...n>Ss?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function Ld(e){if(!Le(e))return{};let t=Hr(e),r=fh[e];if(!r)return{};let[n,s,o,i]=await Promise.all([yh(t.indexer),Sh(t.node),bh(r.faucet),vh(r.explorer)]);return{indexer:n,rpc:s,faucet:o,explorer:i}}function kh(e,t,r){process.stderr.write(`
|
|
529
539
|
`+k(e)+`
|
|
530
540
|
`),process.stderr.write(l(" "+"─".repeat(62))+`
|
|
531
|
-
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(
|
|
532
|
-
`)}else if(i){let c=
|
|
533
|
-
`)}}}function
|
|
534
|
-
`+
|
|
541
|
+
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(gh[s]??s).padEnd(18);if(o){let c=Md[o.status]??l("—"),d=o.latencyMs>0?l(` ${o.latencyMs}ms`):"",p=o.notes?l(` — ${o.notes}`):"",u="";if(i&&i.status!==o.status&&i.status!=="unknown")u=l(` (canary: ${i.status}${i.lastChecked?" "+ai(i.lastChecked):""})`);process.stderr.write(` ${ft(a)}${c}${d}${p}${u}
|
|
542
|
+
`)}else if(i){let c=Md[i.status]??l("—"),d=i.latencyMs>0?l(` ${i.latencyMs}ms`):"",p=i.lastChecked?l(` (${ai(i.lastChecked)})`):"",u=i.notes?l(` — ${i.notes}`):"";process.stderr.write(` ${ft(a)}${c}${d}${p}${u}
|
|
543
|
+
`)}}}function Ch(e,t){let r=t?e.filter((n)=>n.affects.toLowerCase().includes(t.toLowerCase())):e;if(r.length===0)return;process.stderr.write(`
|
|
544
|
+
`+j("Known Issues")+`
|
|
535
545
|
|
|
536
|
-
`);for(let n of r)process.stderr.write(` ${
|
|
546
|
+
`);for(let n of r)process.stderr.write(` ${J(n.id.padEnd(28))}${n.summary}
|
|
537
547
|
`),process.stderr.write(` ${" ".repeat(28)}${l(n.status)}
|
|
538
|
-
`)}async function
|
|
539
|
-
`+
|
|
540
|
-
`),i?.lastUpdated)process.stderr.write(l(` Canary: ${
|
|
548
|
+
`)}async function Ud(e){let t=R(e,"json"),r=R(e,"all"),n=R(e,"watch"),s=await wh(e)??"preprod",o=G("Checking network status..."),i=null,a=null,c,d;if(r)d=["preprod","preview"];else d=[s];let[p,...u]=await Promise.all([Promise.all([ys("/api/status"),ys("/api/issues")]).catch((f)=>(c=f.message,null)),...d.map((f)=>Ld(f))]);if(p)[i,a]=p;o.stop("Done");let g={};for(let f=0;f<d.length;f++)g[d[f]]=u[f];if(t){let f={lastUpdated:i?.lastUpdated??null,dashboard:Tn,canaryAvailable:i!==null,networks:{}};for(let S of d){let w=g[S]??{},b=i?.networks[S],x={...b,...w};f.networks[S]={overall:ii(x),live:w,canary:b??null}}if(a){let S=r?void 0:d[0];f.issues=S?a.issues.filter((w)=>w.affects.toLowerCase().includes(S.toLowerCase())):a.issues}if(c)f.canaryError=c;_(f);let y=d.reduce((S,w)=>{let b={...i?.networks[w]??{},...g[w]??{}},x=ii(b);if(x==="down")return"down";if(x==="degraded"&&S!=="down")return"degraded";return S},"up");if(y==="down")process.exitCode=2;else if(y==="degraded")process.exitCode=1;return}let m=()=>{if(process.stderr.write(`
|
|
549
|
+
`+j("Midnight Network Status")+`
|
|
550
|
+
`),i?.lastUpdated)process.stderr.write(l(` Canary: ${ai(i.lastUpdated)}`)+" ");if(process.stderr.write(l("Live: just now")+`
|
|
541
551
|
`),c)process.stderr.write(l(` (Dashboard unreachable: ${c})`)+`
|
|
542
552
|
`);if(d.length===0){process.stderr.write(`
|
|
543
553
|
`+l("No network data available.")+`
|
|
544
554
|
|
|
545
|
-
`);return}for(let
|
|
546
|
-
`+
|
|
547
|
-
`),process.stderr.write(l(" Dashboard: ")+L(
|
|
548
|
-
|
|
549
|
-
`)};if(
|
|
550
|
-
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(
|
|
551
|
-
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((
|
|
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.
|
|
556
|
-
`),"approve";if(t.autoApproveReads
|
|
557
|
-
`),"approve";if(!process.stdin.isTTY)return process.stderr.write(
|
|
558
|
-
`),process.stderr.write(l(
|
|
559
|
-
`),"reject";if(
|
|
555
|
+
`);return}for(let f of d)kh(f,i?.networks[f],g[f]??{});if(a){let f=r?void 0:d[0];Ch(a.issues,f)}process.stderr.write(`
|
|
556
|
+
`+V()+`
|
|
557
|
+
`),process.stderr.write(l(" Dashboard: ")+L(Tn)+`
|
|
558
|
+
|
|
559
|
+
`)};if(m(),n){let f=setInterval(async()=>{try{let[y,...S]=await Promise.all([Promise.all([ys("/api/status"),ys("/api/issues")]).catch(()=>null),...d.map((w)=>Ld(w))]);if(y)[i,a]=y;for(let w=0;w<d.length;w++)g[d[w]]=S[w];process.stderr.write("\x1B[2J\x1B[H"),m()}catch{process.stderr.write(l(" Refresh failed — retrying in 30s")+`
|
|
560
|
+
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(f),process.exit(0)})})}let h=d.reduce((f,y)=>{let S={...i?.networks[y]??{},...g[y]??{}},w=ii(S);if(w==="down")return"down";if(w==="degraded"&&f!=="down")return"degraded";return f},"up");if(h==="down")process.exitCode=2;else if(h==="degraded")process.exitCode=1}var fh,gh,Md,hh=15000,Ss=5000,Fd=1e4;var Wd=T(()=>{we();ue();tt();fh={preprod:{faucet:"https://faucet.preprod.midnight.network/",explorer:"https://preprod.midnightexplorer.com/"},preview:{faucet:"https://faucet.preview.midnight.network/",explorer:null},undeployed:{faucet:"",explorer:""}},gh={indexer:"Indexer",rpc:"RPC Node",faucet:"Faucet",explorer:"Explorer",chain:"Chain",dust:"Dust Generation",wallet:"Wallet Ops",dapp:"DApp Flow"},Md={up:B("UP"),down:J("DOWN"),degraded:k("\x1B[33mDEGRADED\x1B[0m"),unknown:l("—")}});import{existsSync as ci,readFileSync as xh,readdirSync as Eh}from"node:fs";import{join as Sr,basename as Ah}from"node:path";function rt(e,t){let r=Sr(e,"compiler",vs);if(ci(r))return Hd(r,e,[]);for(let n of Bd){let s=n?Sr(e,n,"managed"):Sr(e,"managed");if(!ci(s))continue;let o;try{o=Eh(s).sort()}catch{continue}let i=o.filter((p)=>ci(Sr(s,p,"compiler",vs)));if(i.length===0)continue;let a;if(t){if(!i.includes(t))throw Error(`Contract "${t}" not found in ${s}
|
|
561
|
+
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((p)=>p!==a),d=Sr(s,a,"compiler",vs);return Hd(d,Sr(s,a),c)}throw Error(`No compiled contract found in ${e}
|
|
562
|
+
Expected: managed/<name>/compiler/${vs}
|
|
563
|
+
Searched: ${Bd.map((n)=>n?`${n}/managed/`:"managed/").join(", ")}
|
|
564
|
+
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function Hd(e,t,r){let n;try{n=JSON.parse(xh(e,"utf-8"))}catch(o){throw Error(`Failed to parse ${e}: ${o.message}`)}return{info:Th(n,e,t,r),infoPath:e}}function Th(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:Ah(r),managedDir:r,compilerVersion:o,languageVersion:i,runtimeVersion:a,circuits:c,witnesses:d,siblings:n}}function Je(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(Je).join(", ")}]`;case"Boolean":return"boolean";case"String":return"string";case"Vector":return e.types?.[0]?`${Je(e.types[0])}[]`:"unknown[]";case"Map":if(e.types&&e.types.length>=2)return`Map<${Je(e.types[0])}, ${Je(e.types[1])}>`;return"Map<unknown, unknown>";case"Set":return e.types?.[0]?`Set<${Je(e.types[0])}>`:"Set<unknown>";case"Option":return e.types?.[0]?`${Je(e.types[0])} | null`:"unknown | null";default:return e["type-name"]??"unknown"}}function Gd(e){let t=e.arguments.map((r)=>`${r.name}: ${Je(r.type)}`).join(", ");return`${e.name}(${t})`}function Kd(e){if(e.pure)return"pure";let t=["impure"];if(e.proof)t.push("proof");return t.join(", ")}function Jd(e){let t=e.arguments.map((s)=>`${s.name}: ${Je(s.type)}`).join(", "),r=Je(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:Je(r.type)})),returnType:Je(t["result-type"])})),witnesses:e.witnesses.map((t)=>({name:t.name,arguments:t.arguments.map((r)=>({name:r.name,type:Je(r.type)})),returnType:Je(t["result type"])}))}}var vs="contract-info.json",Bd;var fn=T(()=>{Bd=["","contract/src","contract","contracts/src","contracts","src"]});import*as qd from"node:readline";function zd(e,t){if(e.approveAll)return{reads:"auto",balancing:"auto",writes:"auto"};if(e.approveFees)return{reads:"auto",balancing:"fee-only",writes:"fee-only",feeLimits:{maxFeeSpecks:t.maxFeeSpecks.toString(),maxPending:t.maxPending}};return{reads:"auto",balancing:"prompt",writes:"prompt"}}function $h(e){return Nh.has(e)}function Ih(e){return Rh.has(e)}function _h(e){let t=[],r=e.dappName?`Request from "${e.dappName}"`:"DApp Request";if(t.push(k(r)),t.push(""),t.push(` ${l("Action:")} ${L(e.method)}`),t.push(` ${l("Network:")} ${e.network}`),e.details.length>0){t.push("");for(let n of e.details)t.push(` ${l(n.label+":")} ${n.value}`)}return t.push(""),t.push(` ${B("[A]pprove")} ${J("[R]eject")}`),Aa(t,"heavy")}function Ph(e,t){if(t.approveFees)return`--approve-fees approves only paying the Dust fee for an agent's own balanced transaction (and its submit); ${e.method} needs a terminal to approve`;return`${Ih(e.method)?"Balancing prompts like any other write":`${e.method} needs a terminal to approve`}: use --approve-all for non-interactive environments, or --approve-fees for a fee wallet that only pays an agent's Dust fee`}async function Xd(e,t={}){if(t.approveAll)return process.stderr.write(l(` Auto-approved: ${e.method}`)+`
|
|
565
|
+
`),"approve";if(t.approveFees&&e.feeOnly)return process.stderr.write(l(` Auto-approved (fee-only): ${e.method}`)+`
|
|
566
|
+
`),"approve";if(t.autoApproveReads&&$h(e.method))return process.stderr.write(l(` Auto-approved (read-only): ${e.method}`)+`
|
|
567
|
+
`),"approve";if(!process.stdin.isTTY)return process.stderr.write(J(" Cannot prompt for approval: stdin is not a TTY")+`
|
|
568
|
+
`),process.stderr.write(l(` ${Ph(e,t)}`)+`
|
|
569
|
+
`),"reject";if(gn)return process.stderr.write(J(" Rejected: another approval prompt is active")+`
|
|
560
570
|
`),"reject";process.stderr.write(`
|
|
561
|
-
`+
|
|
562
|
-
|
|
563
|
-
`),
|
|
564
|
-
`),"reject"}return new Promise((n)=>{let s=(o)=>{
|
|
565
|
-
`)}),c.on("connection",(u)=>{let
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
${
|
|
573
|
-
${
|
|
571
|
+
`+_h(e)+`
|
|
572
|
+
|
|
573
|
+
`),gn=!0;let r;try{r=qd.createInterface({input:process.stdin,output:process.stderr})}catch{return gn=!1,process.stderr.write(J(" Cannot create readline interface")+`
|
|
574
|
+
`),"reject"}return new Promise((n)=>{let s=(o)=>{gn=!1,r.close(),n(o)};r.on("close",()=>{if(gn)s("reject")}),r.question(D(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var Nh,Rh,gn=!1;var di=T(()=>{ue();Nh=new Set(["getShieldedBalances","getUnshieldedBalances","getDustBalance","getShieldedAddresses","getUnshieldedAddress","getDustAddress","getTxHistory","getConfiguration","getConnectionStatus"]),Rh=new Set(["balanceUnsealedTransaction","balanceSealedTransaction"])});import{WebSocketServer as Dh}from"ws";function Mh(e){if(li(e))return Oh[e.code]??-32603;return-32603}function li(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="DAppConnectorAPIError"}function Fh(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 ks(e,t){if(typeof t==="bigint")return t.toString();return t}function Lh(e,t){return t}function Uh(e){let t;try{t=JSON.parse(e,Lh)}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 Cs(e){let{port:t,handlers:r,onConnect:n,onDisconnect:s,onRequest:o,onResponse:i}=e,a=new Map,c=new Dh({port:t,host:"127.0.0.1"}),d=new Promise((u,g)=>{c.once("listening",()=>u()),c.once("error",g)});d.catch(()=>{}),c.on("error",(u)=>{process.stderr.write(`WebSocket server error: ${u.message}
|
|
575
|
+
`)}),c.on("connection",(u)=>{let g=`conn_${++jh}`,m={ws:u,id:g,connectedAt:new Date,authenticated:!1,requestCount:0,notify(y,S){if(u.readyState!==u.OPEN)return;let w={jsonrpc:"2.0",method:y,...S&&{params:S}};u.send(JSON.stringify(w,ks))}};a.set(g,m),n?.(m);let h=!1,f=()=>{if(h)return;h=!0,a.delete(g),s?.(m)};u.on("message",async(y)=>{let S=null,w,b,x=Date.now();try{w=Uh(y.toString("utf-8")),S=w.id,m.requestCount++,o?.(m,w);let I=Object.hasOwn(r,w.method)?r[w.method]:void 0;if(!I){let K={jsonrpc:"2.0",id:w.id,error:{code:-32601,message:`Method not found: ${w.method}`}};u.send(JSON.stringify(K,ks));return}b={notify:m.notify.bind(m),connectionId:g,requestId:w.id,metadata:{}};let O=await I(w.params??{},b),z=Date.now()-x;if(w.method==="connect"&&O&&typeof O==="object")m.authenticated=!0,m.networkId=O.networkId;let Q={jsonrpc:"2.0",id:w.id,result:O};u.send(JSON.stringify(Q,ks)),i?.(m,w,z,O,void 0,b.metadata)}catch(I){let O=Date.now()-x,z=I?.rpcCode??Mh(I),Q=I instanceof Error?I.message:"Internal error",K=li(I)?{type:I.type,code:I.code}:Fh(I),M={jsonrpc:"2.0",id:S,error:{code:z,message:Q,data:K}};if(u.send(JSON.stringify(M,ks)),w){let F={message:Q,code:li(I)?I.code:void 0};i?.(m,w,O,void 0,F,b?.metadata)}}}),u.on("close",f),u.on("error",()=>{f();try{u.close()}catch{}})});async function p(){for(let u of a.values())u.ws.close(1001,"Server shutting down");return a.clear(),new Promise((u,g)=>{c.close((m)=>{if(m)g(m);else u()})})}return{wss:c,connections:a,ready:d,close:p}}function ce(e,t){let r=Error(t);return r.type="DAppConnectorAPIError",r.code=e,r.reason=t,r}var Oh,jh=0;var xs=T(()=>{Oh={Rejected:-32000,PermissionRejected:-32001,Disconnected:-32002,InvalidRequest:-32602,InternalError:-32603}});function Yd(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}}function Zd(e){return Buffer.from(e).toString("hex")}function br(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 Wh(e,t){let r=/^(\d+)(?:\.(\d{1,15}))?$/.exec(e.trim());if(!r)throw new H(`${t} must be a positive DUST amount with at most ${Qd} decimals, e.g. 0.5`);let n=BigInt(r[1]),s=BigInt((r[2]??"").padEnd(Qd,"0")),o=n*el+s;if(o===0n)throw new H(`${t} must be greater than 0`);return o}function tl(e,t){let r={...ui};if(e!==void 0)r.maxFeeSpecks=Wh(e,"--max-fee");if(t!==void 0){if(!/^[1-9]\d*$/.test(t))throw new H("--max-pending must be a whole number of at least 1");r.maxPending=Number(t)}return r}function rl(e,t){if(e<=t.maxFeeSpecks)return;return`the estimated fee ${Me(e)} DUST is over --max-fee ${Me(t.maxFeeSpecks)} DUST`}function nl(e,t){if(e<t.maxPending)return;return`${e} balanced transactions are still waiting to be submitted (--max-pending ${t.maxPending})`}var el,Qd=15,ui;var pi=T(()=>{Fe();ue();el=10n**15n,ui={maxFeeSpecks:10n*el,maxPending:2}});import{Transaction as Bh}from"@midnightntwrk/ledger-v9";function mi(e,t){let r=[];r.push({label:"Tx size",value:Jh(e.length/2)});let n=Hh(e,t);if(n){let s=Gh(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 Hh(e,t){let r=Kh(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 Bh.deserialize(s,o,i,r).toString(!0)}catch{}return null}function Gh(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 Kh(e){return new Uint8Array(Buffer.from(e,"hex"))}function Jh(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 sl=()=>{};import{Transaction as ol,addressFromKey as il}from"@midnightntwrk/ledger-v9";function vr(e,t){return t==="unsealed"?ol.deserialize("signature","proof","pre-binding",e):ol.deserialize("signature","proof","binding",e)}function fi(e){return new Set([Vh,...e.intents?.keys()??[],...e.fallibleOffer?.keys()??[]])}function al(e,t){return[...e.intents??new Map].filter(([,r])=>r.ttl.getTime()<=t.getTime()).map(([r,n])=>({segment:r,ttl:n.ttl}))}function gi(e){let t=[];for(let[r,n]of e.intents??new Map){let s=[["guaranteed",n.guaranteedUnshieldedOffer],["fallible",n.fallibleUnshieldedOffer]];for(let[o,i]of s)i?.inputs.forEach((a,c)=>t.push({where:`intent ${r} ${o} unshielded input ${c}`,owner:a.owner,signed:i.signatures[c]!==void 0}))}return t}function cl(e,t){if(e.rewards!==void 0)return["it is a rewards claim, not a standard transaction"];let r=[],n=il(t);for(let{where:s,owner:o,signed:i}of gi(e)){if(il(o)===n)r.push(`${s} spends this wallet's own funds`);if(!i)r.push(`${s} is unsigned, so this wallet would sign it`)}for(let s of fi(e)){let o;try{o=e.imbalances(s)}catch(i){r.push(`segment ${s}'s balance could not be computed: ${i.message??i}`);continue}for(let[i,a]of o){if(i.tag==="dust"||a>=0n)continue;r.push(`segment ${s} is short ${-a} of ${i.tag} token ${i.raw}, which a Dust-only balance can't fund`)}}return r}var Vh=0;var hi=()=>{};function dl(e){let t=gi(e),r=t.filter((n)=>n.signed).length;if(r===0)return"none";return r===t.length?"all":"some"}function qh(e){return[...fi(e)].filter((t)=>[...e.imbalances(t)].some(([r,n])=>r.tag==="unshielded"&&n!==0n))}function ll(e,t){let r=dl(e);if(r==="some")throw new kr;if(r==="all"&&t){let n=qh(e);if(n.length>0)throw new wi(n)}}async function ul(e,t,r){if(t.type!=="UNBOUND_TRANSACTION")return e.signRecipe(t,r);let n=vr(t.baseTransaction.serialize(),"unsealed"),s=dl(n);if(s==="none")return e.signRecipe(t,r);if(s==="some")throw new kr;if(!t.balancingTransaction)return t;let o=await e.signRecipe({type:"UNPROVEN_TRANSACTION",protocolVersion:t.protocolVersion,transaction:t.balancingTransaction},r);if(o.type!=="UNPROVEN_TRANSACTION")throw Error(`The wallet SDK signed an unproven transaction into a ${o.type} recipe`);return{...t,balancingTransaction:o.transaction}}var kr,wi;var pl=T(()=>{hi();kr=class kr 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,kr.prototype)}};wi=class wi 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,wi.prototype)}}});async function ml(e,t){let r;try{r=await Vn(e,Xh,{hash:t},zh)}catch(o){throw new hn(t,o.message)}let n=r.transactions?.find((o)=>o.__typename==="RegularTransaction");if(!n)throw new hn(t,"the indexer has no such transaction");let s=n.transactionResult?.status;if(s!=="PARTIAL_SUCCESS")throw new hn(t,`the indexer reports it as ${s??"having no result"}, not a partial success`);return n.transactionResult?.segments??[]}var zh=1e4,Xh=`query ($hash: HexEncoded!) {
|
|
576
|
+
transactions(offset: { hash: $hash }) {
|
|
577
|
+
__typename
|
|
578
|
+
... on RegularTransaction { transactionResult { status segments { id success } } }
|
|
579
|
+
}
|
|
580
|
+
}`,hn;var fl=T(()=>{_o();hn=class hn extends Error{constructor(e,t){super(`Could not read the segment results of transaction ${e} from the indexer: ${t}`);this.name="SegmentResultsUnavailableError",Object.setPrototypeOf(this,hn.prototype)}}});import*as Cr from"rxjs";import{MidnightBech32m as yi,UnshieldedAddress as Yh,ShieldedAddress as Zh}from"@midnightntwrk/wallet-sdk/address-format";function qt(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 gl(e,t){switch(e.lifecycle.status){case"finalized":return{txHash:e.hash,txStatus:{status:"finalized",executionStatus:Qh(e,t)}};case"rejected":return{txHash:e.hash,txStatus:{status:"discarded"}};case"pending":return{txHash:e.hash,txStatus:{status:"pending"}}}}function Qh(e,t){switch(e.status){case"SUCCESS":return{0:"Success"};case"FAILURE":return{0:"Failure"};case"PARTIAL_SUCCESS":if(!t||t.length===0)throw Error(`Transaction ${e.hash} partly succeeded, but its segment results are missing`);return Object.fromEntries(t.map((r)=>[r.id,r.success?"Success":"Failure"]));case void 0:return{}}}function ew(e){if(e!=="schnorr")throw Error(`Unexpected signature scheme "${e}": mn signs with BIP-340 Schnorr only`);return"schnorr_bip340"}function As(e){let{bundle:t,networkConfig:r,approvalOptions:n,callbacks:s}=e,o=e.feeLimits??ui,{facade:i,keystore:a}=t,c=He(r.networkId),d,p,u=i.state().subscribe((E)=>{if(p=E.protocolVersion,E.isSynced)d=E});function g(){if(!d)throw ce("Disconnected","Wallet not synced yet");return d}function m(){if(!p)throw ce("Disconnected","Wallet not synced yet");let E=xc(p);if(E.length>0){let v=E.map((N)=>`${N} at ${p[N]}`).join(", ");throw ce("Disconnected",`This wallet can't take transactions until all three of its wallets are on ledger 9 (fork at ${gt.v9}); still behind: ${v}. Wait for them to sync past the fork and retry.`)}}let h=new Map;function f(E,v,N,P=!1){let U=h.get(E);if(!U)U=new Map,h.set(E,U);let X=setTimeout(async()=>{if(U.delete(v),U.size===0)h.delete(E);try{await i.revert(N)}catch{}process.stderr.write(l(` abandoned tx reverted (${E})`)+`
|
|
581
|
+
`)},Ca);U.set(v,{finalized:N,timer:X,feeOnly:P})}function y(E,v){let N=h.get(E);if(!N)return;let P=N.get(v);if(P)clearTimeout(P.timer),N.delete(v);if(N.size===0)h.delete(E)}async function S(E){let v=h.get(E);if(!v||v.size===0)return;h.delete(E);for(let[,N]of v){clearTimeout(N.timer);try{await i.revert(N.finalized)}catch{}}process.stderr.write(l(` reverted ${v.size} pending tx(s) on disconnect`)+`
|
|
582
|
+
`)}function w(){return new Date(Date.now()+En*60*1000)}async function b(E,v){v?.start("signing");let N;try{N=await ul(i,E,a.signDataAsync)}catch(Y){try{await i.revert(E)}catch{}if(Y instanceof kr)throw ce("InvalidRequest",Y.message);throw Y}v?.start("proving");let P,U,X=i.finalizeRecipe(N);try{U=await Promise.race([X,new Promise((Y,Pe)=>{P=setTimeout(()=>Pe(Error("ZK proof generation timed out")),xn)})])}catch(Y){try{await i.revert(E)}catch{}throw X.then((Pe)=>i.revert(Pe)).catch(()=>{}),Y}finally{clearTimeout(P)}return v?.complete(),{hex:Zd(U.serialize()),finalized:U}}function x(E,v){try{return i.adoptTransaction(br(E),v)}catch(N){throw ce("InvalidRequest",`The transaction could not be read at stage ${v} as this wallet's ledger version: ${qt(N)}`)}}async function I(E,v=[],N,P=!1){N?.notify("approval:pending",{method:E});let U=await Xd({method:E,network:r.networkId,details:v,dappName:N?.connectionId,feeOnly:P},n),X=U==="reject"?"rejected":"approved";if(N?.notify("approval:resolved",{method:E,result:X}),U==="reject")throw ce("Rejected",n.approveFees?`${Es}: this fee wallet (--approve-fees) approves without the operator only paying the Dust fee for an agent's own transaction and submitting a transaction it balanced that way on the same connection`:Es)}function O(E,v,N){if(N===!1)throw ce("InvalidRequest","This wallet is a fee wallet (--approve-fees): it only pays the Dust fee, so payFees: false leaves it nothing to do");let P;try{P=vr(br(E),v)}catch(X){throw ce("InvalidRequest",`The transaction could not be read as a proven ledger-9 ${v} transaction: ${qt(X)}`)}let U=cl(P,a.getPublicKey());if(U.length>0)throw ce("Rejected",`This wallet is a fee wallet (--approve-fees) and pays only the Dust fee; it refuses this transaction because ${U.join("; ")}`)}function z(E,v){let N;try{N=al(vr(br(E),v),new Date)}catch(P){throw ce("InvalidRequest",qt(P))}if(N.length>0){let P=N.map(({segment:U,ttl:X})=>`intent ${U}'s TTL (${X.toISOString()})`).join(", ");throw ce("InvalidRequest",`The transaction has expired: ${P} has passed. Build it again with a later TTL.`)}}function Q(E,v){try{ll(vr(br(E),"unsealed"),v)}catch(N){throw ce("InvalidRequest",qt(N))}}function K(){let E=0;for(let[,v]of h)E+=v.size;return E}function M(E){return ce("Rejected",`This wallet is a fee wallet (--approve-fees) and refuses this transaction: ${E}`)}let F=0;function ee(){let E=nl(K()+F,o);if(E)throw M(E);F++;let v=!1;return()=>{if(!v)v=!0,F--}}async function pe(E,v){let N=await Ve(()=>i.estimateTransactionFee(E,{ttl:v}));process.stderr.write(l(` fee-only: estimated fee ${Me(N)} DUST (limit ${Me(o.maxFeeSpecks)})`)+`
|
|
583
|
+
`);let P=rl(N,o);if(P)throw M(P)}async function le(E,v,N,P){let U=String(N.tx??"");if(!U)throw ce("InvalidRequest","tx is required");m();let X=N.options?.payFees,Y=n.approveFees===!0;if(Y)O(U,v,X);let Pe=Y?["dust"]:X===!1?["shielded","unshielded"]:"all",je=w(),ot=v==="unsealed"?x(U,"Unbound"):x(U,"Finalized");if(z(U,v),v==="unsealed")Q(U,Pe==="all"||Pe.includes("unshielded"));let it=Y?ee():void 0;try{if(Y)await pe(ot,je);let at=Oe(E,P);at.start("approve"),await I(E,mi(U,v),P,Y),at.start("building");let Xt={ttl:je,tokenKindsToBalance:Pe},Vs;if(v==="unsealed"){let qs=ot;Vs=await Ve(()=>i.balanceUnboundTransaction(qs,Xt))}else{let qs=ot;Vs=await Ve(()=>i.balanceFinalizedTransaction(qs,Xt))}let{hex:oa,finalized:Qp}=await b(Vs,at);return f(P.connectionId,oa,Qp,Y),P.metadata.phases=at.getTimings(),{tx:oa}}finally{it?.()}}function ge(E){return yi.encode(c,E).asString()}function te(E){let v={};for(let N of E){let P=N.kind;if(P!=="shielded"&&P!=="unshielded")throw ce("InvalidRequest",`Invalid output kind: "${P}" — must be "shielded" or "unshielded"`);if(!v[P])v[P]=[];let U=BigInt(N.value),X;if(P==="unshielded")X=yi.parse(N.recipient).decode(Yh,c);else X=yi.parse(N.recipient).decode(Zh,c);v[P].push({type:N.type,receiverAddress:X,amount:U})}return Object.entries(v).map(([N,P])=>({type:N,outputs:P}))}function Oe(E,v){return Yd({onStart:(N)=>{let P=v?.connectionId??"unknown";s?.onPhaseStart?.(P,E,N),v?.notify("progress",{method:E,phase:N,status:"started"})},onComplete:(N,P)=>{let U=v?.connectionId??"unknown";s?.onPhaseComplete?.(U,E,N,P),v?.notify("progress",{method:E,phase:N,status:"completed",durationMs:P})}})}function Ae(){return d!==void 0&&yt(d)}async function Se(E){return new Promise((v)=>{if(Ae()){v(!0);return}let N=i.state().pipe(Cr.filter(()=>Ae()),Cr.take(1),Cr.timeout(E)).subscribe({next:()=>{N.unsubscribe(),v(!0)},error:()=>{N.unsubscribe(),v(!1)}})})}function st(E){return ce("InternalError",`No Dust is free to pay the fee (${qt(E)}). Each balanced transaction reserves a whole Dust coin until it is submitted and on chain, or released when its connection closes or it expires; ${K()} balanced transaction(s) are waiting to be submitted on this server. Retry once they settle. To pay for more transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.`)}async function Ve(E){for(let v=1;v<=Fr;v++)try{return await E()}catch(N){let P=String(N?.message??N??"");if(!yc(N))throw N;if(v===Fr)throw st(N);if(process.stderr.write(l(` dust unavailable, waiting for recovery (${v}/${Fr})... [${P.slice(0,60)}]`)+`
|
|
584
|
+
`),!await Se(ro)&&v<Fr)await new Promise((X)=>setTimeout(X,ro))}throw Error("unreachable")}let me={connect:async(E)=>{let v=String(E.networkId??"");if(v.toLowerCase()!==r.networkId.toLowerCase())throw ce("InvalidRequest",`Network mismatch: wallet is on ${r.networkId}, requested ${v}`);return{networkId:r.networkId}},getUnshieldedBalances:async()=>g().unshielded.balances,getShieldedBalances:async()=>g().shielded.balances,getDustBalance:async()=>{let v=g().dust.balance(new Date);return{cap:v,balance:v}},getUnshieldedAddress:async()=>{let E=g();return{unshieldedAddress:ge(E.unshielded.address)}},getShieldedAddresses:async()=>{let v=g().shielded.address;return{shieldedAddress:ge(v),shieldedCoinPublicKey:v.coinPublicKeyString(),shieldedEncryptionPublicKey:v.encryptionPublicKeyString()}},getDustAddress:async()=>{let E=g();return{dustAddress:ge(E.dust.address)}},getTxHistory:async(E)=>{g();let v=Number(E.pageNumber??0),N=Number(E.pageSize??20),P=v*N,U=await i.getAllFromTxHistory(),X=[];for(let Y of U.slice(P,P+N)){if(Y.lifecycle.status!=="finalized"||Y.status!=="PARTIAL_SUCCESS"){X.push(gl(Y));continue}try{X.push(gl(Y,await ml(r.indexer,Y.hash)))}catch(Pe){throw ce("InternalError",qt(Pe))}}return X},getConfiguration:async()=>({indexerUri:r.indexer,indexerWsUri:r.indexerWS,proverServerUri:r.proofServer,substrateNodeUri:r.node,networkId:r.networkId}),getConnectionStatus:async()=>({status:"connected",networkId:c}),makeTransfer:async(E,v)=>{let N=E.desiredOutputs;if(!Array.isArray(N)||N.length===0)throw ce("InvalidRequest","desiredOutputs must be a non-empty array");m();let P=Oe("makeTransfer",v),U=N.map((it,at)=>({label:`Output ${at+1}`,value:`${it.value} → ${String(it.recipient).slice(0,20)}... (${it.kind})`}));P.start("approve"),await I("makeTransfer",U,v),P.start("building");let X=te(N),Y=E.options?.payFees??!0,Pe=await Ve(()=>i.transferTransaction(X,{ttl:w(),payFees:Y})),{hex:je,finalized:ot}=await b(Pe,P);return f(v.connectionId,je,ot),v.metadata.phases=P.getTimings(),{tx:je}},submitTransaction:async(E,v)=>{let N=String(E.tx??"");if(!N)throw ce("InvalidRequest","tx is required");m();let P=Oe("submitTransaction",v),U=n.approveFees===!0&&h.get(v.connectionId)?.get(N)?.feeOnly===!0;P.start("approve");try{await I("submitTransaction",mi(N,"sealed"),v,U)}catch(Y){let je=h.get(v.connectionId)?.get(N);if(je)try{await i.revert(je.finalized)}catch{}throw y(v.connectionId,N),Y}let X=x(N,"Finalized");P.start("submitting");try{let Y=await i.submitTransaction(X);return P.complete(),y(v.connectionId,N),v.metadata.phases=P.getTimings(),{txHash:Y}}catch(Y){P.complete();let je=h.get(v.connectionId)?.get(N);if(je)try{await i.revert(je.finalized)}catch{}y(v.connectionId,N);let ot=qt(Y),it=Error(`Transaction submission failed: ${ot}`);throw it.cause=Y,it}},balanceUnsealedTransaction:(E,v)=>le("balanceUnsealedTransaction","unsealed",E,v),balanceSealedTransaction:(E,v)=>le("balanceSealedTransaction","sealed",E,v),makeIntent:async(E,v)=>{let{desiredInputs:N,desiredOutputs:P,options:U}=E;if(!U)throw ce("InvalidRequest","options is required for makeIntent");m();let X=Oe("makeIntent",v);X.start("approve"),await I("makeIntent",[],v),X.start("building");let Y={};if(Array.isArray(N))for(let at of N){let Xt=at.kind;if(!Y[Xt])Y[Xt]={};Y[Xt][at.type]=BigInt(at.value)}let Pe=te(P??[]),je=await Ve(()=>i.initSwap(Y,Pe,{ttl:w(),payFees:U.payFees??!0})),{hex:ot,finalized:it}=await b(je,X);return f(v.connectionId,ot,it),v.metadata.phases=X.getTimings(),{tx:ot}},signData:async(E,v)=>{let N=String(E.data??""),P=E.options;if(!N||!P?.encoding)throw ce("InvalidRequest","data and options.encoding are required");if(P.keyType&&P.keyType!=="unshielded")throw ce("InvalidRequest",`Unsupported keyType: "${P.keyType}" — only "unshielded" is supported`);await I("signData",[{label:"Encoding",value:P.encoding},{label:"Data",value:N.length>64?N.slice(0,64)+"...":N}],v);let U;switch(P.encoding){case"hex":U=br(N);break;case"base64":U=new Uint8Array(Buffer.from(N,"base64"));break;case"text":U=new Uint8Array(Buffer.from(N,"utf-8"));break;default:throw ce("InvalidRequest",`Unknown encoding: ${P.encoding}`)}let X=await a.signDataAsync(U),Y=a.getPublicKey();return{data:N,signature:X.value,verifyingKey:Y.value,scheme:ew(X.tag)}},getProvingProvider:async()=>({provingProvider:"ready",proverServerUri:r.proofServer}),hintUsage:async(E)=>{let v=E.methodNames??[];process.stderr.write(l(` DApp hints usage: ${v.join(", ")}`)+`
|
|
585
|
+
`)}};function fe(){u.unsubscribe();for(let[,E]of h)for(let[,v]of E)clearTimeout(v.timer);h.clear()}function qe(){for(let[,E]of h)if(E.size>0)return!0;return!1}return{handlers:me,revertPendingTxs:S,hasPendingTxs:qe,dispose:fe}}var Es="User rejected the request";var Si=T(()=>{ze();we();di();xs();Tt();on();pi();sl();hi();pl();fl();Kt();ue()});import{Socket as tw}from"node:net";function hl(e){let{name:t,config:r}=de({args:{command:"serve",subcommand:void 0,positionals:[],flags:{...e.network?{network:e.network}:{},...$n(e.endpoints??{})}}});return Re(r,e.endpoints??{},t),{networkName:t,networkConfig:r}}function rw(e,t){let r=(s,o)=>s!==void 0&&s.replace(/\/+$/,"")===o.replace(/\/+$/,""),n=[];if(!r(e.substrateNodeUri,t.node))n.push(`node ${e.substrateNodeUri} (need ${t.node})`);if(!r(e.indexerWsUri,t.indexerWS))n.push(`indexer ${e.indexerWsUri} (need ${t.indexerWS})`);return n.length>0?n.join(", "):void 0}function nw(e){return new Promise((t)=>{let r=new tw;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 sw(e){let r=(await wl(e,"getConnectionStatus"))?.networkId;return typeof r==="string"?r:null}async function ow(e){let t=await wl(e,"getConfiguration");return t&&typeof t==="object"?t:null}async function wl(e,t){let r=(await import("ws")).default;return new Promise((n)=>{let s=new r(`ws://127.0.0.1:${e}`),o=setTimeout(()=>{try{s.close()}catch{}n(null)},2000);s.on("open",()=>{s.send(JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:{}}))}),s.on("message",(i)=>{clearTimeout(o);try{let a=JSON.parse(i.toString());s.close(),n(a?.result??null)}catch{s.close(),n(null)}}),s.on("error",()=>{clearTimeout(o),n(null)})})}async function Ts(e){let t=e.port??Mt,r=(e.network??"undeployed").toLowerCase(),n=e.onMessage??(()=>{});if(await nw(t)){let s=await sw(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.`);let i=await ow(t),a=i?rw(i,hl(e).networkConfig):"its endpoints could not be read";if(a)throw Error(`mn serve on port ${t} is on a different ${o} chain: ${a}. Stop it first (\`pkill -f 'mn serve'\`) and retry.`);return n(`Reusing existing mn serve on port ${t}`),{port:t,async stop(){}}}return iw(e)}async function iw(e){let t=e.port??Mt,r=e.onMessage??(()=>{}),n=ae(se(e.wallet)),s=Buffer.from(n.seed,"hex"),{networkName:o,networkConfig:i}=hl(e);await ut(o,i);let a=n.addresses[o],c=xe((h,f)=>{r(`SDK: ${f}`)}),d=_e();r("Building wallet facade...");let p=It(a,o),u=await dt(s,i,p);r("Syncing wallet..."),await $t(u,{onProgress:(h,f)=>{if(f>0){let y=Math.min(Math.round(h/f*100),100);r(`Syncing wallet... ${y}%`)}}}),r("Wallet synced"),r("Waiting for dust..."),await ar(u),r("Dust ready");try{await Xe(a,o,u.facade)}catch{}let g=As({bundle:u,networkConfig:i,approvalOptions:{approveAll:!0,autoApproveReads:!0},callbacks:{onPhaseStart:(h,f,y)=>{r(`${y}...`)},onPhaseComplete:(h,f,y,S)=>{r(`${y} ${Math.round(S)}ms`)}}}),m=Cs({port:t,handlers:g.handlers,onConnect:(h)=>{r(`connected ${h.id}`)},onDisconnect:(h)=>{r(`disconnected ${h.id}`),g.revertPendingTxs(h.id).catch(()=>{})},onRequest:(h,f)=>{r(`${h.id} → ${f.method}`)},onResponse:(h,f,y,S,w)=>{if(w)r(`${h.id} ← ${f.method} FAILED: ${w.message}`);else r(`${h.id} ← ${f.method} (${Math.round(y)}ms)`)}});try{await m.ready}catch(h){throw g.dispose(),await m.close(),await Ke(u),c(),d(),Error(`Could not start mn serve on port ${t}: ${h.message}`)}return r(`Server ready on ws://localhost:${t}`),{port:t,async stop(){m.close(),g.dispose(),d(),c();try{await Ke(u)}catch{}}}}var bi=T(()=>{Ie();Ce();Kt();we();ze();_t();Pt();Si();xs()});import{existsSync as yl}from"node:fs";import{join as Sl}from"node:path";function Rs(e){for(let t of Ns){let r=Sl(e,t);if(yl(r))return r}return null}function cw(e){for(let t of aw){let r=Sl(e,t);if(yl(r))return r}return null}function $s(e){let{projectRoot:t,witnessNames:r}=e,n=cw(t),s=[`Contract declares ${r.length} witness(es): ${r.join(", ")}`,"but no compiled witnesses module was found.","",`Searched (relative to ${t}):`,...Ns.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(`
|
|
586
|
+
`)}var Ns,aw;var Is=T(()=>{Ns=["dist/witnesses.js","src/witnesses.js","contract/dist/witnesses.js","contract/src/witnesses.js"],aw=["src/witnesses.ts","contract/src/witnesses.ts"]});function _s(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(_s)}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]=_s(e[r]);return t}return e}function bl(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 dw}from"node:child_process";import{writeFileSync as lw,unlinkSync as vl,existsSync as Ps,symlinkSync as kl}from"node:fs";import{join as wn,dirname as Cl}from"node:path";import{fileURLToPath as uw}from"node:url";function pw(){let e=Cl(uw(import.meta.url));for(let t=0;t<8;t++){let r=wn(e,"node_modules");if(Ps(r))return r;let n=Cl(e);if(n===e)break;e=n}return null}async function xr(e){let t=hw(e),r=await ki(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`State script returned unexpected output:
|
|
587
|
+
${r}`)}}async function Ds(e){let t=fw(e),r=e.privateStateSecretKey?{MN_PRIVATE_STATE_SECRET:e.privateStateSecretKey}:void 0,n=await ki(e.dappDir,t,e.onMessage,r);try{return JSON.parse(n)}catch{throw Error(`Deploy script returned unexpected output:
|
|
588
|
+
${n}`)}}async function Os(e){let t=gw(e),r=await ki(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`Call script returned unexpected output:
|
|
589
|
+
${r}`)}}function xl(e){return`
|
|
574
590
|
import WebSocket from 'ws';
|
|
575
591
|
|
|
576
592
|
const RPC_URL = 'ws://127.0.0.1:${e}';
|
|
@@ -611,37 +627,24 @@ function rpcCall(method, params = {}) {
|
|
|
611
627
|
function rpcClose() {
|
|
612
628
|
if (rpcWs) rpcWs.close();
|
|
613
629
|
}
|
|
614
|
-
`}function
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
async balanceTx(tx, ttl) {
|
|
625
|
-
const { toHex } = await import('@midnight-ntwrk/midnight-js-utils');
|
|
626
|
-
const txHex = toHex(tx.serialize());
|
|
627
|
-
const result = await rpcCall('balanceUnsealedTransaction', { tx: txHex });
|
|
628
|
-
|
|
629
|
-
const { fromHex } = await import('@midnight-ntwrk/midnight-js-utils');
|
|
630
|
-
const { Transaction } = await import('@midnight-ntwrk/midnight-js-types');
|
|
631
|
-
const bytes = fromHex(result.tx);
|
|
632
|
-
return Transaction.deserialize('signature', 'proof', 'binding', bytes);
|
|
633
|
-
},
|
|
634
|
-
async submitTx(tx) {
|
|
635
|
-
const { toHex } = await import('@midnight-ntwrk/midnight-js-utils');
|
|
636
|
-
const txHex = toHex(tx.serialize());
|
|
637
|
-
await rpcCall('submitTransaction', { tx: txHex });
|
|
638
|
-
return tx.identifiers()[0];
|
|
630
|
+
`}function Al(){return`
|
|
631
|
+
const walletState = await rpcCall('getShieldedAddresses', {});
|
|
632
|
+
|
|
633
|
+
const walletProvider = createWalletProvider({
|
|
634
|
+
getCoinPublicKey: () => walletState.shieldedCoinPublicKey,
|
|
635
|
+
getEncryptionPublicKey: () => walletState.shieldedEncryptionPublicKey,
|
|
636
|
+
// ttl is ignored: mn serve applies its own TTL when balancing.
|
|
637
|
+
async balanceTx(tx) {
|
|
638
|
+
const result = await rpcCall('balanceUnsealedTransaction', { tx: toHex(tx.serialize()) });
|
|
639
|
+
return Transaction.deserialize('signature', 'proof', 'binding', fromHex(result.tx));
|
|
639
640
|
},
|
|
640
|
-
};
|
|
641
|
+
});
|
|
641
642
|
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
643
|
+
const midnightProvider = createMidnightProvider(async (tx) => {
|
|
644
|
+
await rpcCall('submitTransaction', { tx: toHex(tx.serialize()) });
|
|
645
|
+
return tx.identifiers()[0];
|
|
646
|
+
});
|
|
647
|
+
`}function Tl(e,t){return`
|
|
645
648
|
import { pathToFileURL } from 'node:url';
|
|
646
649
|
import { resolve } from 'node:path';
|
|
647
650
|
import { CompiledContract } from '@midnight-ntwrk/compact-js';
|
|
@@ -655,7 +658,7 @@ const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract',
|
|
|
655
658
|
// Both relative-to-cwd locations and contract/<...> locations are checked
|
|
656
659
|
// so mn dev (which chdirs into the contract sub-package) and mn contract
|
|
657
660
|
// deploy run from a workspace root both work.
|
|
658
|
-
const WITNESS_CANDIDATES = ${JSON.stringify(
|
|
661
|
+
const WITNESS_CANDIDATES = ${JSON.stringify(Ns)};
|
|
659
662
|
let witnesses;
|
|
660
663
|
let createPrivateState;
|
|
661
664
|
for (const p of WITNESS_CANDIDATES) {
|
|
@@ -686,7 +689,7 @@ if (!witnesses) {
|
|
|
686
689
|
// Uses a deterministic seed derived from the wallet so post/takeDown use the same key.
|
|
687
690
|
// The private state provider (leveldb) persists between calls, but initialPrivateState
|
|
688
691
|
// is the fallback when no stored state exists yet.
|
|
689
|
-
${
|
|
692
|
+
${mw}
|
|
690
693
|
function makeInitialPrivateState() {
|
|
691
694
|
if (createPrivateState) {
|
|
692
695
|
// Secret precedence (see resolvePrivateStateSecretKey, injected above via
|
|
@@ -712,46 +715,42 @@ const compiled = witnesses
|
|
|
712
715
|
CompiledContract.withVacantWitnesses,
|
|
713
716
|
(c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR),
|
|
714
717
|
);
|
|
715
|
-
`}function
|
|
716
|
-
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
717
|
-
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
718
|
-
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
719
|
-
import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';
|
|
720
|
-
|
|
718
|
+
`}function Nl(e,t){return`
|
|
721
719
|
const zkConfigProvider = new NodeZkConfigProvider(MANAGED_DIR);
|
|
722
720
|
|
|
723
721
|
const providers = {
|
|
724
722
|
privateStateProvider: levelPrivateStateProvider({
|
|
725
|
-
privateStateStoreName: ${JSON.stringify(
|
|
723
|
+
privateStateStoreName: ${JSON.stringify(t)},
|
|
726
724
|
privateStoragePasswordProvider: () => Promise.resolve('mn-contract-default-pwd-16ch'),
|
|
727
725
|
accountId: 'mn-contract-runner',
|
|
728
726
|
}),
|
|
729
|
-
publicDataProvider: indexerPublicDataProvider(
|
|
730
|
-
${JSON.stringify(
|
|
731
|
-
${JSON.stringify(
|
|
732
|
-
),
|
|
727
|
+
publicDataProvider: indexerPublicDataProvider({
|
|
728
|
+
queryURL: ${JSON.stringify(e.indexer)},
|
|
729
|
+
subscriptionURL: ${JSON.stringify(e.indexerWS??e.indexer.replace("http","ws"))},
|
|
730
|
+
}),
|
|
733
731
|
zkConfigProvider,
|
|
734
|
-
proofProvider: httpClientProofProvider(${JSON.stringify(
|
|
732
|
+
proofProvider: httpClientProofProvider({ url: ${JSON.stringify(e.proofServer)}, zkConfigProvider }),
|
|
735
733
|
walletProvider,
|
|
736
|
-
midnightProvider
|
|
734
|
+
midnightProvider,
|
|
737
735
|
};
|
|
738
|
-
`}function
|
|
736
|
+
`}function fw(e){let t=e.privateStateKey??`${e.contractName}PrivateState`,r=JSON.stringify(e.args??[]);return`
|
|
739
737
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
740
738
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
741
739
|
|
|
742
|
-
${
|
|
743
|
-
${
|
|
740
|
+
${xl(e.servePort)}
|
|
741
|
+
${Tl(e.contractName,e.managedDir)}
|
|
744
742
|
|
|
745
743
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
746
744
|
await rpcConnect();
|
|
747
745
|
process.stderr.write('Connected\\n');
|
|
748
746
|
|
|
749
|
-
${
|
|
750
|
-
${
|
|
747
|
+
${El}
|
|
748
|
+
${Al()}
|
|
749
|
+
${Nl(e.networkConfig,t)}
|
|
751
750
|
|
|
752
751
|
import { deployContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
753
752
|
|
|
754
|
-
${
|
|
753
|
+
${Rl}
|
|
755
754
|
const constructorArgs = (${r}).map(coerceArg);
|
|
756
755
|
process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n');
|
|
757
756
|
const deployed = await deployContract(providers, {
|
|
@@ -767,19 +766,20 @@ process.stderr.write('Deploy complete: ' + address + '\\n');
|
|
|
767
766
|
console.log(JSON.stringify({ contractAddress: address }));
|
|
768
767
|
rpcClose();
|
|
769
768
|
process.exit(0);
|
|
770
|
-
`}function
|
|
769
|
+
`}function gw(e){let t=e.privateStateKey??`${e.contractName}PrivateState`;return`
|
|
771
770
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
772
771
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
773
772
|
|
|
774
|
-
${
|
|
775
|
-
${
|
|
773
|
+
${xl(e.servePort)}
|
|
774
|
+
${Tl(e.contractName,e.managedDir)}
|
|
776
775
|
|
|
777
776
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
778
777
|
await rpcConnect();
|
|
779
778
|
process.stderr.write('Connected\\n');
|
|
780
779
|
|
|
781
|
-
${
|
|
782
|
-
${
|
|
780
|
+
${El}
|
|
781
|
+
${Al()}
|
|
782
|
+
${Nl(e.networkConfig,t)}
|
|
783
783
|
|
|
784
784
|
import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
785
785
|
|
|
@@ -792,14 +792,14 @@ const deployed = await findDeployedContract(providers, {
|
|
|
792
792
|
});
|
|
793
793
|
|
|
794
794
|
process.stderr.write('Calling ${e.circuit}...\\n');
|
|
795
|
-
${
|
|
795
|
+
${Rl}
|
|
796
796
|
const args = (${JSON.stringify(e.args??[])}).map(coerceArg);
|
|
797
797
|
await deployed.callTx.${e.circuit}(...args);
|
|
798
798
|
|
|
799
799
|
console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(e.circuit)} }));
|
|
800
800
|
rpcClose();
|
|
801
801
|
process.exit(0);
|
|
802
|
-
`}function
|
|
802
|
+
`}function hw(e){return`
|
|
803
803
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
804
804
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
805
805
|
|
|
@@ -818,10 +818,10 @@ if (typeof contractMod.ledger !== 'function') {
|
|
|
818
818
|
}
|
|
819
819
|
|
|
820
820
|
process.stderr.write('Querying contract state...\\n');
|
|
821
|
-
const provider = indexerPublicDataProvider(
|
|
822
|
-
${JSON.stringify(e.networkConfig.indexer)},
|
|
823
|
-
${JSON.stringify(e.networkConfig.indexerWS??e.networkConfig.indexer.replace("http","ws"))},
|
|
824
|
-
);
|
|
821
|
+
const provider = indexerPublicDataProvider({
|
|
822
|
+
queryURL: ${JSON.stringify(e.networkConfig.indexer)},
|
|
823
|
+
subscriptionURL: ${JSON.stringify(e.networkConfig.indexerWS??e.networkConfig.indexer.replace("http","ws"))},
|
|
824
|
+
});
|
|
825
825
|
|
|
826
826
|
const contractState = await provider.queryContractState(${JSON.stringify(e.contractAddress)});
|
|
827
827
|
if (!contractState) {
|
|
@@ -862,20 +862,27 @@ for (const key of Object.keys(state)) {
|
|
|
862
862
|
|
|
863
863
|
console.log(JSON.stringify({ fields, maps }));
|
|
864
864
|
process.exit(0);
|
|
865
|
-
`}function
|
|
866
|
-
`,r?.(h)}),
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
865
|
+
`}function yw(e){if(!vi)return[];let t=[];if(!Ps(e)){try{kl(vi,e),t.push(e)}catch{}return t}for(let r of ww){let n=wn(vi,r),s=wn(e,r);if(!Ps(n)||Ps(s))continue;try{kl(n,s),t.push(s)}catch{}}return t}async function ki(e,t,r,n){let s=wn(e,"node_modules"),o=yw(s),i=wn(e,`.mn-contract-${Date.now()}.mjs`);lw(i,t);let a=()=>{try{vl(i)}catch{}for(let c of o.slice().reverse())try{vl(c)}catch{}};return new Promise((c,d)=>{let p=dw("node",[i],{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1",...n}}),u="",g="";p.stdout?.on("data",(m)=>{u+=m.toString()}),p.stderr?.on("data",(m)=>{let h=m.toString().trim();if(h)g+=h+`
|
|
866
|
+
`,r?.(h)}),p.on("close",(m)=>{if(a(),m!==0){d(Error(g.trim()||`Script exited with code ${m}`));return}c(u.trim())}),p.on("error",(m)=>{a(),d(m)})})}var vi,El=`
|
|
867
|
+
import { createWalletProvider, createMidnightProvider, Transaction } from '@midnight-ntwrk/midnight-js-types';
|
|
868
|
+
import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils';
|
|
869
|
+
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
870
|
+
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
871
|
+
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
872
|
+
import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';
|
|
873
|
+
`,mw,Rl,ww;var yn=T(()=>{Is();vi=pw();mw=`
|
|
874
|
+
const resolvePrivateStateSecretKey = (${bl.toString()});
|
|
875
|
+
`;Rl=`
|
|
876
|
+
const coerceArg = (${_s.toString()});
|
|
877
|
+
`;ww=["@midnight-ntwrk","ws"]});import{indexerPublicDataProvider as Sw}from"@midnight-ntwrk/midnight-js-indexer-public-data-provider";function $l(e){return Sw({queryURL:e.indexer,subscriptionURL:e.indexerWS??e.indexer.replace("http","ws")})}var Il=()=>{};var Ol={};be(Ol,{default:()=>Er});import{resolve as Ms}from"node:path";function Sn(){return{update(){},stop(){},fail(){},log(){}}}function bw(e){return _l.includes(e)}async function Er(e,t){let r=e.subcommand;if(!r||!bw(r))throw new H(`Usage: midnight contract <${_l.join("|")}>
|
|
871
878
|
|
|
872
879
|
inspect Show circuits, witnesses, and types for a compiled contract
|
|
873
880
|
deploy Deploy a contract to the network
|
|
874
881
|
call Call a circuit on a deployed contract
|
|
875
882
|
state Read the ledger state of a deployed contract
|
|
876
883
|
|
|
877
|
-
Run "midnight help contract" for more info.`);switch(r){case"inspect":return
|
|
878
|
-
`+
|
|
884
|
+
Run "midnight help contract" for more info.`);switch(r){case"inspect":return vw(e);case"deploy":return kw(e);case"call":return xw(e);case"state":return Ew(e)}}function Fs(e){let t=A(e,"managed"),r=A(e,"path");return Ms(t??r??process.cwd())}async function vw(e){let t=R(e,"json"),r=Fs(e),n=A(e,"name"),{info:s}=rt(r,n);if(t){_(Vd(s));return}if(process.stderr.write(`
|
|
885
|
+
`+j(`Contract: ${s.name}`)+`
|
|
879
886
|
|
|
880
887
|
`),process.stderr.write(C("Compiler",s.compilerVersion)+`
|
|
881
888
|
`),process.stderr.write(C("Language",s.languageVersion)+`
|
|
@@ -883,85 +890,85 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return Nh(
|
|
|
883
890
|
`),process.stderr.write(`
|
|
884
891
|
`+k(" Circuits")+`
|
|
885
892
|
`),s.circuits.length===0)process.stderr.write(l(" (none)")+`
|
|
886
|
-
`);else for(let o of s.circuits){let i=
|
|
893
|
+
`);else for(let o of s.circuits){let i=Gd(o),a=Kd(o),c=o.pure?L(a):D(a);process.stderr.write(` ${i} ${l("—")} ${c}
|
|
887
894
|
`)}if(process.stderr.write(`
|
|
888
895
|
`+k(" Witnesses")+`
|
|
889
896
|
`),s.witnesses.length===0)process.stderr.write(l(" (none)")+`
|
|
890
|
-
`);else for(let o of s.witnesses)process.stderr.write(` ${
|
|
897
|
+
`);else for(let o of s.witnesses)process.stderr.write(` ${Jd(o)}
|
|
891
898
|
`);if(s.siblings.length>0){process.stderr.write(`
|
|
892
899
|
`+k(" Other contracts in this project")+`
|
|
893
900
|
`);for(let o of s.siblings)process.stderr.write(` ${L(o)}
|
|
894
901
|
`);process.stderr.write(`
|
|
895
902
|
`+l(" Inspect a sibling: mn contract inspect --name <name>")+`
|
|
896
903
|
`)}process.stderr.write(`
|
|
897
|
-
`)}async function
|
|
904
|
+
`)}async function Ci(e,t){await Promise.resolve().then(() => Ce());let n=A(e,"network")??"undeployed",s={node:A(e,"node"),indexerWS:A(e,"indexer-ws"),proofServer:A(e,"proof-server")},{name:o,config:i}=de({args:{command:"contract",subcommand:t,positionals:[],flags:{network:n,...$n(s)}}});return Re(i,s,o),{network:n,networkConfig:i,endpoints:s}}async function Pl({network:e,networkConfig:t},r,n){await Promise.resolve().then(() => Ie());await Promise.resolve().then(() => bt());await Promise.resolve();let c=ae(se(n)),d=Buffer.from(c.seed,"hex"),p=c.addresses[e],u=r?Sn():G("Checking wallet..."),g=ye();try{let h=(await g.unshielded(p,t)).balances.get(Pr)??0n;if(h===0n)throw u.fail("No NIGHT balance"),Error(`Wallet has 0 NIGHT on ${e}.
|
|
898
905
|
|
|
899
906
|
Fund your wallet before deploying:
|
|
900
907
|
Address: ${p}
|
|
901
908
|
`+(e==="undeployed"?` Run: midnight airdrop 1000
|
|
902
909
|
`:` Use the Midnight faucet or transfer from another wallet.
|
|
903
|
-
`));let
|
|
910
|
+
`));let f=await g.dust(d,t,{onStatus:(y)=>u.update(y)});if(f.balance===0n&&f.availableCoins===0)throw u.fail("No dust available"),Error(`Wallet has no dust on ${e}. Dust is required to pay transaction fees.
|
|
904
911
|
|
|
905
912
|
Register for dust generation:
|
|
906
913
|
Run: midnight dust register --network ${e}
|
|
907
914
|
Then wait: midnight dust status --network ${e}
|
|
908
|
-
`);
|
|
909
|
-
`+
|
|
915
|
+
`);u.stop(`Wallet OK (${h} NIGHT, dust available)`)}catch(m){throw u.fail("Wallet check failed"),m}}async function Dl({network:e,endpoints:t},r,n){await Promise.resolve().then(() => bi());let o=r?Sn():G("Starting mn serve..."),i=await Ts({network:e,endpoints:t,wallet:n,onMessage:(a)=>o.update(a)});return o.stop("mn serve ready (port "+i.port+")"),{port:i.port,stop:()=>i.stop()}}async function kw(e){let t=R(e,"json"),r=Ms(A(e,"path")??process.cwd()),n=Fs(e),s=A(e,"name");await Promise.resolve().then(() => yn());if(!t)process.stderr.write(`
|
|
916
|
+
`+j("Contract Deploy")+`
|
|
910
917
|
|
|
911
|
-
`);let{info:
|
|
918
|
+
`);let{info:i}=rt(n,s),a=i.witnesses.map((y)=>y.name);if(a.length>0){await Promise.resolve().then(() => Is());if(!Rs(r))throw Error($s({projectRoot:r,witnessNames:a}))}let c=await Ci(e,"deploy"),{network:d,networkConfig:p}=c,u=A(e,"args"),g=[];if(u)try{let y=JSON.parse(u);g=Array.isArray(y)?y:Object.values(y)}catch(y){throw new H(`Invalid --args JSON: ${y.message}`)}let m=A(e,"secret-key");if(m!==void 0&&!/^[0-9a-fA-F]{64}$/.test(m))throw new H("--secret-key must be 32 bytes of hex (64 chars)");if(!t){if(process.stderr.write(C("Contract",i.name)+`
|
|
912
919
|
`),process.stderr.write(C("Network",d)+`
|
|
913
|
-
`),
|
|
920
|
+
`),g.length>0)process.stderr.write(C("Constructor args",String(g.length))+`
|
|
914
921
|
`);process.stderr.write(`
|
|
915
|
-
`)}await
|
|
916
|
-
`),process.stderr.write(C("Address",
|
|
922
|
+
`)}await Pl(c,t,A(e,"wallet"));let h=await Dl(c,t,A(e,"wallet")),f=t?Sn():G("Deploying contract...");try{let y=await Ds({dappDir:r,networkConfig:p,managedDir:i.managedDir,contractName:i.name,servePort:h.port,args:g,privateStateSecretKey:m,onMessage:(S)=>f.update(S)});if(f.stop(B("✓")+" Contract deployed"),t)_({subcommand:"deploy",contractName:i.name,address:y.contractAddress,network:d});else process.stderr.write(`
|
|
923
|
+
`),process.stderr.write(C("Address",y.contractAddress)+`
|
|
917
924
|
`),process.stderr.write(`
|
|
918
|
-
`+
|
|
919
|
-
`)
|
|
920
|
-
`)}catch(
|
|
925
|
+
`+B(" ✓ Deploy successful")+`
|
|
926
|
+
`),Cw(y.contractAddress,i.circuits,d),process.stdout.write(y.contractAddress+`
|
|
927
|
+
`)}catch(y){throw f.fail("Deploy failed"),y}finally{await h.stop()}}function Cw(e,t,r){let n=r==="undeployed"?"":` --network ${r}`;process.stderr.write(`
|
|
921
928
|
`+l(" Next:")+`
|
|
922
929
|
`),process.stderr.write(l(" mn contract state --address ")+L(e)+l(n)+`
|
|
923
930
|
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(l(" mn contract call --address ")+L(e)+l(" --circuit ")+L(s.name)+l(n)+`
|
|
924
931
|
`);process.stderr.write(`
|
|
925
|
-
`)}async function
|
|
926
|
-
`+
|
|
932
|
+
`)}async function xw(e){let t=R(e,"json"),r=Ms(A(e,"path")??process.cwd()),n=Fs(e),s=A(e,"name"),o=Cn(e,"address","contract address"),i=Cn(e,"circuit","circuit name"),a=A(e,"args");await Promise.resolve().then(() => yn());if(!t)process.stderr.write(`
|
|
933
|
+
`+j("Contract Call")+`
|
|
927
934
|
|
|
928
|
-
`);let{info:
|
|
935
|
+
`);let{info:d}=rt(n,s),p=[];if(a)try{let y=JSON.parse(a);p=Array.isArray(y)?y:Object.values(y)}catch(y){throw new H(`Invalid --args JSON: ${y.message}`)}let u=await Ci(e,"call"),{network:g,networkConfig:m}=u;if(!t)process.stderr.write(C("Contract",d.name)+`
|
|
929
936
|
`),process.stderr.write(C("Circuit",i)+`
|
|
930
937
|
`),process.stderr.write(C("Address",o.slice(0,20)+"...")+`
|
|
931
938
|
|
|
932
|
-
`);await
|
|
933
|
-
`+
|
|
939
|
+
`);await Pl(u,t,A(e,"wallet"));let h=await Dl(u,t,A(e,"wallet")),f=t?Sn():G(`Calling ${i}...`);try{let y=await Os({dappDir:r,networkConfig:m,managedDir:d.managedDir,contractName:d.name,contractAddress:o,circuit:i,args:p,servePort:h.port,onMessage:(S)=>f.update(S)});if(f.stop(B("✓")+` ${i} called`),t)_({subcommand:"call",contractName:d.name,circuit:i,address:o,network:g,status:y.status});else process.stderr.write(`
|
|
940
|
+
`+B(" ✓ Circuit call successful")+`
|
|
934
941
|
|
|
935
|
-
`)}catch(
|
|
936
|
-
`+
|
|
942
|
+
`)}catch(y){throw f.fail("Call failed"),y}finally{await h.stop()}}async function Ew(e){let t=R(e,"json"),r=Ms(A(e,"path")??process.cwd()),n=Fs(e),s=A(e,"name"),o=Cn(e,"address","contract address");await Promise.resolve().then(() => yn());let{network:a,networkConfig:c}=await Ci(e,"state");if(!t)process.stderr.write(`
|
|
943
|
+
`+j("Contract State")+`
|
|
937
944
|
|
|
938
945
|
`),process.stderr.write(C("Address",o.slice(0,20)+"...")+`
|
|
939
|
-
`),process.stderr.write(C("Network",
|
|
946
|
+
`),process.stderr.write(C("Network",a)+`
|
|
940
947
|
|
|
941
|
-
`);let
|
|
942
|
-
`);for(let[
|
|
943
|
-
`);for(let[
|
|
948
|
+
`);let d=t?Sn():G("Querying contract state...");try{let{info:p}=rt(n,s),u=await xr({dappDir:r,networkConfig:c,managedDir:p.managedDir,contractName:p.name,contractAddress:o,onMessage:(g)=>d.update(g)});if(d.stop(B("✓")+" State retrieved"),t)_({subcommand:"state",address:o,network:a,...u});else{let g=Object.keys(u.fields).length>0,m=Object.keys(u.maps).length>0;if(g||m){process.stderr.write(k(" Ledger State")+`
|
|
949
|
+
`);for(let[h,f]of Object.entries(u.fields))process.stderr.write(` ${h}: ${L(f)}
|
|
950
|
+
`);for(let[h,f]of Object.entries(u.maps))process.stderr.write(` ${h}: ${l(`Map (${f.size} entries)`)}
|
|
944
951
|
`)}else process.stderr.write(l(" (no ledger fields found)")+`
|
|
945
952
|
`);process.stderr.write(`
|
|
946
|
-
`)}}catch(p){
|
|
953
|
+
`)}}catch(p){d.stop(D("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() => Il());let m=await $l(c).queryContractState(o);if(!m)throw Error(`No contract found at address ${o} on ${a}`);let h=m.data??m;if(t)_({subcommand:"state",address:o,network:a,raw:h});else process.stderr.write(k(" Raw State")+`
|
|
947
954
|
`),process.stderr.write(l(" (run from dApp root for parsed ledger fields)")+`
|
|
948
|
-
`),process.stderr.write(` ${JSON.stringify(
|
|
955
|
+
`),process.stderr.write(` ${JSON.stringify(h).slice(0,200)}
|
|
949
956
|
|
|
950
|
-
`)}}var
|
|
951
|
-
Run this command from the root of a dApp project, or create a ${
|
|
952
|
-
Check the build log: ${i}`);if(await
|
|
953
|
-
Check the build log: ${i}`)}function
|
|
957
|
+
`)}}var _l;var Ls=T(()=>{we();Fe();ue();tt();fn();_l=["inspect","deploy","call","state"]});import{existsSync as Ar,readFileSync as bn,readdirSync as Aw}from"node:fs";import{join as zt,resolve as Tw}from"node:path";function Us(e){let t=Tw(e??process.cwd()),r=zt(t,xi);if(!Ar(r))throw Error(`No ${xi} found in ${t}
|
|
958
|
+
Run this command from the root of a dApp project, or create a ${xi} file.`);let n;try{n=JSON.parse(bn(r,"utf-8"))}catch(o){throw Error(`Failed to parse ${r}: ${o.message}`)}return{config:$w(n,r),configPath:r,dappDir:t}}function Ei(e){let t=zt(e,Nw);if(!Ar(t))return[];let r=Aw(t,{withFileTypes:!0}),n=[];for(let s of r){if(!s.isDirectory())continue;let o=zt(t,s.name),i=zt(o,"suite.json");if(!Ar(i))continue;let a;try{a=JSON.parse(bn(i,"utf-8"))}catch(c){throw Error(`Failed to parse ${i}: ${c.message}`)}n.push({suite:Iw(a,i),suiteDir:o})}return n}function jl(e){let t=zt(e,"assertions.json");if(!Ar(t))return null;let r;try{r=JSON.parse(bn(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return _w(r,t)}function Wl(e){let t=zt(e,"actions.json");if(!Ar(t))return null;let r;try{r=JSON.parse(bn(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return Pw(r,t)}function Bl(e){let t=zt(e,"prompt.md");if(!Ar(t))return null;return bn(t,"utf-8")}function $w(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&&!Ml.includes(r.network))throw Error(`${t}: "network" must be one of: ${Ml.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"||!Rw.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 Iw(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(!Fl.includes(r.strategy))throw Error(`${t}: "strategy" must be one of: ${Fl.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&&!Ll.includes(r.browserMode))throw Error(`${t}: "browserMode" must be one of: ${Ll.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 _w(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 Pw(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"||!Ul.includes(s.type))throw Error(`${t}: action "${s.id}" has invalid type "${s.type}". Valid: ${Ul.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 xi="dapp.test.json",Nw="tests/suites",Ml,Fl,Ll,Rw,Ul;var Hl=T(()=>{Ml=["undeployed","preprod","preview"],Fl=["browser","cli","hybrid"],Ll=["dom","script","vision","auto"],Rw=/^(cache-clear|localnet-up|balance:\d+|dust|dust-register|dust-wait|mn-serve|build-and-serve)$/;Ul=["contract-deploy","contract-call","contract-state","wallet-cmd"]});function Gl(){let e=[];return{cleanups:e,addCleanup(t){e.push(t)}}}import{spawn as Dw}from"node:child_process";import{createWriteStream as Ow}from"node:fs";import{join as Mw}from"node:path";import Fw from"node:http";import Lw from"node:net";async function Jl(e){let{dappDir:t,buildCmd:r,buildDir:n=".",port:s,url:o,logFile:i,timeoutMs:a=240000,onMessage:c=()=>{}}=e;if(await Uw(s)){if(await Kl(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 jw(s),await new Promise((f)=>setTimeout(f,2000))}let d=Mw(t,n),p=Ow(i,{flags:"a"}),u=Dw("bash",["-lc",r],{cwd:d,stdio:["ignore","pipe","pipe"],detached:!1});u.stdout?.pipe(p),u.stderr?.pipe(p);let g=!1,m=null;u.on("exit",(f)=>{g=!0,m=f}),c(`Building (${r})...`);let h=Date.now()+a;while(Date.now()<h){if(g)throw Error(`Build process exited with code ${m} before the UI was ready.
|
|
959
|
+
Check the build log: ${i}`);if(await Kl(o))return c("UI ready"),{port:s,child:u,stop(){if(!g)u.kill("SIGTERM"),setTimeout(()=>{if(!g)u.kill("SIGKILL")},5000).unref();p.end()}};await new Promise((f)=>setTimeout(f,2000))}throw u.kill("SIGTERM"),p.end(),Error(`UI did not start within ${Math.round(a/1000)}s at ${o}
|
|
960
|
+
Check the build log: ${i}`)}function Uw(e){return new Promise((t)=>{let r=new Lw.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 jw(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 Kl(e){return new Promise((t)=>{let r=Fw.get(e,{timeout:3000},(n)=>{t(n.statusCode===200),n.resume()});r.on("error",()=>t(!1)),r.on("timeout",()=>{r.destroy(),t(!1)})})}var Vl=()=>{};import*as zl from"@midnightntwrk/ledger-v9";import{join as Ww}from"node:path";async function Xl(e,t,r,n){let s=[];for(let o of e.prep){let i=Date.now();n.onStepStart(o);try{await Bw(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 Bw(e,t,r,n,s){if(e==="cache-clear")return Hw(t);if(e==="localnet-up")return Gw(t,s);if(e.startsWith("balance:")){let o=parseInt(e.split(":")[1],10);return Kw(o,t,s)}if(e==="dust"||e==="dust-register"||e==="dust-wait")return Jw(t,s);if(e==="mn-serve")return Vw(t,n,s);if(e==="build-and-serve")return qw(t,r,n,s);throw Error(`Unknown prep step: ${e}`)}async function Hw(e){let t=e.network??"undeployed";et(void 0,t)}async function Gw(e,t){let r=e.network??"undeployed",{config:n}=de({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}});await zn(r,n),t.onMessage(`Using the ledger-9 stack at ${n.node} (indexer ${n.indexer})`)}async function Kw(e,t,r){let n=t.network??"undeployed",{config:s}=de({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:n}}});await ut(n,s);let o=ae(se()),i=Buffer.from(o.seed,"hex"),a=o.addresses[n];r.onMessage("Checking balance...");let c=xe((h,f)=>{r.onMessage(`SDK: ${f}`)}),d=_e(),p=It(a,n),u=await dt(i,s,p);try{let h=await $t(u,{syncMode:"lite",onProgress:(S,w)=>{if(w>0){let b=Math.min(Math.round(S/w*100),100);r.onMessage(`Syncing wallet... ${b}%`)}},onSyncDetail:(S)=>{r.onMessage(`Syncing wallet... (${S})`)}}),f=zl.unshieldedToken().raw,y=h.unshielded.balances[f]??0n;if(y>0n){r.onMessage(`Balance OK: ${y}`);try{await Xe(a,n,u.facade)}catch{}return}}finally{d(),c();try{await Ke(u)}catch{}}if(n!=="undeployed")throw Error(`Wallet has 0 NIGHT on ${n}. Fund your wallet before running tests:
|
|
954
961
|
mn airdrop ${e} (if faucet available)
|
|
955
|
-
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let
|
|
962
|
+
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let g=Buffer.from(mt,"hex"),m=$e(g,n);await fr({seedBuffer:g,networkConfig:s,recipientAddress:a,amountNight:e,onSync(h,f){},onDust(h){r.onMessage(`Dust: ${h}`)},onProving(){r.onMessage("Generating ZK proof...")},onSubmitting(){r.onMessage("Submitting airdrop transaction...")},onSyncWarning(h,f){r.onMessage(`Syncing genesis... (${f})`)}}),r.onMessage(`Airdropped ${e} NIGHT`)}async function Jw(e,t){let r=e.network??"undeployed",{config:n}=de({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}});await ut(r,n);let s=ae(se()),o=Buffer.from(s.seed,"hex"),i=s.addresses[r],a=xe(),c=_e(),d=It(i,r),p=await dt(o,n,d);try{if(t.onMessage("Syncing wallet..."),await $t(p,{syncMode:"lite"}),t.onMessage("Ensuring dust..."),(await pt(p,(h)=>t.onMessage(`Dust: ${h}`))).alreadyAvailable){t.onMessage("Dust already available");try{await Xe(i,r,p.facade)}catch{}return}t.onMessage("Dust registered. Waiting for coins to become available...");let g=await ar(p,ql);if(!yt(g)){if(r!=="undeployed")throw Error(`Dust not available on ${r}. Register dust and wait for it to generate:
|
|
956
963
|
mn dust register
|
|
957
|
-
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${
|
|
958
|
-
`).filter(Boolean);e(`Found ${r.length} orphan chrome-devtools-mcp Chrome process(es), killing`);for(let n of r)try{
|
|
964
|
+
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${ql/1000}s. The chain may be slow — try again.`)}t.onMessage("Dust is available");try{await Xe(i,r,p.facade)}catch{}}finally{c(),a();try{await Ke(p)}catch{}}}async function Vw(e,t,r){r.onMessage("Starting mn serve...");let n=await Ts({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 qw(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=Ww(t,"tests","results",`build_${Date.now()}.log`),a=await Jl({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 ql=90000;var Yl=T(()=>{_t();Ie();Ce();Kt();ze();_t();Pt();Qe();bi();Vl()});import{execSync as Zl,spawn as zw}from"node:child_process";import{createWriteStream as Xw,existsSync as Yw,mkdirSync as Zw,readFileSync as Qw}from"node:fs";import{dirname as ey,join as ty}from"node:path";import{homedir as ry}from"node:os";function ny(){let e=ty(ry(),".claude.json");if(!Yw(e))return!1;try{let t=JSON.parse(Qw(e,"utf-8"));return Boolean(t.mcpServers?.["chrome-devtools"])}catch{return!1}}function oy(e){let t;try{t=Zl(`ps -ax -o pid,command | grep "${sy}" | grep -v grep | awk '{print $1}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return}if(!t)return;let r=t.split(`
|
|
965
|
+
`).filter(Boolean);e(`Found ${r.length} orphan chrome-devtools-mcp Chrome process(es), killing`);for(let n of r)try{Zl(`kill ${n}`,{stdio:"pipe"})}catch{}}function Ai(e){let t=e.browserMode??"vision";if(t==="auto")return"vision";return t}async function Ql(e){let{suite:t,prompt:r,dappDir:n,logFile:s,onMessage:o=()=>{}}=e,i=(t.timeout??600)*1000,a=Ai(t);if(a==="dom"||a==="script"){if(!ny())throw Error(`Browser mode "${a}" requires the chrome-devtools MCP server, which is not registered in ~/.claude.json.
|
|
959
966
|
|
|
960
967
|
Install it:
|
|
961
968
|
claude mcp add chrome-devtools --scope user npx chrome-devtools-mcp@latest
|
|
962
969
|
|
|
963
|
-
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");
|
|
964
|
-
`),s}function
|
|
970
|
+
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");oy(o)}Zw(ey(s),{recursive:!0});let c=Xw(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 p=r;if(a==="dom")p=iy+r;else if(a==="script")p=ay+r;return d.push("-p",p),o(`Launching Claude (mode: ${a}, model: ${t.model??"default"}, timeout: ${t.timeout??600}s)`),new Promise((u)=>{let g=zw("claude",d,{cwd:n,stdio:["inherit","pipe","inherit"]}),m=!1;g.stdout?.on("data",(f)=>{process.stdout.write(f),c.write(f)});let h=setTimeout(()=>{m=!0,o(`Timeout: test exceeded ${t.timeout??600}s`),g.kill("SIGTERM"),setTimeout(()=>{if(!g.killed)g.kill("SIGKILL")},1e4).unref()},i);g.on("close",(f)=>{clearTimeout(h),c.end(),u({exitCode:f??1,logFile:s,timedOut:m})}),g.on("error",(f)=>{clearTimeout(h),c.end(),o(`Claude process error: ${f.message}`),u({exitCode:1,logFile:s,timedOut:!1})})})}var sy="chrome-devtools-mcp/chrome-profile",iy="## 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",ay="## 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 eu=()=>{};import{existsSync as cy,readFileSync as dy}from"node:fs";import ly from"node:net";async function tu(e,t){let r=[];for(let n of e)try{let s=await uy(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 uy(e,t){switch(e.type){case"balance-changed":return py(e,t);case"process-exit-code":return my(e,t);case"port-listening":return fy(e);case"agent-report-no-failure":return hy(e,t);default:throw Error(`Unsupported assertion type: "${e.type}" (available in v2)`)}}function py(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 my(e,t){if(t.processExitCode===void 0)throw Error("Process exit code not available");let r=e.params.code;return t.processExitCode===r}function fy(e){let t=e.params.port;return new Promise((r)=>{let n=new ly.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 hy(e,t){let r=e.params??{},n=r.logPath??t.agentLogPath;if(!n||!cy(n))return!0;let s;try{s=dy(n,"utf-8")}catch{return!0}let o=yy(s),i=r.markers??gy;for(let a of i)if(wy(o,a))return!1;return!0}function wy(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 yy(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"")}var gy;var ru=T(()=>{gy=["FAILED","❌","did not pass","test failed","overall: fail","result: fail"]});import{existsSync as Sy,mkdirSync as by,writeFileSync as vy,readFileSync as ky,readdirSync as Cy}from"node:fs";import{join as js}from"node:path";function su(e,t){let r=js(t,nu);by(r,{recursive:!0});let n=`${e.suite}_${e.timestamp.replace(/[:.]/g,"-")}.json`,s=js(r,n);return vy(s,JSON.stringify(e,null,2)+`
|
|
971
|
+
`),s}function ou(e,t){let r=Ti(e,t);return r.length>0?r[0]:null}function Ti(e,t){let r=js(e,nu);if(!Sy(r))return[];let n=Cy(r).filter((o)=>o.endsWith(".json")).filter((o)=>!t||o.startsWith(t+"_")),s=[];for(let o of n)try{let i=ky(js(r,o),"utf-8");s.push(JSON.parse(i))}catch{}return s.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),s}var nu="tests/results";var iu=()=>{};import{execSync as xy}from"node:child_process";async function Ni(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)Ey(e.buildHandle.port,t)}function Ey(e,t){try{xy(`osascript -e 'tell application "Google Chrome"
|
|
965
972
|
repeat with theWindow in every window
|
|
966
973
|
repeat with theTab in every tab of theWindow
|
|
967
974
|
if URL of theTab contains "localhost:${e}" then
|
|
@@ -969,7 +976,7 @@ Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision
|
|
|
969
976
|
end if
|
|
970
977
|
end repeat
|
|
971
978
|
end repeat
|
|
972
|
-
end tell'`,{timeout:5000,stdio:"pipe"}),t?.(`Closed Chrome tabs for localhost:${e}`)}catch{}}var
|
|
979
|
+
end tell'`,{timeout:5000,stdio:"pipe"}),t?.(`Closed Chrome tabs for localhost:${e}`)}catch{}}var au=()=>{};function cu(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(cu);default:return null}}function Ri(e){let t={};for(let r of e.arguments)t[r.name]=cu(r.type);return t}function $i(e,t){if((t.strategy??"cli")==="browser"){if(!t.browser)throw Error("Browser strategy requires browser options (port, buildCmd, buildDir?, url?)");return _y(t,t.browser)}return Iy(e,t)}function Iy(e,t){let r=t.suiteName??Ay,n=t.network??du,s=t.servePort??lu;return{dappConfig:{name:t.contractName,network:n,prep:uu},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??Ny},actions:{actions:Dy(e)},assertions:{post:[pu(s)]},prompt:null,suiteName:r}}function _y(e,t){let r=e.suiteName??Ty,n=e.network??du,s=e.servePort??lu,o=t.url??`http://localhost:${t.port}/`,i={name:e.contractName,network:n,port:t.port,buildCmd:t.buildCmd,url:o,prep:$y};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??Ry,...t.browserMode?{browserMode:t.browserMode}:{}},actions:null,assertions:{post:[{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"},pu(s),{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}]},prompt:Py(e.contractName,o),suiteName:r}}function pu(e){return{id:"serve-port-listening",type:"port-listening",params:{port:e},expect:"pass"}}function Py(e,t){return`You are running an automated E2E test of ${e}.
|
|
973
980
|
|
|
974
981
|
The UI is at ${t} — open it in Chrome.
|
|
975
982
|
mn serve is running with --approve-all so contract calls will auto-approve.
|
|
@@ -999,44 +1006,44 @@ Follow these steps:
|
|
|
999
1006
|
|
|
1000
1007
|
If any step fails, report exactly what you see on screen and stop.
|
|
1001
1008
|
Take screenshots at each major step to document the test.
|
|
1002
|
-
`}function
|
|
1009
|
+
`}function Dy(e){let t=[{id:"deploy",type:"contract-deploy"},{id:"check-initial",type:"contract-state"}],r=e.filter((n)=>!n.pure);for(let n of r){let s={id:`call-${n.name}`,type:"contract-call",circuit:n.name};if(n.arguments.length>0)s.args=Ri(n);t.push(s)}return t.push({id:"check-final",type:"contract-state"}),t}var du="undeployed",Ay="cli-default",Ty="ui-default",Ny=300,Ry=600,lu=9932,uu,$y;var Ii=T(()=>{uu=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],$y=[...uu,"build-and-serve"]});import{existsSync as fu,mkdirSync as Oy,readFileSync as My,writeFileSync as mu}from"node:fs";import{join as Tr}from"node:path";function gu(e,t){let{dappDir:r,force:n=!1}=t,s=Tr(r,"tests","suites",e.suiteName),o=Tr(r,"dapp.test.json"),i=[{path:Tr(s,"suite.json"),kind:"json",body:e.suite},{path:Tr(s,"assertions.json"),kind:"json",body:e.assertions}];if(e.actions)i.push({path:Tr(s,"actions.json"),kind:"json",body:e.actions});if(e.prompt)i.push({path:Tr(s,"prompt.md"),kind:"text",body:e.prompt});if(!n){let p=i.filter((u)=>fu(u.path)).map((u)=>u.path);if(p.length>0)throw Error(`Suite "${e.suiteName}" already exists at ${s}.
|
|
1003
1010
|
Pick a different suite name (--suite <name>) or pass --force to overwrite.
|
|
1004
1011
|
Existing files:
|
|
1005
|
-
`+
|
|
1006
|
-
`))}let a=
|
|
1007
|
-
`),c.push(o);else d.push(o);for(let
|
|
1008
|
-
`:
|
|
1009
|
-
Fix or remove it (or pass --force to overwrite).`)}if(n.name!==t.dappConfig.name)throw Error(`${e} exists with name "${String(n.name)}" but this scaffold targets "${t.dappConfig.name}". Use --force to overwrite, or run from the right project directory.`);return{action:"preserve"}}var
|
|
1012
|
+
`+p.map((u)=>` - ${u}`).join(`
|
|
1013
|
+
`))}let a=Fy(o,e,n);Oy(s,{recursive:!0});let c=[],d=[];if(a.action==="write")mu(o,JSON.stringify(e.dappConfig,null,2)+`
|
|
1014
|
+
`),c.push(o);else d.push(o);for(let p of i){let u=p.kind==="json"?JSON.stringify(p.body,null,2)+`
|
|
1015
|
+
`:p.body;mu(p.path,u),c.push(p.path)}return{written:c,preserved:d}}function Fy(e,t,r){if(r||!fu(e))return{action:"write"};let n;try{n=JSON.parse(My(e,"utf-8"))}catch(s){let o=s instanceof Error?s.message:String(s);throw Error(`${e} exists but is not valid JSON: ${o}
|
|
1016
|
+
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 hu=()=>{};import{existsSync as yu,readdirSync as Ly,readFileSync as Uy,statSync as jy}from"node:fs";import{basename as Wy,extname as By,join as Su,relative as Hy}from"node:path";function bu(e){let t=new Map;for(let r of Gy){let n=Su(e,r);if(!yu(n))continue;_i(n,e,t)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function vu(e,t=e){if(!yu(e))return[];let r=new Map;return _i(e,t,r),[...r.values()].sort((n,s)=>n.name.localeCompare(s.name))}function _i(e,t,r){let n;try{n=Ly(e)}catch{return}for(let s of n){let o=Su(e,s),i;try{i=jy(o)}catch{continue}if(i.isDirectory()){if(Ky.has(s.toLowerCase()))continue;_i(o,t,r);continue}if(By(s)!==wu)continue;if(s.endsWith(".test.tsx")||s.endsWith(".spec.tsx"))continue;let a=Wy(s,wu);if(!Jy(a,o))continue;let c=qy(a);if(r.has(c))continue;r.set(c,{name:c,component:a,path:o,relativePath:Hy(t,o)})}}function Jy(e,t){if(!/^[A-Z][A-Za-z0-9]*$/.test(e))return!1;let r;try{r=Uy(t,"utf-8")}catch{return!1}return Vy.test(r)}function qy(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}var Gy,wu=".tsx",Ky,Vy;var Pi=T(()=>{Gy=["src/components","src/pages","src/screens","src/views"];Ky=new Set(["layout","layouts","shared","common","ui","icons","styles"]);Vy=/\bexport\s+(default\b|const\s+[A-Z]|function\s+[A-Z])/});import{existsSync as zy,statSync as Xy}from"node:fs";import*as ku from"node:readline";function Cu(){return process.stdin.isTTY===!0}function nt(e,t){let r=ku.createInterface({input:process.stdin,output:process.stderr}),n=t!==void 0?l(` [${t}]`):"";return new Promise((s)=>{r.question(` ${e}${n}: `,(o)=>{r.close();let i=o.trim();s(i===""&&t!==void 0?t:i)})})}async function xu(){process.stderr.write(`
|
|
1010
1017
|
`+L("Test scaffold setup")+`
|
|
1011
|
-
`);for(;;){let e=(await
|
|
1012
|
-
`))}}async function
|
|
1018
|
+
`);for(;;){let e=(await nt("Strategy? cli or ui","cli")).toLowerCase();if(e==="cli")return"cli";if(e==="ui"||e==="browser")return"browser";process.stderr.write(l(` Unknown strategy "${e}". Pick "cli" or "ui".
|
|
1019
|
+
`))}}async function Eu(e={}){process.stderr.write(`
|
|
1013
1020
|
`+l("Browser test scaffold needs your dApp UI details:")+`
|
|
1014
|
-
`);let t=e.port!==void 0?String(e.port):await
|
|
1021
|
+
`);let t=e.port!==void 0?String(e.port):await nt("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 nt("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 nt("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await nt("URL",`http://localhost:${r}/`),a=e.browserMode??await Yy();return{port:r,buildCmd:n,buildDir:o,url:i,browserMode:a}}async function Yy(){process.stderr.write(`
|
|
1015
1022
|
`+L("Browser mode — how should Claude perceive the page?")+`
|
|
1016
1023
|
`),process.stderr.write(` ${l("1.")} dom ${l("— accessibility tree (text). Fast. HTML / React / Vue UIs.")}
|
|
1017
1024
|
`),process.stderr.write(` ${l("2.")} vision ${l("— screenshots. Slow. Canvas games (no DOM).")}
|
|
1018
1025
|
`),process.stderr.write(` ${l("3.")} script ${l("— direct JS. Fastest. Needs dApp-side hooks (advanced).")}
|
|
1019
1026
|
`),process.stderr.write(l(` dom and script need chrome-devtools-mcp installed.
|
|
1020
|
-
`));for(;;){let e=(await
|
|
1021
|
-
`))}}async function
|
|
1027
|
+
`));for(;;){let e=(await nt("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(D(` Pick 1 (dom), 2 (vision), or 3 (script).
|
|
1028
|
+
`))}}async function Au(e){let t=e.filter((r)=>!r.pure);if(t.length===0){process.stderr.write(l(` No impure circuits in this contract — nothing to test as a write path.
|
|
1022
1029
|
`));return}process.stderr.write(`
|
|
1023
1030
|
`+L("Pick the circuit this suite will exercise:")+`
|
|
1024
1031
|
`);for(let r=0;r<t.length;r++)process.stderr.write(` ${l(`${r+1}.`)} ${t[r].name}
|
|
1025
1032
|
`);process.stderr.write(l(` (or type "skip" to scaffold all circuits without AI)
|
|
1026
|
-
`));for(;;){let r=(await
|
|
1027
|
-
`))}}async function
|
|
1033
|
+
`));for(;;){let r=(await nt("Circuit","1")).trim();if(r.toLowerCase()==="skip")return;let n=parseInt(r,10);if(Number.isFinite(n)&&n>=1&&n<=t.length)return t[n-1];let s=t.find((o)=>o.name===r);if(s)return s;process.stderr.write(l(` Pick a number 1–${t.length}, the circuit name, or "skip".
|
|
1034
|
+
`))}}async function Di(e){if(e.length===0)return Zy();process.stderr.write(`
|
|
1028
1035
|
`+L("Pick the screen this suite will test:")+`
|
|
1029
1036
|
`);for(let t=0;t<e.length;t++)process.stderr.write(` ${l(`${t+1}.`)} ${e[t].name} ${l(`(${e[t].relativePath})`)}
|
|
1030
1037
|
`);process.stderr.write(l(` (or type "skip" to scaffold a generic prompt.md without AI)
|
|
1031
|
-
`));for(;;){let t=(await
|
|
1032
|
-
`))}}async function
|
|
1038
|
+
`));for(;;){let t=(await nt("Screen","1")).trim();if(t.toLowerCase()==="skip")return;let r=parseInt(t,10);if(Number.isFinite(r)&&r>=1&&r<=e.length)return e[r-1];let n=e.find((s)=>s.name===t||s.component===t);if(n)return n;process.stderr.write(l(` Pick a number 1–${e.length}, the screen name, or "skip".
|
|
1039
|
+
`))}}async function Zy(){process.stderr.write(l(`
|
|
1033
1040
|
Could not auto-discover screens (no src/components, src/pages, or src/screens under the build dir).
|
|
1034
|
-
`));for(;;){let e=(await
|
|
1035
|
-
`));continue}let t;try{t=
|
|
1036
|
-
`));continue}if(t.isDirectory()){let r=
|
|
1037
|
-
`));continue}return
|
|
1038
|
-
`));continue}return
|
|
1039
|
-
`))}}function
|
|
1041
|
+
`));for(;;){let e=(await nt('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!zy(e)){process.stderr.write(l(` No such path: ${e}
|
|
1042
|
+
`));continue}let t;try{t=Xy(e)}catch{process.stderr.write(l(` Cannot stat: ${e}
|
|
1043
|
+
`));continue}if(t.isDirectory()){let r=vu(e);if(r.length===0){process.stderr.write(l(` No PascalCase .tsx components in ${e}
|
|
1044
|
+
`));continue}return Di(r)}if(!e.endsWith(".tsx")){process.stderr.write(l(` Not a .tsx file: ${e}
|
|
1045
|
+
`));continue}return eS(e)}}async function Tu(){let e=(await nt("What does success look like? (one line, optional)")).trim();return e===""?void 0:e}async function Oi(e){for(;;){let t=(await nt("Suite name",e)).trim();if(Qy(t))return t;process.stderr.write(D(` Suite names must be kebab-case (a–z, 0–9, dashes, underscores). Try again.
|
|
1046
|
+
`))}}function Qy(e){return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e)}function eS(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 Nu=T(()=>{Pi()});function Iu(e){let{contractName:t,contractSummary:r,contractSource:n,targetCircuit:s,goal:o,witnessDependentCircuits:i}=e,a=i&&i.size>0?`
|
|
1040
1047
|
## Circuits NOT testable from a CLI suite
|
|
1041
1048
|
|
|
1042
1049
|
These circuits call witnesses that read from private state. In a
|
|
@@ -1044,7 +1051,7 @@ CLI test the private state is empty (no UI to populate it), so
|
|
|
1044
1051
|
they crash with "Cannot read properties of undefined". Do NOT
|
|
1045
1052
|
include them as actions, even as setup steps:
|
|
1046
1053
|
|
|
1047
|
-
`+[...i.entries()].map(([u
|
|
1054
|
+
`+[...i.entries()].map(([p,u])=>` - ${p} (uses ${u.join(", ")})`).join(`
|
|
1048
1055
|
`)+`
|
|
1049
1056
|
${s&&i.has(s.name)?`
|
|
1050
1057
|
The user explicitly asked for "${s.name}" — try anyway,
|
|
@@ -1057,7 +1064,7 @@ Focus this suite on ONE circuit:
|
|
|
1057
1064
|
|
|
1058
1065
|
Circuit: ${s.name} (${s.pure?"pure":"impure"})
|
|
1059
1066
|
Args:
|
|
1060
|
-
${s.arguments.length===0?" (takes no arguments)":s.arguments.map((
|
|
1067
|
+
${s.arguments.length===0?" (takes no arguments)":s.arguments.map((p)=>` - ${p.name}: ${p.type["type-name"]}`).join(`
|
|
1061
1068
|
`)}
|
|
1062
1069
|
${e.startingArgs&&Object.keys(e.startingArgs).length>0?`
|
|
1063
1070
|
Starting args (REQUIRED — keep these exact field names; replace
|
|
@@ -1141,12 +1148,12 @@ Args coercion the runner applies (so JSON arg values can be):
|
|
|
1141
1148
|
- [0..255] int array → Uint8Array for Bytes<N>
|
|
1142
1149
|
- object → recurses into Struct fields
|
|
1143
1150
|
|
|
1144
|
-
${
|
|
1151
|
+
${$u}
|
|
1145
1152
|
|
|
1146
|
-
Now produce the JSON.`}function
|
|
1147
|
-
--- ${
|
|
1148
|
-
${
|
|
1149
|
-
--- end ${
|
|
1153
|
+
Now produce the JSON.`}function _u(e){let{contractName:t,contractSummary:r,screenComponent:n,screenSource:s,relatedSources:o,url:i,goal:a}=e,c=(o??[]).map((u)=>`
|
|
1154
|
+
--- ${u.path} ---
|
|
1155
|
+
${u.source}
|
|
1156
|
+
--- end ${u.path} ---`).join(`
|
|
1150
1157
|
`),d=n&&s?`## Target screen
|
|
1151
1158
|
|
|
1152
1159
|
Component: ${n}
|
|
@@ -1176,7 +1183,7 @@ Conventional patterns Midnight dApps follow that you can rely on:
|
|
|
1176
1183
|
- Toast or inline error messages on failure.
|
|
1177
1184
|
|
|
1178
1185
|
Use generic-but-specific selectors (\`getByRole('button', { name: /connect wallet/i })\`)
|
|
1179
|
-
in the prompt steps, since you don't have the actual JSX.`,
|
|
1186
|
+
in the prompt steps, since you don't have the actual JSX.`,p=a?`Success criterion (from the user):
|
|
1180
1187
|
> ${a}
|
|
1181
1188
|
`:n?`No specific success criterion was given. Infer one from the screen source: what is the obvious "happy path" outcome a user would see on success?
|
|
1182
1189
|
`:`No specific success criterion was given. Infer one from the contract circuits: what is the obvious "happy path" outcome the dApp exists to support?
|
|
@@ -1186,7 +1193,7 @@ drives Chrome and follows a prompt.md file.
|
|
|
1186
1193
|
|
|
1187
1194
|
${d}
|
|
1188
1195
|
|
|
1189
|
-
${
|
|
1196
|
+
${p}
|
|
1190
1197
|
|
|
1191
1198
|
## Contract context (so you know what circuits the dApp calls)
|
|
1192
1199
|
|
|
@@ -1220,82 +1227,82 @@ A JSON object with three keys:
|
|
|
1220
1227
|
chain (e.g. ledger-field on a contract-state read).
|
|
1221
1228
|
- description: one short sentence summarising what this suite verifies.
|
|
1222
1229
|
|
|
1223
|
-
${
|
|
1230
|
+
${$u}
|
|
1224
1231
|
|
|
1225
|
-
Now produce the JSON.`}function
|
|
1226
|
-
`)}var
|
|
1232
|
+
Now produce the JSON.`}function Mi(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(`
|
|
1233
|
+
`)}var Ru="```json",$u;var Pu=T(()=>{$u=`Output rules:
|
|
1227
1234
|
- Reply with EXACTLY one ${"```json"} ... \`\`\` fenced code block.
|
|
1228
1235
|
- Inside the fence: valid JSON, nothing else (no comments, no trailing text).
|
|
1229
1236
|
- Fields you don't know about: omit them. Don't invent fields.
|
|
1230
1237
|
- Use only the circuit / ledger field names that appear in the inputs below.
|
|
1231
|
-
- Be concise — fewer, well-named actions beat many vague ones.`});var zl={};W(zl,{analyzeWitnessDependencies:()=>Zr});function Zr(e,t){if(t.length===0)return{byCircuit:new Map};let r=by(e),n=vy(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,u]of n){o.set(d,new Set),i.set(d,new Set);for(let p of Cy(u.body,u.argNames))if(s.has(p))o.get(d).add(p);else if(n.has(p))i.get(d).add(p)}let a=!0;while(a){a=!1;for(let[d,u]of i){let p=o.get(d);for(let f of u)for(let g of o.get(f)??[])if(!p.has(g))p.add(g),a=!0}}let c=new Map;for(let[d,u]of n){if(!u.isCircuit)continue;let p=o.get(d);if(p&&p.size>0)c.set(d,[...p].sort())}return{byCircuit:c}}function by(e){return e.replace(Sy,"").replace(yy,"")}function vy(e){let t=new Map,r=/\b(circuit|function)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gms,n;while((n=r.exec(e))!==null){let s=n[1],o=n[2],i=n[3],a=n.index+n[0].length,c=e.indexOf("{",a);if(c<0)continue;let d=1,u=c+1;for(;u<e.length&&d>0;u++){let g=e[u];if(g==="{")d++;else if(g==="}")d--}if(d!==0)continue;let p=e.slice(c+1,u-1),f=ky(i);t.set(o,{body:p,argNames:f,isCircuit:s==="circuit"})}return t}function ky(e){let t=new Set;for(let r of e.split(",")){let n=r.trim();if(!n)continue;let s=n.indexOf(":"),o=s>-1?n.slice(0,s).trim():n;if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))t.add(o)}return t}function Cy(e,t){let r=new Set,n=/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g,s;while((s=n.exec(e))!==null){let o=s[1];if(Ay.has(o)||t.has(o))continue;r.add(o)}return r}var yy,Sy,Ay;var Ns=x(()=>{yy=/\/\/[^\n]*/g,Sy=/\/\*[\s\S]*?\*\//g;Ay=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var su={};W(su,{claudeSubprocessRunner:()=>Ji,findContractSourcePath:()=>Vi,generateCliScaffoldWithAI:()=>My,generateUiScaffoldWithAI:()=>Fy,isClaudeAvailable:()=>Iy});import{execFileSync as Ey,spawn as xy}from"node:child_process";import{existsSync as Ki,readdirSync as Ty,readFileSync as Yl}from"node:fs";import{dirname as hr,join as Rs}from"node:path";function Iy(){try{return Ey("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function tu(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${Hl} ... \`\`\` fenced block. First 200 chars: ${e.slice(0,200)}`);try{return JSON.parse(r[1])}catch(n){let s=n instanceof Error?n.message:String(n);throw Error(`JSON inside the fence failed to parse: ${s}`)}}function _y(e,t){if(!e||typeof e!=="object")throw Error("AI response must be an object");if(typeof e.description!=="string"||!e.description)throw Error("AI response missing string `description`");if(!e.assertions||!Array.isArray(e.assertions.post))throw Error("AI response missing `assertions.post` array");let r=Py(e);if(!r)throw Error("AI response missing actions — expected either `actions: [...]` (top-level array) "+"or `actions: { actions: [...] }` (wrapped). Got: "+JSON.stringify(e.actions??null).slice(0,200));let n=new Map(t.circuits.map((s)=>[s.name,s]));for(let s of r){if(s.type!=="contract-call"||!s.circuit)continue;let o=n.get(s.circuit);if(!o)throw Error(`AI response references unknown circuit "${s.circuit}". Valid circuits: ${[...n.keys()].join(", ")||"(none)"}`);Dy(s,o)}return{actions:r}}function Dy(e,t){if(t.arguments.length===0)return;let r=e.args??{};for(let n of t.arguments){let s=r[n.name];if(s===void 0)throw Error(`Action "${e.id}" (circuit ${t.name}) is missing required arg "${n.name}" of type ${n.type["type-name"]}. Declared args: ${t.arguments.map((i)=>`${i.name}: ${i.type["type-name"]}`).join(", ")}`);let o=n.type["type-name"];if((o==="Struct"||o==="Alias")&&(s===null||typeof s!=="object"||Array.isArray(s)))throw Error(`Action "${e.id}" (circuit ${t.name}) arg "${n.name}" must be an object for ${o} type; got ${s===null?"null":typeof s}. Read the contract source to find the inner field names.`)}}function Py(e){if(Array.isArray(e.actions))return e.actions;let t=e.actions;if(t&&Array.isArray(t.actions))return t.actions;return null}function Oy(e){if(!e||typeof e!=="object")throw Error("AI response must be an object");if(typeof e.description!=="string"||!e.description)throw Error("AI response missing string `description`");if(typeof e.prompt!=="string"||!e.prompt.trim())throw Error("AI response missing non-empty `prompt`");if(!e.assertions||!Array.isArray(e.assertions.post))throw Error("AI response missing `assertions.post` array")}async function My(e,t=Ji){let r=e.contractSourcePath&&Ki(e.contractSourcePath)?Yl(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?Zr(r,n).byCircuit:new Map,o=e.targetCircuit?Ts(e.targetCircuit):void 0,i=Kl({contractName:e.contract.name,contractSummary:Gi({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),contractSource:r,targetCircuit:e.targetCircuit,startingArgs:o,witnessDependentCircuits:s,goal:e.goal}),a=await t(i),c=tu(a),d=_y(c,e.contract),u=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${nu(e.goal)??"ai"}`),p=e.network??Zl,f=e.servePort??Ql,g={name:e.contract.name,network:p,prep:eu},h={name:u,description:c.description,strategy:"cli",timeout:Ny},m=Ly(c.assertions,f),w=[...s.entries()].filter(([y])=>y!==e.targetCircuit?.name).map(([y,S])=>({name:y,reason:`uses witness ${S.join(", ")} (private state — UI-only)`}));return{dappConfig:g,suite:h,actions:d,assertions:m,prompt:null,suiteName:u,excludedCircuits:w.length>0?w:void 0}}async function Fy(e,t=Ji){let r=e.screen?Yl(e.screen.path,"utf-8"):void 0,n=Jl({contractName:e.contract.name,contractSummary:Gi({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),screenComponent:e.screen?.component,screenSource:r,relatedSources:e.relatedSources,url:e.url,goal:e.goal}),s=await t(n),o=tu(s);Oy(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${nu(e.goal)??"ai"}`),a=e.network??Zl,c=e.servePort??Ql,d=e.url,u={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:$y};if(e.buildDir)u.buildDir=e.buildDir;let p={name:i,description:o.description,strategy:"browser",timeout:Ry,...e.browserMode?{browserMode:e.browserMode}:{}},f=Uy(o.assertions,c);return{dappConfig:u,suite:p,actions:null,assertions:f,prompt:o.prompt,suiteName:i}}function ru(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function Ly(e,t){if(e.post.some((n)=>n.type==="port-listening"&&ru(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function Uy(e,t){let r=e.post;if(!r.some((i)=>i.type==="process-exit-code"))r=[...r,{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"}];if(!r.some((i)=>i.type==="port-listening"&&ru(i)===t))r=[...r,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}];if(!r.some((i)=>i.type==="agent-report-no-failure"))r=[...r,{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}];return{...e,post:r}}function nu(e){if(!e)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32);return t.length>=2?t:void 0}function Vi(e){let t=e.split("/").pop(),r=[hr(e),Rs(hr(e),"src"),hr(hr(e)),Rs(hr(hr(e)),"src")];for(let n of r){if(!Ki(n))continue;if(t){let i=Rs(n,`${t}.compact`);if(Ki(i))return i}let s;try{s=Ty(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return Rs(n,o)}return}var Zl="undeployed",Ql=9932,Ny=300,Ry=600,eu,$y,ql=300000,Xl=4194304,Ji=(e)=>new Promise((t,r)=>{let n=xy("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${ql/1000}s`))},ql);n.stdout?.on("data",(d)=>{if(i+=d.length,i>Xl){a=!0,n.kill("SIGTERM");return}s+=d.toString()}),n.stderr?.on("data",(d)=>{o+=d.toString()}),n.on("error",(d)=>{if(clearTimeout(c),d.code==="ENOENT"){r(Error("claude CLI not found on PATH. Install Claude Code (npm install -g @anthropic-ai/claude-code) or run mn test create without --goal / --screen for the deterministic scaffolder."));return}r(d)}),n.on("exit",(d,u)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${Xl/1024/1024}MB; aborted.`));return}if(u==="SIGTERM")return;if(d!==0){let p=o.trim().slice(0,300)||`(no stderr; exit ${d})`;r(Error(`claude --print exited with code ${d}: ${p}`));return}t(s)}),n.stdin?.write(e),n.stdin?.end()});var zi=x(()=>{Vl();ji();Ns();eu=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],$y=[...eu,"build-and-serve"]});var du={};W(du,{diffState:()=>qy,runActions:()=>By});import{existsSync as ou,readFileSync as iu,writeFileSync as jy,mkdirSync as Wy}from"node:fs";import{join as au}from"node:path";async function By(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:u}=e,p=[],f=r.network??"undeployed",g;if(!a)g=Xy(n,s,f);let{info:h}=At(n),m=zy(h),w;for(let y of t){c?.(y);let S=Date.now();if(w&&(y.type==="contract-call"||y.type==="contract-state")){let b={id:y.id,type:y.type,status:"skip",duration:0,message:`cascaded skip — depends on ${w}`};p.push(b),d?.(y,b);continue}try{let b=await Hy(y,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:g,witnessDeps:m,onMessage:u});if(b.contractAddress){if(g=b.contractAddress,Yy(n,s,f,g),y.type==="contract-deploy")w=void 0}let v=Date.now()-S,R={...b,duration:v};if(p.push(R),d?.(y,R),b.status==="skip"&&y.type==="contract-call")w=`skipped action "${y.id}"`}catch(b){let v=Date.now()-S,R={id:y.id,type:y.type,status:"fail",duration:v,message:b.message};p.push(R),d?.(y,R);break}}return p}async function Hy(e,t){switch(e.type){case"contract-deploy":return Gy(e,t);case"contract-call":return Ky(e,t);case"contract-state":return Jy(e,t);case"wallet-cmd":return Vy(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function Gy(e,t){if(t.contractAddress)return{id:e.id,type:e.type,status:"pass",duration:0,contractAddress:t.contractAddress,message:`Reusing cached contract ${t.contractAddress.slice(0,16)}...`};let r=await Ii({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,servePort:t.servePort,onMessage:t.onMessage});return{id:e.id,type:e.type,status:"pass",duration:0,contractAddress:r.contractAddress,message:`Deployed at ${r.contractAddress.slice(0,16)}...`}}async function Ky(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);if(!e.circuit)throw Error(`Action "${e.id}": missing circuit name.`);let r=t.witnessDeps.get(e.circuit);if(r&&r.length>0)return{id:e.id,type:e.type,status:"skip",duration:0,message:"not CLI-testable — circuit reads private state via witness "+`${r.join(", ")}. Cover with mn test create --strategy ui.`};let n;try{n=await zr({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:()=>{}})}catch{}let s=e.args?Object.values(e.args):[];await _i({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,circuit:e.circuit,args:s,servePort:t.servePort,onMessage:t.onMessage});let o;try{o=await zr({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:()=>{}})}catch{}return{id:e.id,type:e.type,status:"pass",duration:0,message:`${e.circuit} called`,stateBefore:n,stateAfter:o}}async function Jy(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await zr({dappDir:t.dappDir,networkConfig:t.networkConfig,managedDir:t.managedDir,contractName:t.contractName,contractAddress:t.contractAddress,onMessage:t.onMessage});if(e.assert){let n=[];for(let[s,o]of Object.entries(e.assert)){let i=r.fields[s];if(i===void 0){let a=r.maps[s];if(a)qi(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);qi(s,a,o,n)}catch{qi(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1238
|
+
- Be concise — fewer, well-named actions beat many vague ones.`});function Nr(e,t){if(t.length===0)return{byCircuit:new Map};let r=nS(e),n=sS(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,p]of n){o.set(d,new Set),i.set(d,new Set);for(let u of iS(p.body,p.argNames))if(s.has(u))o.get(d).add(u);else if(n.has(u))i.get(d).add(u)}let a=!0;while(a){a=!1;for(let[d,p]of i){let u=o.get(d);for(let g of p)for(let m of o.get(g)??[])if(!u.has(m))u.add(m),a=!0}}let c=new Map;for(let[d,p]of n){if(!p.isCircuit)continue;let u=o.get(d);if(u&&u.size>0)c.set(d,[...u].sort())}return{byCircuit:c}}function nS(e){return e.replace(rS,"").replace(tS,"")}function sS(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,p=c+1;for(;p<e.length&&d>0;p++){let m=e[p];if(m==="{")d++;else if(m==="}")d--}if(d!==0)continue;let u=e.slice(c+1,p-1),g=oS(i);t.set(o,{body:u,argNames:g,isCircuit:s==="circuit"})}return t}function oS(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 iS(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(aS.has(o)||t.has(o))continue;r.add(o)}return r}var tS,rS,aS;var Ws=T(()=>{tS=/\/\/[^\n]*/g,rS=/\/\*[\s\S]*?\*\//g;aS=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var Hu={};be(Hu,{claudeSubprocessRunner:()=>Li,findContractSourcePath:()=>Ui,generateCliScaffoldWithAI:()=>SS,generateUiScaffoldWithAI:()=>bS,isClaudeAvailable:()=>fS});import{execFileSync as cS,spawn as dS}from"node:child_process";import{existsSync as Fi,readdirSync as lS,readFileSync as Mu}from"node:fs";import{dirname as Rr,join as Bs}from"node:path";function fS(){try{return cS("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function ju(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${Ru} ... \`\`\` 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 gS(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=wS(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)"}`);hS(s,o)}return{actions:r}}function hS(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 wS(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 yS(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 SS(e,t=Li){let r=e.contractSourcePath&&Fi(e.contractSourcePath)?Mu(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((S)=>S.name),s=r?Nr(r,n).byCircuit:new Map,o=e.targetCircuit?Ri(e.targetCircuit):void 0,i=Iu({contractName:e.contract.name,contractSummary:Mi({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=ju(a),d=gS(c,e.contract),p=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${Bu(e.goal)??"ai"}`),u=e.network??Fu,g=e.servePort??Lu,m={name:e.contract.name,network:u,prep:Uu},h={name:p,description:c.description,strategy:"cli",timeout:uS},f=vS(c.assertions,g),y=[...s.entries()].filter(([S])=>S!==e.targetCircuit?.name).map(([S,w])=>({name:S,reason:`uses witness ${w.join(", ")} (private state — UI-only)`}));return{dappConfig:m,suite:h,actions:d,assertions:f,prompt:null,suiteName:p,excludedCircuits:y.length>0?y:void 0}}async function bS(e,t=Li){let r=e.screen?Mu(e.screen.path,"utf-8"):void 0,n=_u({contractName:e.contract.name,contractSummary:Mi({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=ju(s);yS(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${Bu(e.goal)??"ai"}`),a=e.network??Fu,c=e.servePort??Lu,d=e.url,p={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:mS};if(e.buildDir)p.buildDir=e.buildDir;let u={name:i,description:o.description,strategy:"browser",timeout:pS,...e.browserMode?{browserMode:e.browserMode}:{}},g=kS(o.assertions,c);return{dappConfig:p,suite:u,actions:null,assertions:g,prompt:o.prompt,suiteName:i}}function Wu(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function vS(e,t){if(e.post.some((n)=>n.type==="port-listening"&&Wu(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function kS(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"&&Wu(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 Bu(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 Ui(e){let t=e.split("/").pop(),r=[Rr(e),Bs(Rr(e),"src"),Rr(Rr(e)),Bs(Rr(Rr(e)),"src")];for(let n of r){if(!Fi(n))continue;if(t){let i=Bs(n,`${t}.compact`);if(Fi(i))return i}let s;try{s=lS(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return Bs(n,o)}return}var Fu="undeployed",Lu=9932,uS=300,pS=600,Uu,mS,Du=300000,Ou=4194304,Li=(e)=>new Promise((t,r)=>{let n=dS("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${Du/1000}s`))},Du);n.stdout?.on("data",(d)=>{if(i+=d.length,i>Ou){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,p)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${Ou/1024/1024}MB; aborted.`));return}if(p==="SIGTERM")return;if(d!==0){let u=o.trim().slice(0,300)||`(no stderr; exit ${d})`;r(Error(`claude --print exited with code ${d}: ${u}`));return}t(s)}),n.stdin?.write(e),n.stdin?.end()});var ji=T(()=>{Pu();Ii();Ws();Uu=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],mS=[...Uu,"build-and-serve"]});import{existsSync as Gu,readFileSync as Ku,writeFileSync as CS,mkdirSync as xS}from"node:fs";import{join as Ju}from"node:path";async function Vu(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:p}=e,u=[],g=r.network??"undeployed",m;if(!a)m=IS(n,s,g);let{info:h}=rt(n),f=$S(h),y;for(let S of t){c?.(S);let w=Date.now();if(y&&(S.type==="contract-call"||S.type==="contract-state")){let b={id:S.id,type:S.type,status:"skip",duration:0,message:`cascaded skip — depends on ${y}`};u.push(b),d?.(S,b);continue}try{let b=await ES(S,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:m,witnessDeps:f,onMessage:p});if(b.contractAddress){if(m=b.contractAddress,_S(n,s,g,m),S.type==="contract-deploy")y=void 0}let x=Date.now()-w,I={...b,duration:x};if(u.push(I),d?.(S,I),b.status==="skip"&&S.type==="contract-call")y=`skipped action "${S.id}"`}catch(b){let x=Date.now()-w,I={id:S.id,type:S.type,status:"fail",duration:x,message:b.message};u.push(I),d?.(S,I);break}}return u}async function ES(e,t){switch(e.type){case"contract-deploy":return AS(e,t);case"contract-call":return TS(e,t);case"contract-state":return NS(e,t);case"wallet-cmd":return RS(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function AS(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 Ds({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 TS(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 xr({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 Os({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 xr({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 NS(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await xr({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)Wi(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);Wi(s,a,o,n)}catch{Wi(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1232
1239
|
${n.join(`
|
|
1233
|
-
`)}`)}return{id:e.id,type:e.type,status:"pass",duration:0,message:`State checked (${Object.keys(r.fields).length} fields, ${Object.keys(r.maps).length} maps)`,stateAfter:r}}function
|
|
1234
|
-
`)}var
|
|
1240
|
+
`)}`)}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 Wi(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 RS(e,t){return{id:e.id,type:e.type,status:"pass",duration:0,message:`wallet-cmd: ${e.cmd??"no command"} (not yet implemented)`}}function $S(e){if(e.witnesses.length===0)return new Map;let t=Ui(e.managedDir);if(!t||!Gu(t))return new Map;let r=Ku(t,"utf-8"),n=e.witnesses.map((s)=>s.name);return Nr(r,n).byCircuit}function qu(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 zu(e,t){return Ju(e,"tests","results",`.contract-cache-${t}.json`)}function IS(e,t,r){let n=zu(e,t);if(!Gu(n))return;try{let s=JSON.parse(Ku(n,"utf-8"));if(s.network!==r)return;return s.address}catch{return}}function _S(e,t,r,n){let s=zu(e,t);xS(Ju(e,"tests","results"),{recursive:!0});let o={address:n,network:r,timestamp:new Date().toISOString()};CS(s,JSON.stringify(o,null,2)+`
|
|
1241
|
+
`)}var Xu=T(()=>{yn();fn();Ws();ji()});var ep={};be(ep,{default:()=>Hs});import{join as Yu}from"node:path";import{mkdirSync as PS}from"node:fs";function DS(e){return Zu.includes(e)}async function Hs(e,t){let r=e.subcommand;if(!r||!DS(r))throw new H(`Usage: midnight test <${Zu.join("|")}>
|
|
1235
1242
|
|
|
1236
1243
|
create Generate dapp.test.json + a CLI test suite from the contract
|
|
1237
1244
|
run Run test suites for the current dApp
|
|
1238
1245
|
list List available test suites
|
|
1239
1246
|
results Show latest test results
|
|
1240
1247
|
|
|
1241
|
-
Run from the root of a dApp project containing dapp.test.json.`);let n=
|
|
1242
|
-
`+
|
|
1248
|
+
Run from the root of a dApp project containing dapp.test.json.`);let n=R(e,"json");switch(r){case"create":return US(e,n);case"run":return HS(e,n,t);case"list":return GS(n);case"results":return KS(e,n)}}function OS(e){let t=(e??"").toLowerCase();if(t==="")return;if(t==="cli"||t==="browser")return t;if(t==="ui")return"browser";throw new H(`Unknown strategy "${e}". Use "cli" or "ui".`)}function MS(e){return e==="preprod"||e==="preview"||e==="undeployed"?e:void 0}function FS(e){let t={},r=A(e,"port");if(r!==void 0){let a=parseInt(r,10);if(!Number.isFinite(a)||a<=0||a>65535)throw new H(`Invalid --port "${r}" — must be 1–65535.`);t.port=a}let n=A(e,"build-cmd");if(n!==void 0)t.buildCmd=n;let s=A(e,"build-dir");if(s!==void 0)t.buildDir=s;let o=A(e,"url");if(o!==void 0)t.url=o;let i=A(e,"browser-mode");if(i!==void 0){if(i!=="dom"&&i!=="vision"&&i!=="script"&&i!=="auto")throw new H(`Invalid --browser-mode "${i}" — must be dom, vision, or script.`);t.browserMode=i}return t}function LS(e){if(e.port===void 0||e.buildCmd===void 0)throw new H("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 US(e,t){let{resolve:r}=await import("node:path");await Promise.resolve().then(() => fn());await Promise.resolve().then(() => Ii());await Promise.resolve().then(() => hu());let i=await Promise.resolve().then(() => (Nu(),{}));await Promise.resolve();let f=await Promise.resolve().then(() => (ji(),Hu));await Promise.resolve().then(() => Pi());let S=r(A(e,"path")??process.cwd()),w=A(e,"name"),b=A(e,"suite"),x=MS(A(e,"network")),I=R(e,"force"),O=!t&&Cu(),z=A(e,"goal"),Q=A(e,"screen"),K=R(e,"no-ai"),F=OS(A(e,"strategy"))??(O?await xu():"cli"),ee;if(F==="browser"){let Se=FS(e);ee=O?await Eu(Se):LS(Se)}let{info:pe}=rt(S,w),le=!K&&f.isClaudeAvailable(),ge=!K&&(z!==void 0||Q!==void 0||O&&le),te=ge?await jS({strategy:F,info:pe,dappDir:S,browser:ee,network:x,suiteName:b,goalFlag:z,screenFlag:Q,interactive:O,jsonMode:t,ai:f,promptCircuit:Au,promptScreen:Di,promptGoal:Tu,promptSuiteName:Oi,discoverScreens:bu})??$i(pe.circuits,{contractName:pe.name,suiteName:b,strategy:F,browser:ee,network:x}):$i(pe.circuits,{contractName:pe.name,suiteName:b,strategy:F,browser:ee,network:x});if(O&&!b){let Se=await Oi(te.suiteName);if(Se!==te.suiteName)te.suiteName=Se,te.suite.name=Se}let Oe=gu(te,{dappDir:S,force:I});if(t){_({subcommand:"create",contractName:pe.name,suiteName:te.suiteName,strategy:F,aiAssisted:ge&&te.suiteName!=="cli-default"&&te.suiteName!=="ui-default",written:Oe.written,excludedCircuits:te.excludedCircuits});return}process.stderr.write(`
|
|
1249
|
+
`+j(`Test scaffold: ${pe.name}`)+`
|
|
1243
1250
|
|
|
1244
|
-
`);for(let
|
|
1245
|
-
`);let
|
|
1251
|
+
`);for(let Se of Oe.written)process.stderr.write(` ${B("✓")} ${Se}
|
|
1252
|
+
`);let Ae=F==="browser"?{file:"prompt.md",hint:"verify the UI steps match your dApp — exact button labels, expected screens, success criteria. Claude follows these literally."}:{file:"actions.json",hint:'review args — placeholder values like 0 may violate contract assertions (e.g. "amount > 0").'};if(te.excludedCircuits&&te.excludedCircuits.length>0){process.stderr.write(`
|
|
1246
1253
|
`+l(" Skipped (not CLI-testable):")+`
|
|
1247
|
-
`);for(let
|
|
1254
|
+
`);for(let Se of te.excludedCircuits)process.stderr.write(` ${D("!")} ${Se.name} ${l("— "+Se.reason)}
|
|
1248
1255
|
`);process.stderr.write(l(` These need the dApp UI to populate private state first.
|
|
1249
1256
|
`)),process.stderr.write(l(` Cover them with a browser-strategy suite (mn test create --strategy ui).
|
|
1250
1257
|
`))}process.stderr.write(`
|
|
1251
1258
|
`+l(" Next:")+`
|
|
1252
|
-
`),process.stderr.write(l(" Edit ")+L(`tests/suites/${
|
|
1253
|
-
`),process.stderr.write(l(" ")+l(
|
|
1254
|
-
`),process.stderr.write(l(" Run ")+L(`mn test run --suite ${
|
|
1259
|
+
`),process.stderr.write(l(" Edit ")+L(`tests/suites/${te.suiteName}/${Ae.file}`)+`
|
|
1260
|
+
`),process.stderr.write(l(" ")+l(Ae.hint)+`
|
|
1261
|
+
`),process.stderr.write(l(" Run ")+L(`mn test run --suite ${te.suiteName}`)+`
|
|
1255
1262
|
`),process.stderr.write(l(" List ")+L("mn test list")+l(" (see every suite in this project)")+`
|
|
1256
1263
|
|
|
1257
|
-
`)}async function
|
|
1264
|
+
`)}async function jS(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 WS(e,t);return await BS(e,t)}catch(t){return process.stderr.write(`
|
|
1258
1265
|
${l("AI scaffold failed, falling back to deterministic:")} ${t.message}
|
|
1259
|
-
`),null}}async function
|
|
1260
|
-
`+
|
|
1266
|
+
`),null}}async function Qu(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 WS(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(() => Ws());let i=s(n,"utf-8"),a=e.info.witnesses.map((p)=>p.name),d=Nr(i,a).byCircuit.get(r.name);if(d&&d.length>0)process.stderr.write(`
|
|
1267
|
+
`+D("!")+` ${r.name} calls ${d.join(", ")} — a witness that reads private state.
|
|
1261
1268
|
`),process.stderr.write(l(` The CLI suite will deploy + run, but expect a "Cannot read properties of undefined" failure
|
|
1262
1269
|
`)+l(` unless the dApp UI populates that state first. Consider --strategy ui instead.
|
|
1263
|
-
`))}return
|
|
1264
|
-
`+
|
|
1270
|
+
`))}return Qu("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 BS(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 Qu("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 HS(e,t,r){let{config:n,dappDir:s}=Us(),o=Ei(s),i=A(e,"suite"),a;if(i){if(a=o.find((m)=>m.suite.name===i),!a){let m=o.map((h)=>h.suite.name).join(", ")||"none found";throw new H(`Suite "${i}" not found. Available: ${m}`)}}else if(o.length>0)a=o[0];PS(Yu(s,"tests","results"),{recursive:!0});let c=Date.now(),d=new Date().toISOString();if(!t){if(process.stderr.write(`
|
|
1271
|
+
`+j(`E2E Test: ${n.name}`)+`
|
|
1265
1272
|
|
|
1266
1273
|
`),process.stderr.write(C("Network",n.network??"undeployed")+`
|
|
1267
1274
|
`),n.port)process.stderr.write(C("Port",String(n.port))+`
|
|
1268
1275
|
`);if(a){if(process.stderr.write(C("Suite",a.suite.name)+`
|
|
1269
1276
|
`),process.stderr.write(C("Strategy",a.suite.strategy)+`
|
|
1270
|
-
`),a.suite.strategy==="browser"){let
|
|
1277
|
+
`),a.suite.strategy==="browser"){let m=Ai(a.suite);process.stderr.write(C("Browser Mode",m)+`
|
|
1271
1278
|
`)}}process.stderr.write(`
|
|
1272
|
-
`)}let
|
|
1273
|
-
`)};r?.addEventListener("abort",()=>
|
|
1274
|
-
`));let
|
|
1275
|
-
`);let
|
|
1279
|
+
`)}let p=Gl(),u=[],g=(m)=>{if(!t)process.stderr.write(l(` [teardown] ${m}`)+`
|
|
1280
|
+
`)};r?.addEventListener("abort",()=>Ni(p,g),{once:!0});try{if(!t)process.stderr.write(k(` Prep
|
|
1281
|
+
`));let m=G("Starting prep..."),h=await Xl(n,s,p,{onStepStart(M){m.update(`[prep] ${M}...`)},onStepComplete(M,F,ee,pe){if(F==="pass")m.stop(`${B("✓")} ${M} (${JS(ee)})`);else m.stop(`${J("✗")} ${M}: ${pe??"failed"}`);m=G("")},onMessage(M){m.update(M)}});if(m.stop(""),u.push(...h),!t)process.stderr.write(`
|
|
1282
|
+
`);let f=0,y="";if(a){let M=a.suite;if(M.strategy==="browser"){let F=Bl(a.suiteDir);if(!F)throw Error(`No prompt.md found in ${a.suiteDir} — required for browser strategy`);if(y=Yu(s,"tests","results",`${M.name}_${d.replace(/[:.]/g,"-")}_claude.log`),!t)process.stderr.write(k(` Browser Test
|
|
1276
1283
|
`)),process.stderr.write(l(` Claude will take over the terminal. Output is also logged.
|
|
1277
1284
|
|
|
1278
|
-
`));let ee=await
|
|
1279
|
-
`)}});if(
|
|
1280
|
-
`),ee.timedOut)process.stderr.write(` ${
|
|
1281
|
-
`);else process.stderr.write(` ${
|
|
1282
|
-
`)}else if(
|
|
1285
|
+
`));let ee=await Ql({suite:M,prompt:F,dappDir:s,logFile:y,onMessage:(pe)=>{if(!t)process.stderr.write(l(` ${pe}`)+`
|
|
1286
|
+
`)}});if(f=ee.exitCode,!t)if(process.stderr.write(`
|
|
1287
|
+
`),ee.timedOut)process.stderr.write(` ${J("✗")} Browser test timed out
|
|
1288
|
+
`);else process.stderr.write(` ${f===0?B("✓"):J("✗")} Claude exited with code ${f}
|
|
1289
|
+
`)}else if(M.strategy==="cli"){let F=Wl(a.suiteDir);if(!F)throw Error(`No actions.json found in ${a.suiteDir} — required for CLI strategy`);if(!t)process.stderr.write(k(` CLI Test
|
|
1283
1290
|
`)),process.stderr.write(l(` Executing ${F.actions.length} action(s)
|
|
1284
1291
|
|
|
1285
|
-
`));
|
|
1286
|
-
`)}}},onMessage:(
|
|
1287
|
-
`);let
|
|
1288
|
-
`)}
|
|
1289
|
-
`));let
|
|
1292
|
+
`));await Promise.resolve().then(() => Xu());await Promise.resolve().then(() => Ce());let ge=n.network??"undeployed",{config:te}=de({args:{command:"test",subcommand:"run",positionals:[],flags:{network:ge}}});await Promise.resolve();let Ae=p.serveHandle?.port??Mt,Se=R(e,"redeploy"),st=await Vu({actions:F.actions,config:n,dappDir:s,suiteName:M.name,networkConfig:te,servePort:Ae,redeploy:Se,onActionStart:(me)=>{if(!t){let fe=G(`[${me.id}] ${me.type}${me.circuit?` ${me.circuit}`:""}...`);me._spinner=fe}},onActionComplete:(me,fe)=>{if(!t){let qe=me._spinner;if(qe)if(fe.status==="pass")qe.stop(`${B("✓")} ${me.id}: ${fe.message??"pass"}`);else if(fe.status==="skip")qe.stop(`${D("⊘")} ${me.id}: ${fe.message??"skipped"}`);else qe.stop(`${J("✗")} ${me.id}: ${fe.message??"fail"}`);if(fe.stateBefore&&fe.stateAfter){let E=qu(fe.stateBefore,fe.stateAfter);if(E.length>0)for(let v of E)process.stderr.write(l(` ${v.field}: ${v.before} → `)+L(v.after)+`
|
|
1293
|
+
`)}}},onMessage:(me)=>{}});if(f=st.some((me)=>me.status==="fail")?1:0,!t){process.stderr.write(`
|
|
1294
|
+
`);let me=st.filter((v)=>v.status==="pass").length,fe=st.filter((v)=>v.status==="skip").length,qe=st.filter((v)=>v.status==="fail").length,E=B(String(me)+" passed");if(fe>0)E+=`, ${D(String(fe)+" skipped")}`;if(qe>0)E+=`, ${J(String(qe)+" failed")}`;process.stderr.write(` Actions: ${E}
|
|
1295
|
+
`)}p._actionResults=st}}else if(!t)process.stderr.write(l(` No test suites found — only prep was run
|
|
1296
|
+
`));let S={processExitCode:f,agentLogPath:y},w=[];if(a){let M=jl(a.suiteDir);if(M&&M.post.length>0){if(!t)process.stderr.write(`
|
|
1290
1297
|
`+k(` Assertions
|
|
1291
|
-
`));if(
|
|
1292
|
-
`)}}}let b=Math.round((Date.now()-c)/1000),
|
|
1293
|
-
`+
|
|
1294
|
-
`),process.stderr.write(` ${
|
|
1295
|
-
`),process.stderr.write(l(` Results: ${
|
|
1298
|
+
`));if(w=await tu(M.post,S),!t)for(let F of w){let ee=F.status==="pass"?B("✓"):J("✗"),pe=F.message?l(` — ${F.message}`):"";process.stderr.write(` ${ee} ${F.id}${pe}
|
|
1299
|
+
`)}}}let b=Math.round((Date.now()-c)/1000),x=u.every((M)=>M.status==="pass"),I=w.every((M)=>M.status==="pass"),O=x&&I&&f===0?"pass":"fail",z=p._actionResults,Q={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:O,prep:u,actions:z?.map((M)=>({id:M.id,type:M.type,status:M.status,duration:M.duration,message:M.message,contractAddress:M.contractAddress})),assertions:w,testOutput:y?{exitCode:f,logFile:y}:void 0},K=su(Q,s);if(t)_(Q);else process.stderr.write(`
|
|
1300
|
+
`+V()+`
|
|
1301
|
+
`),process.stderr.write(` ${O==="pass"?B(k("PASS")):J(k("FAIL"))} — ${n.name} (${b}s)
|
|
1302
|
+
`),process.stderr.write(l(` Results: ${K}`)+`
|
|
1296
1303
|
|
|
1297
|
-
`);if(
|
|
1298
|
-
`+
|
|
1304
|
+
`);if(O==="fail")process.exitCode=1}finally{await Ni(p,g)}}function GS(e){let{config:t,dappDir:r}=Us(),n=Ei(r);if(e){_({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(`
|
|
1305
|
+
`+j(`Tests: ${t.name}`)+`
|
|
1299
1306
|
|
|
1300
1307
|
`),n.length===0)process.stderr.write(l(` No test suites found.
|
|
1301
1308
|
`)),process.stderr.write(l(` Create tests/suites/<name>/suite.json to add one.
|
|
@@ -1304,57 +1311,57 @@ Run from the root of a dApp project containing dapp.test.json.`);let n=N(e,"json
|
|
|
1304
1311
|
`),process.stderr.write(l(` strategy: ${s.strategy}`)+(s.timeout?l(`, timeout: ${s.timeout}s`):"")+`
|
|
1305
1312
|
|
|
1306
1313
|
`);process.stderr.write(`
|
|
1307
|
-
`)}function
|
|
1308
|
-
`+
|
|
1314
|
+
`)}function KS(e,t){let{config:r,dappDir:n}=Us(),s=R(e,"all"),o=A(e,"suite"),i=s?Ti(n,o):(()=>{let a=ou(n,o);return a?[a]:[]})();if(t){_(s?{dapp:r.name,results:i}:i[0]??{});return}if(process.stderr.write(`
|
|
1315
|
+
`+j(`Results: ${r.name}`)+`
|
|
1309
1316
|
|
|
1310
1317
|
`),i.length===0)process.stderr.write(l(` No test results found.
|
|
1311
1318
|
`)),process.stderr.write(l(` Run "midnight test run" to generate results.
|
|
1312
|
-
`));else for(let a of i){let c=a.status==="pass"?
|
|
1319
|
+
`));else for(let a of i){let c=a.status==="pass"?B("✓"):J("✗"),d=a.status==="pass"?B(k("PASS")):J(k("FAIL"));process.stderr.write(` ${c} ${k(a.suite)} — ${d} (${a.duration}s)
|
|
1313
1320
|
`),process.stderr.write(l(` ${a.timestamp} | ${a.network} | ${a.strategy}`)+`
|
|
1314
|
-
`);let
|
|
1315
|
-
`);let
|
|
1321
|
+
`);let p=a.prep.filter((g)=>g.status==="fail");if(p.length>0)process.stderr.write(J(` prep: ${p.length} failed`)+`
|
|
1322
|
+
`);let u=a.assertions.filter((g)=>g.status==="fail");if(u.length>0)process.stderr.write(J(` assertions: ${u.length} failed`)+`
|
|
1316
1323
|
`);process.stderr.write(`
|
|
1317
1324
|
`)}process.stderr.write(`
|
|
1318
|
-
`)}function uS(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var pu;var Yi=x(()=>{He();ue();ze();nl();ml();hl();yl();kl();Cl();pu=["run","list","results","create"]});var ES={};import{readFileSync as gu}from"node:fs";import{fileURLToPath as yu}from"node:url";import{Server as pS}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mS}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as fS,CallToolRequestSchema as gS,ListResourcesRequestSchema as hS,ReadResourceRequestSchema as wS}from"@modelcontextprotocol/sdk/types.js";function Se(e,t,r){let n={json:!0},s=[];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;let a=o==="full"?yr:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}async function ne(e){let t=vS[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}function CS(e,t){let r=t.network??"active network",n=t.wallet??"active wallet";switch(e){case"midnight_transfer":return`Send ${t.amount} NIGHT from ${n} to ${t.to} on ${r}`;case"midnight_contract_deploy":{let s=t.args?` with args ${t.args}`:"";return`Deploy contract from ${t.path??"current directory"} as ${n} on ${r}${s}`}case"midnight_contract_call":{let s=t.args?` with args ${t.args}`:"";return`Call circuit ${t.circuit} on contract ${t.address} as ${n} on ${r}${s}`}default:return`Execute ${e} with ${JSON.stringify(t)}`}}function Qi(e){return{...e,_serverVersion:Ge}}async function wu(e,t){let r=vu.find((n)=>n.name===e);if(!r)return Zi(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(Qi(n),null,2)}]}}catch(n){return Zi(n instanceof Error?n:Error(String(n)))}}function Zi(e){let{errorCode:t}=Ar(e);return{content:[{type:"text",text:JSON.stringify(Qi({error:!0,code:t,message:Da(e.message)}))}],isError:!0}}async function AS(){await Ir();let e=new mS;await Qr.connect(e)}var Su="midnight-wallet://skill/core",bu="midnight-wallet://skill/full",yS="midnight-wallet://skill",SS,bS,vS,vu,kS,hu,Qr;var ku=x(()=>{Cn();Ys();Tr();Oa();go();SS=yu(new URL("../docs/SKILL-CORE.md",import.meta.url)),bS=yu(new URL("../docs/SKILL.md",import.meta.url));vS={generate:()=>Promise.resolve().then(() => (wo(),ho)),info:()=>Promise.resolve().then(() => (So(),yo)),balance:()=>Promise.resolve().then(() => (Ko(),Go)),address:()=>Promise.resolve().then(() => (Vo(),Jo)),"genesis-address":()=>Promise.resolve().then(() => (qo(),zo)),"inspect-cost":()=>Promise.resolve().then(() => (Yo(),Xo)),airdrop:()=>Promise.resolve().then(() => (Yn(),Xn)),transfer:()=>Promise.resolve().then(() => (Qo(),Zo)),dust:()=>Promise.resolve().then(() => (Qn(),Zn)),cache:()=>Promise.resolve().then(() => (ti(),ei)),config:()=>Promise.resolve().then(() => (ni(),ri)),localnet:()=>Promise.resolve().then(() => (li(),di)),wallet:()=>Promise.resolve().then(() => (os(),ss)),status:()=>Promise.resolve().then(() => (ud(),ld)),contract:()=>Promise.resolve().then(() => (Cs(),ks)),test:()=>Promise.resolve().then(() => (Yi(),Xi))};vu=[{name:"midnight_wallet_generate",description:"Create wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"64-char hex"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=Se("wallet",e,"generate");if(r.positionals=[t],delete r.flags.name,e.force==="true"||e.force===!0)r.flags.force=!0;let n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_list",description:"List wallets. Default: per-wallet { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the 3-network addresses + shieldedAddresses maps.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Return full per-network addresses + shieldedAddresses maps (the same shape `mn wallet list --json` emits). Default false (slim)."}}},async handler({full:e}={}){let t={json:!0};if(e)t[yr]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_use",description:"Set active wallet.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"use",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_info",description:"Show wallet details. Default: { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the per-network maps + createdAt + file path.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},full:{type:"boolean",description:"Return the full per-network addresses + shieldedAddresses maps and bookkeeping fields (matches `mn wallet info <name> --json`). Default false (slim)."}}},async handler(e){let{name:t,full:r}=e,n={json:!0};if(r)n[yr]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await ne("wallet");return q(o,s)}},{name:"midnight_wallet_remove",description:"Remove wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"remove",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return q(n,r)}},{name:"midnight_info",description:"Wallet metadata.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=Se("info",e),r=await ne("info");return q(r,t)}},{name:"midnight_balance",description:"NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string"},full:{type:"boolean",description:"Include the queried address + shieldedAddress in the response (matches `mn balance --json`). Default false (slim)."}}},async handler(e){let t=e.address,r=Se("balance",e,t);delete r.flags.address;let n=await ne("balance");return q(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64-char hex"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=Se("address",e),r=await ne("address");return q(r,t)}},{name:"midnight_genesis_address",description:"Genesis address.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]}}},async handler(e){let t=Se("genesis-address",e),r=await ne("genesis-address");return q(r,t)}},{name:"midnight_inspect_cost",description:"Block limits.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e=Se("inspect-cost",{}),t=await ne("inspect-cost");return q(t,e)}},{name:"midnight_airdrop",description:'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.',annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{amount:{type:"string",description:"NIGHT"},wallet:{type:"string",description:"Destination: wallet name, JSON path, or bech32m address"},shielded:{type:"string",description:'Set to "true" for shielded airdrop'}},required:["amount"]},async handler(e){let t=e.amount,r=Se("airdrop",e,t);delete r.flags.amount;let n=await ne("airdrop");return q(n,r)}},{name:"midnight_transfer",description:"Send NIGHT (returns pending token; see skill).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{to:{type:"string",description:"bech32m"},amount:{type:"string",description:"NIGHT"},wallet:{type:"string"}},required:["to","amount"]},async handler(e){let{to:t,amount:r}=e,n=Se("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await ne("transfer");return q(s,n)}},{name:"midnight_dust_register",description:"Register for dust.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=Se("dust",e,"register"),r=await ne("dust");return q(r,t)}},{name:"midnight_dust_status",description:"Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},"proof-server":{type:"string"},node:{type:"string"},"indexer-ws":{type:"string"},"no-cache":{type:"string"},full:{type:"boolean",description:"Include sync internals (eventsApplied, ownedUtxos, cached) in the response (matches `mn dust status --json`). Default false (slim)."}}},async handler(e){let t=Se("dust",e,"status"),r=await ne("dust");return q(r,t)}},{name:"midnight_config_get",description:"Read config.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"get",positionals:[e.key],flags:{json:!0}},n=await ne("config");return q(n,r)}},{name:"midnight_config_set",description:"Write config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"},value:{type:"string"}},required:["key","value"]},async handler(e){let{key:t,value:r}=e,n={command:"config",subcommand:"set",positionals:[t,r],flags:{json:!0}},s=await ne("config");return q(s,n)}},{name:"midnight_cache_clear",description:"Clear sync cache.",annotations:{destructiveHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]},wallet:{type:"string"}}},async handler(e){let t=Se("cache",e,"clear"),r=await ne("cache");return q(r,t)}},{name:"midnight_config_unset",description:"Reset config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"unset",positionals:[e.key],flags:{json:!0}},n=await ne("config");return q(n,r)}},{name:"midnight_localnet_up",description:"Start localnet (Docker).",annotations:{openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_stop",description:"Stop localnet (preserves state).",annotations:{idempotentHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"stop",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_down",description:"Localnet teardown (volumes + undeployed cache).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"down",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_status",description:"Localnet status.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"status",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_clean",description:"Remove stray containers.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"clean",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_contract_inspect",description:"Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed/<name>/compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path)"},name:{type:"string",description:"Specific contract name to inspect when the project has multiple (see siblings field)"}}},async handler(e){let t=Se("contract",e,"inspect"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_state",description:"Read the current ledger state of a deployed contract. Returns the ledger fields as a JSON object.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},path:{type:"string",description:"dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address"]},async handler(e){let t=Se("contract",e,"state"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_deploy",description:"Deploy a compiled Compact contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of constructor arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}}},async handler(e){let t=Se("contract",e,"deploy"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_call",description:"Call a circuit on a deployed contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},circuit:{type:"string",description:"Circuit name to invoke"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of circuit arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address","circuit"]},async handler(e){let t=Se("contract",e,"call"),r=await ne("contract");return q(r,t)}},{name:"midnight_test_create",description:"Generate a test scaffold for the contract. Two paths: (1) AI-assisted — pass `goal` (and optionally `screen` for UI strategy) and the scaffold is generated by Claude reading the contract + screen source, producing a focused suite with realistic args / on-screen labels. (2) Deterministic — pass `no-ai: true` (or omit goal/screen in non-interactive mode) for boilerplate scaffolds that the user reviews. CLI strategy emits dapp.test.json + tests/suites/<name>/{suite,actions,assertions}.json. Browser strategy emits prompt.md instead of actions.json plus the browser fields in dapp.test.json — required: port, build-cmd. Use force:true to overwrite.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"dApp directory (defaults to cwd)"},name:{type:"string",description:"Specific contract name when the project has multiple"},suite:{type:"string",description:"Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)"},strategy:{type:"string",enum:["cli","browser"],description:"cli (default): drive contracts via actions.json. browser: drive a real UI via Claude + Chrome via prompt.md."},network:{type:"string",enum:["preprod","preview","undeployed"]},goal:{type:"string",description:'AI mode: one-line success criterion this suite should verify (e.g. "round goes from 0 to 1 after increment"). Triggers AI scaffolding.'},screen:{type:"string",description:'AI mode + browser strategy: name of the screen component to focus on (e.g. "loan-request-form" or "LoanRequestForm"). Auto-discovered from src/components, src/pages, src/screens.'},"no-ai":{type:"boolean",description:"Force deterministic scaffolder even when claude CLI is available."},port:{type:"string",description:'Browser strategy only — dev server port (e.g. "4173").'},"build-cmd":{type:"string",description:'Browser strategy only — shell command that builds + serves the UI (e.g. "npm run dev").'},"build-dir":{type:"string",description:"Browser strategy only — subdir the build runs in (monorepo case)."},url:{type:"string",description:"Browser strategy only — full URL Claude opens (default http://localhost:<port>/)."},"browser-mode":{type:"string",enum:["dom","vision","script"],description:"Browser strategy only — how Claude perceives the page. dom (HTML/React UIs, fast, needs chrome-devtools-mcp), vision (canvas games, slow), script (advanced, needs hooks). Default: dom for AI scaffolds."},force:{type:"boolean",description:"Overwrite existing files instead of aborting on collision"}}},async handler(e){let t=Se("test",e,"create"),r=await ne("test");return q(r,t)}},{name:"midnight_localnet_logs",description:"Snapshot of recent localnet logs (last N lines per service, no streaming). Returns { tail, lines: string[] }.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{tail:{type:"string",description:"Number of lines to retrieve (default 200)"}}},async handler(e){let t=Se("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await ne("localnet");return q(r,t)}},{name:"midnight_confirm_operation",description:"Redeem a pending token (confirm step).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{token:{type:"string"}},required:["token"]},async handler(){throw Error("midnight_confirm_operation reached the inner handler — this is an MCP wiring bug")}}],kS=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),hu=Pa();Qr=new pS({name:"midnight-wallet-cli",version:Ge},{capabilities:{tools:{},resources:{}}});Qr.setRequestHandler(hS,async()=>({resources:[{uri:Su,name:"midnight-wallet skill (core)",description:"Read this first. Intent routing table + non-negotiable safety rules. ~830 tokens. Fetch /full on demand for canonical flows, error recovery, and concept primers.",mimeType:"text/markdown"},{uri:bu,name:"midnight-wallet skill (full)",description:"Canonical multi-step flows, error-recovery recipes, concept primers (NIGHT/DUST/shielded), network selection. Fetch on demand when you hit an error, start a multi-step flow, or need to explain a concept.",mimeType:"text/markdown"}]}));Qr.setRequestHandler(wS,async(e)=>{let t=e.params.uri;if(t===Su){let r=gu(SS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===bu||t===yS){let r=gu(bS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Qr.setRequestHandler(fS,async()=>({tools:vu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Qr.setRequestHandler(gS,async(e)=>{let{name:t,arguments:r}=e.params,n=r??{};if(t==="midnight_confirm_operation"){let s=typeof n.token==="string"?n.token:"",o=hu.redeem(s);if(!o)return Zi(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return wu(o.tool,o.args)}if(kS.has(t)){let s=hu.create({tool:t,args:n,description:CS(t,n)});return{content:[{type:"text",text:JSON.stringify(Qi({pending:!0,token:s.token,description:s.description,tool:s.tool,expiresAt:new Date(s.expiresAt).toISOString(),nextStep:"Show the description to the user, get explicit consent, then call midnight_confirm_operation with this token."}),null,2)}]}}return wu(t,n)});AS().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1319
|
-
`),process.exit(1)})});function
|
|
1320
|
-
`),n=Math.floor(e*100);if(t>=1)return
|
|
1321
|
-
`);return r.map((s,o)=>Array.from(s).map((i,a)=>{if(i===" ")return" ";let c=(o*131+a*997)%100/100;return t>=c?i:
|
|
1322
|
-
`)}var
|
|
1323
|
-
`)
|
|
1324
|
-
`),o=s.length,i=36,a=Math.max(o,t?.length??0),c=3,d=r?.animated??!0;if(!
|
|
1325
|
-
`:"\x1B[36G"+
|
|
1326
|
-
`);else process.stderr.write(
|
|
1327
|
-
`)}return}function
|
|
1328
|
-
`);else process.stderr.write(
|
|
1329
|
-
`)}}function
|
|
1330
|
-
`);if(
|
|
1325
|
+
`)}function JS(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var Zu;var Bi=T(()=>{Fe();ue();tt();Hl();Yl();eu();ru();iu();au();Zu=["run","list","results","create"]});import{readFileSync as tp}from"node:fs";import{fileURLToPath as sp}from"node:url";import{Server as VS}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as qS}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as zS,CallToolRequestSchema as XS,ListResourcesRequestSchema as YS,ReadResourceRequestSchema as ZS}from"@modelcontextprotocol/sdk/types.js";function Ee(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"?_r:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}async function ne(e){let t=rb[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}function sb(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 Gi(e){return{...e,_serverVersion:Ze}}async function np(e,t){let r=ap.find((n)=>n.name===e);if(!r)return Hi(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(Gi(n),null,2)}]}}catch(n){return Hi(n instanceof Error?n:Error(String(n)))}}function Hi(e){let{errorCode:t}=Ur(e);return{content:[{type:"text",text:JSON.stringify(Gi({error:!0,code:t,message:Ya(e.message)}))}],isError:!0}}async function ob(){await Zr();let e=new qS;await vn.connect(e)}var op="midnight-wallet://skill/core",ip="midnight-wallet://skill/full",QS="midnight-wallet://skill",eb,tb,rb,ap,nb,rp,vn;var cp=T(()=>{Pn();so();Br();Qa();yo();eb=sp(new URL("../docs/SKILL-CORE.md",import.meta.url)),tb=sp(new URL("../docs/SKILL.md",import.meta.url));rb={generate:()=>Promise.resolve().then(() => (bo(),nc)),info:()=>Promise.resolve().then(() => (vo(),sc)),balance:()=>Promise.resolve().then(() => (Jo(),Qc)),address:()=>Promise.resolve().then(() => (Vo(),ed)),"genesis-address":()=>Promise.resolve().then(() => (qo(),td)),"inspect-cost":()=>Promise.resolve().then(() => (zo(),nd)),airdrop:()=>Promise.resolve().then(() => (cs(),id)),transfer:()=>Promise.resolve().then(() => (Xo(),dd)),dust:()=>Promise.resolve().then(() => (ls(),pd)),cache:()=>Promise.resolve().then(() => (Yo(),md)),config:()=>Promise.resolve().then(() => (Zo(),fd)),localnet:()=>Promise.resolve().then(() => (ni(),_d)),wallet:()=>Promise.resolve().then(() => (ws(),Od)),status:()=>Promise.resolve().then(() => (Wd(),jd)),contract:()=>Promise.resolve().then(() => (Ls(),Ol)),test:()=>Promise.resolve().then(() => (Bi(),ep))};ap=[{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 or 128 hex chars (32-byte raw or 64-byte BIP-39)"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=Ee("wallet",e,"generate");if(r.positionals=[t],delete r.flags.name,e.force==="true"||e.force===!0)r.flags.force=!0;let n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_list",description:"List wallets. Default: per-wallet { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the 3-network addresses + shieldedAddresses maps.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Return full per-network addresses + shieldedAddresses maps (the same shape `mn wallet list --json` emits). Default false (slim)."}}},async handler({full:e}={}){let t={json:!0};if(e)t[_r]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_use",description:"Set active wallet.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"use",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return q(n,r)}},{name:"midnight_wallet_info",description:"Show wallet details. Default: { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the per-network maps + createdAt + file path.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},full:{type:"boolean",description:"Return the full per-network addresses + shieldedAddresses maps and bookkeeping fields (matches `mn wallet info <name> --json`). Default false (slim)."}}},async handler(e){let{name:t,full:r}=e,n={json:!0};if(r)n[_r]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await ne("wallet");return q(o,s)}},{name:"midnight_wallet_remove",description:"Remove wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"}},required:["name"]},async handler(e){let r={command:"wallet",subcommand:"remove",positionals:[e.name],flags:{json:!0}},n=await ne("wallet");return q(n,r)}},{name:"midnight_info",description:"Wallet metadata.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=Ee("info",e),r=await ne("info");return q(r,t)}},{name:"midnight_balance",description:"NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string"},full:{type:"boolean",description:"Include the queried address + shieldedAddress in the response (matches `mn balance --json`). Default false (slim)."}}},async handler(e){let t=e.address,r=Ee("balance",e,t);delete r.flags.address;let n=await ne("balance");return q(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64 or 128 hex chars (32-byte raw or 64-byte BIP-39)"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=Ee("address",e),r=await ne("address");return q(r,t)}},{name:"midnight_genesis_address",description:"Genesis address.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]}}},async handler(e){let t=Ee("genesis-address",e),r=await ne("genesis-address");return q(r,t)}},{name:"midnight_inspect_cost",description:"Block limits.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e=Ee("inspect-cost",{}),t=await ne("inspect-cost");return q(t,e)}},{name:"midnight_airdrop",description:'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.',annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{amount:{type:"string",description:"NIGHT"},wallet:{type:"string",description:"Destination: wallet name, JSON path, or bech32m address"},shielded:{type:"string",description:'Set to "true" for shielded airdrop'}},required:["amount"]},async handler(e){let t=e.amount,r=Ee("airdrop",e,t);delete r.flags.amount;let n=await ne("airdrop");return q(n,r)}},{name:"midnight_transfer",description:"Send NIGHT (returns pending token; see skill).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{to:{type:"string",description:"bech32m"},amount:{type:"string",description:"NIGHT"},wallet:{type:"string"}},required:["to","amount"]},async handler(e){let{to:t,amount:r}=e,n=Ee("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await ne("transfer");return q(s,n)}},{name:"midnight_dust_register",description:"Register for dust.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=Ee("dust",e,"register"),r=await ne("dust");return q(r,t)}},{name:"midnight_dust_status",description:"Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},"proof-server":{type:"string"},node:{type:"string"},"indexer-ws":{type:"string"},"no-cache":{type:"string"},full:{type:"boolean",description:"Include sync internals (eventsApplied, ownedUtxos, cached) in the response (matches `mn dust status --json`). Default false (slim)."}}},async handler(e){let t=Ee("dust",e,"status"),r=await ne("dust");return q(r,t)}},{name:"midnight_config_get",description:"Read config.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"get",positionals:[e.key],flags:{json:!0}},n=await ne("config");return q(n,r)}},{name:"midnight_config_set",description:"Write config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"},value:{type:"string"}},required:["key","value"]},async handler(e){let{key:t,value:r}=e,n={command:"config",subcommand:"set",positionals:[t,r],flags:{json:!0}},s=await ne("config");return q(s,n)}},{name:"midnight_cache_clear",description:"Clear sync cache.",annotations:{destructiveHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]},wallet:{type:"string"}}},async handler(e){let t=Ee("cache",e,"clear"),r=await ne("cache");return q(r,t)}},{name:"midnight_config_unset",description:"Reset config.",annotations:{idempotentHint:!0},inputSchema:{type:"object",properties:{key:{type:"string"}},required:["key"]},async handler(e){let r={command:"config",subcommand:"unset",positionals:[e.key],flags:{json:!0}},n=await ne("config");return q(n,r)}},{name:"midnight_localnet_up",description:"Refused on this ledger-9 build: mn's localnet is ledger 8 and no ledger-9 indexer image is published. Run a ledger-9 stack yourself and point mn at it (config_set node / indexer-ws / proof-server).",annotations:{openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_stop",description:"Stop localnet (preserves state).",annotations:{idempotentHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"stop",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_down",description:"Localnet teardown (volumes + undeployed cache).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"down",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_status",description:"Localnet status.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"status",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_localnet_clean",description:"Remove stray containers.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"clean",positionals:[],flags:{json:!0}},t=await ne("localnet");return q(t,e)}},{name:"midnight_contract_inspect",description:"Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed/<name>/compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path)"},name:{type:"string",description:"Specific contract name to inspect when the project has multiple (see siblings field)"}}},async handler(e){let t=Ee("contract",e,"inspect"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_state",description:"Read the current ledger state of a deployed contract. Returns the ledger fields as a JSON object.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},path:{type:"string",description:"dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address"]},async handler(e){let t=Ee("contract",e,"state"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_deploy",description:"Deploy a compiled Compact contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of constructor arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}}},async handler(e){let t=Ee("contract",e,"deploy"),r=await ne("contract");return q(r,t)}},{name:"midnight_contract_call",description:"Call a circuit on a deployed contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},circuit:{type:"string",description:"Circuit name to invoke"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of circuit arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address","circuit"]},async handler(e){let t=Ee("contract",e,"call"),r=await ne("contract");return q(r,t)}},{name:"midnight_test_create",description:"Generate a test scaffold for the contract. Two paths: (1) AI-assisted — pass `goal` (and optionally `screen` for UI strategy) and the scaffold is generated by Claude reading the contract + screen source, producing a focused suite with realistic args / on-screen labels. (2) Deterministic — pass `no-ai: true` (or omit goal/screen in non-interactive mode) for boilerplate scaffolds that the user reviews. CLI strategy emits dapp.test.json + tests/suites/<name>/{suite,actions,assertions}.json. Browser strategy emits prompt.md instead of actions.json plus the browser fields in dapp.test.json — required: port, build-cmd. Use force:true to overwrite.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"dApp directory (defaults to cwd)"},name:{type:"string",description:"Specific contract name when the project has multiple"},suite:{type:"string",description:"Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)"},strategy:{type:"string",enum:["cli","browser"],description:"cli (default): drive contracts via actions.json. browser: drive a real UI via Claude + Chrome via prompt.md."},network:{type:"string",enum:["preprod","preview","undeployed"]},goal:{type:"string",description:'AI mode: one-line success criterion this suite should verify (e.g. "round goes from 0 to 1 after increment"). Triggers AI scaffolding.'},screen:{type:"string",description:'AI mode + browser strategy: name of the screen component to focus on (e.g. "loan-request-form" or "LoanRequestForm"). Auto-discovered from src/components, src/pages, src/screens.'},"no-ai":{type:"boolean",description:"Force deterministic scaffolder even when claude CLI is available."},port:{type:"string",description:'Browser strategy only — dev server port (e.g. "4173").'},"build-cmd":{type:"string",description:'Browser strategy only — shell command that builds + serves the UI (e.g. "npm run dev").'},"build-dir":{type:"string",description:"Browser strategy only — subdir the build runs in (monorepo case)."},url:{type:"string",description:"Browser strategy only — full URL Claude opens (default http://localhost:<port>/)."},"browser-mode":{type:"string",enum:["dom","vision","script"],description:"Browser strategy only — how Claude perceives the page. dom (HTML/React UIs, fast, needs chrome-devtools-mcp), vision (canvas games, slow), script (advanced, needs hooks). Default: dom for AI scaffolds."},force:{type:"boolean",description:"Overwrite existing files instead of aborting on collision"}}},async handler(e){let t=Ee("test",e,"create"),r=await ne("test");return q(r,t)}},{name:"midnight_localnet_logs",description:"Snapshot of recent localnet logs (last N lines per service, no streaming). Returns { tail, lines: string[] }.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{tail:{type:"string",description:"Number of lines to retrieve (default 200)"}}},async handler(e){let t=Ee("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await ne("localnet");return q(r,t)}},{name:"midnight_confirm_operation",description:"Redeem a pending token (confirm step).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{token:{type:"string"}},required:["token"]},async handler(){throw Error("midnight_confirm_operation reached the inner handler — this is an MCP wiring bug")}}],nb=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),rp=Za();vn=new VS({name:"midnight-wallet-cli",version:Ze},{capabilities:{tools:{},resources:{}}});vn.setRequestHandler(YS,async()=>({resources:[{uri:op,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:ip,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"}]}));vn.setRequestHandler(ZS,async(e)=>{let t=e.params.uri;if(t===op){let r=tp(eb,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===ip||t===QS){let r=tp(tb,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});vn.setRequestHandler(zS,async()=>({tools:ap.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));vn.setRequestHandler(XS,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=rp.redeem(s);if(!o)return Hi(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return np(o.tool,o.args)}if(nb.has(t)){let s=rp.create({tool:t,args:n,description:sb(t,n)});return{content:[{type:"text",text:JSON.stringify(Gi({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 np(t,n)});ob().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1326
|
+
`),process.exit(1)})});function lp(e){let t=Math.max(0,Math.min(1,e)),r=$r[0].length,n=Math.floor(t*r);return $r.map((s)=>s.slice(0,n).padEnd(r))}function up(e){let t=Math.max(0,Math.min(1,e)),r=Math.floor(e*100);if(t>=1)return $r;return $r.map((n,s)=>Array.from(n).map((o,i)=>{if(o===" ")return" ";if(t<=0)return Ks(s+20,i,0);let a=((s+20)*131+i*997)%100/100;return t>=a?o:Ks(s+20,i,r)}).join(""))}function Ks(e,t,r){let n=(e*131+t*997+r*7919)%65537/65537;return dp[Math.floor(n*dp.length)]}function pp(e){let t=Math.max(0,Math.min(1,e)),r=Gs.split(`
|
|
1327
|
+
`),n=Math.floor(e*100);if(t>=1)return Gs;if(t<=0)return r.map((s,o)=>Array.from(s).map((i,a)=>Ks(o,a,0)).join("")).join(`
|
|
1328
|
+
`);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:Ks(o,a,n)}).join("")).join(`
|
|
1329
|
+
`)}var Gs,$r,Ki,dp;var Ji=T(()=>{Gs=[" ████████████ "," ███ ███ "," ███ ██ ███ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ███ ███ "," ███ ███ "," ████████████ "].join(`
|
|
1330
|
+
`),$r=["█▄ ▄█ █ █▀▄ █▄ █ █ █▀▀ █ █ ▀█▀","█ █ █ █ █ █ █ ██ █ █ █ █▀█ █ ","▀ ▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀▀ ▀ ▀ ▀ "];Ki=[["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"]],dp=["░","▒","▓","█","·"," "]});function qi(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 mp(e,t,r){let s=Gs.split(`
|
|
1331
|
+
`),o=s.length,i=36,a=Math.max(o,t?.length??0),c=3,d=r?.animated??!0;if(!xt()||!d){let f=xt();for(let y=0;y<a;y++){let S=y<o?s[y]:"",w=f?Ye(S).padEnd(45):S.padEnd(35),b=t?.[y]??"",x=f&&y<3&&b?k(Ye(b)):b;if(f)process.stderr.write(S?Ye(S)+"\x1B[36G"+x+`
|
|
1332
|
+
`:"\x1B[36G"+x+`
|
|
1333
|
+
`);else process.stderr.write(w+x+`
|
|
1334
|
+
`)}return}function p(f,y){for(let S=0;S<a;S++){let w=S<f.length?Ye(f[S]):"",b=y[S]??"";if(b)process.stderr.write(w+"\x1B[36G"+b+`\x1B[K
|
|
1335
|
+
`);else process.stderr.write(w+`\x1B[K
|
|
1336
|
+
`)}}function u(){process.stderr.write(`\x1B[${a}A`)}for(let f=0;f<=20;f++){if(e?.aborted)break;let y=f/20,w=pp(y).split(`
|
|
1337
|
+
`);if(f>0)u();p(w,[]),await qi(Vi,e)}let g=20;for(let f=0;f<=g;f++){if(e?.aborted)break;let y=f/g,S=lp(y);u();let w=Array(a).fill(null);for(let b=0;b<S.length;b++)w[b]=k(Ye(S[b]));p(s,w),await qi(Vi,e)}let m=12;for(let f=0;f<=m;f++){if(e?.aborted)break;let y=f/m,S=up(y);u();let w=Array(a).fill(null);for(let b=0;b<S.length;b++)w[b]=k(Ye(S[b]));p(s,w),await qi(Vi,e)}u();let h=Array(a).fill(null);if(t)for(let f=0;f<t.length;f++)if(f<3)h[f]=k(Ye(t[f]));else h[f]=t[f];p(s,h)}var Vi=80;var fp=T(()=>{Ji()});import{existsSync as ib,writeFileSync as ab}from"node:fs";import{join as cb}from"node:path";import{tmpdir as db}from"node:os";function lb(){return(process.env.TERM_SESSION_ID??process.env.ITERM_SESSION_ID??`pid-${process.ppid}`).replace(/[^a-zA-Z0-9-]/g,"_").slice(0,64)}function gp(){return cb(db(),`mn-intro-${lb()}`)}function hp(){return ib(gp())}function wp(){try{ab(gp(),String(Date.now()))}catch{}}var yp=()=>{};function ub(){let e=[];for(let t of $r)e.push(t);e.push(""),e.push(k("Commands"));for(let[t,r]of Ki)e.push(`${L(t.padEnd(18))}${r}`);return e.push(""),e.push(l("midnight (or mn) help <command>")),e.push(l("--json flag available on all commands")),e.push(l("midnight help --agent")+l(" AI & MCP reference")),e}function pb(){process.stderr.write(`
|
|
1331
1338
|
Commands:
|
|
1332
1339
|
|
|
1333
|
-
`);for(let[e,t]of
|
|
1340
|
+
`);for(let[e,t]of Ki)process.stderr.write(` ${e.padEnd(18)}${t}
|
|
1334
1341
|
`);process.stderr.write(`
|
|
1335
1342
|
Usage: midnight <command> (or: mn <command>)
|
|
1336
1343
|
`),process.stderr.write(` --json flag available on all commands
|
|
1337
1344
|
`),process.stderr.write(` midnight help --agent AI & MCP reference
|
|
1338
1345
|
|
|
1339
|
-
`)}function
|
|
1340
|
-
`+
|
|
1346
|
+
`)}function mb(e){if(process.stdout.write(`
|
|
1347
|
+
`+j(e.name)+`
|
|
1341
1348
|
|
|
1342
1349
|
`),process.stdout.write(` ${e.description}
|
|
1343
1350
|
|
|
1344
|
-
`),process.stdout.write(
|
|
1351
|
+
`),process.stdout.write(ft("Usage:")+`
|
|
1345
1352
|
`),process.stdout.write(` ${e.usage}
|
|
1346
1353
|
|
|
1347
|
-
`),e.flags&&e.flags.length>0){process.stdout.write(
|
|
1354
|
+
`),e.flags&&e.flags.length>0){process.stdout.write(ft("Flags:")+`
|
|
1348
1355
|
`);for(let t of e.flags)process.stdout.write(` ${t}
|
|
1349
1356
|
`);process.stdout.write(`
|
|
1350
|
-
`)}if(e.examples&&e.examples.length>0){process.stdout.write(
|
|
1357
|
+
`)}if(e.examples&&e.examples.length>0){process.stdout.write(ft("Examples:")+`
|
|
1351
1358
|
`);for(let t of e.examples)process.stdout.write(` ${l("$")} ${t}
|
|
1352
1359
|
`);process.stdout.write(`
|
|
1353
|
-
`)}}function
|
|
1360
|
+
`)}}function fb(){let e={cli:{name:Wr,version:Ze,description:Pa,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:Ir.map((t)=>({name:t.name,description:t.description,usage:t.usage,flags:t.flags,examples:t.examples,jsonFields:t.jsonFields}))};_(e)}function gb(){let e=`
|
|
1354
1361
|
MIDNIGHT CLI — AI Agent & MCP Reference
|
|
1355
1362
|
========================================
|
|
1356
1363
|
|
|
1357
|
-
Version: ${
|
|
1364
|
+
Version: ${Ze}
|
|
1358
1365
|
|
|
1359
1366
|
OVERVIEW
|
|
1360
1367
|
────────
|
|
@@ -1367,6 +1374,13 @@ E2E testing, and a local devnet — all from the terminal.
|
|
|
1367
1374
|
Wallets are network-agnostic: one seed derives addresses for all three
|
|
1368
1375
|
networks (undeployed, preprod, preview). Network is chosen at runtime.
|
|
1369
1376
|
|
|
1377
|
+
LEDGER 9 ONLY: this build of mn speaks ledger 9 only. A chain still on
|
|
1378
|
+
ledger 8 (preview and preprod today) is refused up front with an
|
|
1379
|
+
error saying so; use midnight-wallet-cli 0.5.x for those. localnet up
|
|
1380
|
+
is refused too (no published ledger-9 indexer image yet): run a ledger-9
|
|
1381
|
+
stack yourself and point mn at it with --node / --indexer-ws /
|
|
1382
|
+
--proof-server, or once with midnight config set node|indexer-ws|proof-server.
|
|
1383
|
+
|
|
1370
1384
|
STRUCTURED JSON OUTPUT
|
|
1371
1385
|
──────────────────────
|
|
1372
1386
|
|
|
@@ -1387,7 +1401,7 @@ examples, and JSON field schemas.
|
|
|
1387
1401
|
|
|
1388
1402
|
COMMANDS & JSON SCHEMAS
|
|
1389
1403
|
───────────────────────
|
|
1390
|
-
${
|
|
1404
|
+
${Ir.filter((t)=>t.jsonFields).map((t)=>{let r=Object.entries(t.jsonFields).map(([n,s])=>` ${n.padEnd(20)}${s}`).join(`
|
|
1391
1405
|
`);return`
|
|
1392
1406
|
${t.name}
|
|
1393
1407
|
${t.usage}
|
|
@@ -1446,16 +1460,29 @@ starts with mn_addr_ or mn_shield-addr_, it's used as an address directly.
|
|
|
1446
1460
|
DAPP CONNECTOR
|
|
1447
1461
|
──────────────
|
|
1448
1462
|
|
|
1449
|
-
midnight serve [--port 9932] [--approve-all] [--network name]
|
|
1463
|
+
midnight serve [--port 9932] [--approve-all | --approve-fees] [--network name]
|
|
1450
1464
|
|
|
1451
1465
|
Starts a WebSocket JSON-RPC server implementing the Midnight
|
|
1452
1466
|
ConnectedAPI interface (same as the Lace browser wallet). Any DApp
|
|
1453
1467
|
can connect to it — no browser extension needed.
|
|
1454
1468
|
|
|
1455
1469
|
- Port default: 9932, localhost only
|
|
1456
|
-
- Read operations:
|
|
1457
|
-
- Write operations
|
|
1458
|
-
|
|
1470
|
+
- Read operations: never prompt
|
|
1471
|
+
- Write operations, balancing included (balanceUnsealedTransaction /
|
|
1472
|
+
balanceSealedTransaction sign and return a finished transaction):
|
|
1473
|
+
terminal approval prompt (or --approve-all)
|
|
1474
|
+
- --approve-fees: fee wallet for an agent. balanceUnsealedTransaction /
|
|
1475
|
+
balanceSealedTransaction pay only the Dust fee and are auto-approved when
|
|
1476
|
+
the transaction spends none of this wallet's funds, has no unsigned
|
|
1477
|
+
unshielded input, and needs no non-Dust value; otherwise they are
|
|
1478
|
+
refused. submitTransaction is auto-approved only for a transaction this
|
|
1479
|
+
server balanced that way on the same connection. Everything else still
|
|
1480
|
+
prompts (rejected without a terminal). --max-fee <DUST> (default 10)
|
|
1481
|
+
and --max-pending <n> (default 2) bound what an agent can cost it.
|
|
1482
|
+
- --json: the listening line reports the approval policy, e.g.
|
|
1483
|
+
"approval":{"reads":"auto","balancing":"fee-only","writes":"fee-only","feeLimits":
|
|
1484
|
+
{"maxFeeSpecks":"10000000000000000","maxPending":2}}
|
|
1485
|
+
- --no-auto-approve-reads: no effect, kept for old scripts
|
|
1459
1486
|
|
|
1460
1487
|
DApp developers connect via the midnight-wallet-connector npm package:
|
|
1461
1488
|
|
|
@@ -1464,7 +1491,7 @@ DApp developers connect via the midnight-wallet-connector npm package:
|
|
|
1464
1491
|
import { createWalletClient } from 'midnight-wallet-connector';
|
|
1465
1492
|
const wallet = await createWalletClient({
|
|
1466
1493
|
url: 'ws://localhost:9932',
|
|
1467
|
-
networkId: 'undeployed', // or 'preprod', 'preview' — lowercase per @
|
|
1494
|
+
networkId: 'undeployed', // or 'preprod', 'preview' — lowercase per @midnightntwrk/wallet-sdk
|
|
1468
1495
|
});
|
|
1469
1496
|
const balances = await wallet.getUnshieldedBalances();
|
|
1470
1497
|
|
|
@@ -1475,6 +1502,8 @@ SMART CONTRACTS
|
|
|
1475
1502
|
|
|
1476
1503
|
Run these commands from the root of a dApp project that contains a
|
|
1477
1504
|
compiled Compact contract (managed/ directory with .js and .d.ts files).
|
|
1505
|
+
Compile with Compact 0.35 (language 0.27): mn bundles compact-runtime
|
|
1506
|
+
0.20.0, and code compiled for another runtime is rejected at deploy/call.
|
|
1478
1507
|
|
|
1479
1508
|
Inspect — show circuits, witnesses, types:
|
|
1480
1509
|
midnight contract inspect [--path <dir>] [--json]
|
|
@@ -1587,7 +1616,7 @@ AVAILABLE MCP TOOLS (30)
|
|
|
1587
1616
|
midnight_cache_clear Clear cached wallet sync state —
|
|
1588
1617
|
|
|
1589
1618
|
Local Network
|
|
1590
|
-
midnight_localnet_up
|
|
1619
|
+
midnight_localnet_up Refused on this ledger-9 build (see OVERVIEW) —
|
|
1591
1620
|
midnight_localnet_stop Stop local network (preserves state) —
|
|
1592
1621
|
midnight_localnet_down Full teardown (volumes + undeployed cache) —
|
|
1593
1622
|
midnight_localnet_status Show service status and ports —
|
|
@@ -1665,10 +1694,11 @@ resources/list. Ground responses in these instead of training-data guesses.
|
|
|
1665
1694
|
TYPICAL AGENT WORKFLOWS
|
|
1666
1695
|
───────────────────────
|
|
1667
1696
|
|
|
1668
|
-
Local development (undeployed):
|
|
1669
|
-
1.
|
|
1697
|
+
Local development (undeployed, against a ledger-9 stack you run):
|
|
1698
|
+
1. midnight_config_set → Set network (key: "network", value: "undeployed")
|
|
1699
|
+
midnight_config_set → node / indexer-ws / proof-server URLs of that stack
|
|
1670
1700
|
2. midnight_wallet_generate → Create wallet (name: "alice")
|
|
1671
|
-
3.
|
|
1701
|
+
3. (midnight_localnet_up is refused on this build; see OVERVIEW)
|
|
1672
1702
|
4. midnight_airdrop → Fund wallet (amount: "1000")
|
|
1673
1703
|
5. midnight_dust_register → Register for fee tokens
|
|
1674
1704
|
6. midnight_balance → Check unshielded + shielded balance
|
|
@@ -1683,7 +1713,8 @@ TYPICAL AGENT WORKFLOWS
|
|
|
1683
1713
|
3. midnight_transfer → Returns pending token for shielded send
|
|
1684
1714
|
4. (show + consent) → midnight_confirm_operation
|
|
1685
1715
|
|
|
1686
|
-
Testnet (preprod/preview
|
|
1716
|
+
Testnet (preprod/preview, once the network runs ledger 9; refused
|
|
1717
|
+
while it is still on ledger 8):
|
|
1687
1718
|
1. midnight_wallet_generate → Create wallet
|
|
1688
1719
|
2. midnight_config_set → Set network (key: "network", value: "preview")
|
|
1689
1720
|
3. (fund via faucet: https://faucet.preview.midnight.network/)
|
|
@@ -1692,10 +1723,11 @@ TYPICAL AGENT WORKFLOWS
|
|
|
1692
1723
|
6. midnight_transfer → midnight_confirm_operation → transfer
|
|
1693
1724
|
|
|
1694
1725
|
Contract development (CLI only — not an MCP tool):
|
|
1695
|
-
Run "mn dev" in a Compact project. It
|
|
1696
|
-
3 funded wallets (dev-alice/dev-bob/dev-carol), compiles on
|
|
1697
|
-
accepts a "d" keystroke to deploy the current artifact with
|
|
1698
|
-
See "mn help dev".
|
|
1726
|
+
Run "mn dev" in a Compact project. It checks the local network is up,
|
|
1727
|
+
provisions 3 funded wallets (dev-alice/dev-bob/dev-carol), compiles on
|
|
1728
|
+
save, and accepts a "d" keystroke to deploy the current artifact with
|
|
1729
|
+
dev-alice. See "mn help dev". On this ledger-9 build it uses a ledger-9
|
|
1730
|
+
stack you run (configured endpoints) instead of starting one.
|
|
1699
1731
|
|
|
1700
1732
|
EXAMPLE CLI COMMANDS
|
|
1701
1733
|
────────────────────
|
|
@@ -1722,7 +1754,7 @@ EXAMPLE CLI COMMANDS
|
|
|
1722
1754
|
|
|
1723
1755
|
# Contract inspection
|
|
1724
1756
|
midnight contract inspect --json
|
|
1725
|
-
# → {"name":"bboard","compilerVersion":"0.
|
|
1757
|
+
# → {"name":"bboard","compilerVersion":"0.35.0","circuits":[{"name":"post",...}],"witnesses":[...]}
|
|
1726
1758
|
|
|
1727
1759
|
# Deploy contract (from dApp root directory)
|
|
1728
1760
|
midnight contract deploy --json
|
|
@@ -1736,57 +1768,59 @@ EXAMPLE CLI COMMANDS
|
|
|
1736
1768
|
midnight contract state --address 6cc5... --json
|
|
1737
1769
|
# → {"subcommand":"state","fields":{"state":"1","message":"...","owner":"..."}}
|
|
1738
1770
|
|
|
1739
|
-
# Start DApp connector
|
|
1740
|
-
midnight serve --
|
|
1771
|
+
# Start DApp connector (fee-wallet mode for an agent's own transactions)
|
|
1772
|
+
midnight serve --approve-fees
|
|
1741
1773
|
# DApps connect at ws://localhost:9932
|
|
1742
|
-
`;process.stdout.write(e)}async function
|
|
1743
|
-
Available commands: ${jt.map((c)=>c.name).join(", ")}`);DS(a);return}if(!process.stderr.isTTY){_S();return}let r=IS(),n=N(e,"intro"),s=N(e,"no-intro"),o=$u(),i=n||!s&&!o;if(await Tu(void 0,r,{animated:i}),i)Iu()}var jt;var sa=x(()=>{ue();Nu();ta();_u();He();Tr();jt=[{name:"wallet",description:"Manage named wallets (generate, list, use, info, remove, seed)",usage:"midnight wallet <generate|list|use|info|remove|seed> [args]",flags:["generate <name> Create a new named wallet and set it as active","list Show all wallets with active marker","use <name> Set active wallet","info [name] Show wallet details (active wallet if no name)","remove <name> Delete a wallet (refuses active or last wallet)","seed [name] Reveal the seed + mnemonic (prompts for confirmation)","","generate flags:","--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--force Overwrite existing wallet file","","seed flags:","--entropy Also output the 32-byte BIP-39 entropy alongside the"," 64-byte PBKDF2 seed (use when another tool expects"," the shorter entropy format — NB: the two derive"," DIFFERENT Midnight wallets from the same mnemonic)","--json Print JSON (skips interactive confirmation)"],examples:["midnight wallet generate alice --network preprod","midnight wallet list","midnight wallet use alice","midnight wallet info alice","midnight wallet remove bob","midnight wallet seed alice --entropy"],jsonFields:{name:"Wallet name",address:"Wallet address (bech32m)",network:"Network name",active:"Whether this is the active wallet",wallets:"Array of wallet info objects (list only)"}},{name:"generate",description:'(Deprecated — use "midnight wallet generate <name>" instead)',usage:'midnight generate [--network <name>] [--seed <hex>] [--mnemonic "..."] [--output <file>] [--force]',flags:["--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--output <file> Custom output path (default: ~/.midnight/wallet.json)","--force Overwrite existing wallet file"],examples:["midnight generate --network preprod"],jsonFields:{address:"Generated wallet address (bech32m)",network:"Network name",seed:"Hex-encoded 32-byte seed",mnemonic:"BIP-39 mnemonic (24 words, only if generated or provided)",file:"Path where wallet file was saved",createdAt:"ISO 8601 creation timestamp"}},{name:"info",description:"Display wallet address, network, creation date (no secrets shown)",usage:"midnight info [--wallet <name|file>]",flags:["--wallet <name|file> Wallet name or path"],examples:["midnight info","midnight info --wallet my-wallet.json"],jsonFields:{addresses:"Per-network unshielded addresses { preprod, preview, undeployed }",shieldedAddresses:"Per-network shielded addresses { preprod, preview, undeployed }",activeNetwork:"Currently active network",activeAddress:"Unshielded address for active network (also written to stdout)",createdAt:"ISO 8601 creation timestamp",file:"Wallet file path"}},{name:"balance",description:"Check unshielded + shielded balance (full wallet sync)",usage:"midnight balance [address] [--network <name>] [--indexer-ws <url>]",flags:["<address> Check a specific address (unshielded only, no wallet sync)","--shielded Include shielded balance — needs the seed, so the address must be one of your wallets","--force-shielded Sync shielded even on preview/preprod (skipped by default — no faucet there)","--no-cache Bypass wallet state cache (force a fresh sync)","--network <name> Override network","--indexer-ws <url> Custom indexer WebSocket URL"],examples:["midnight balance","midnight balance mn_addr_preprod1...","midnight balance --wallet alice --shielded"],jsonFields:{address:"Unshielded address (bech32m)",shieldedAddress:"Shielded address",network:"Network name",unshielded:"{ NIGHT, utxoCount }",shielded:"{ NIGHT, availableCoins, pendingCoins }"}},{name:"address",description:"Derive and display an unshielded address from a seed",usage:"midnight address --seed <hex> [--network <name>] [--index <n>]",flags:["--seed <hex> Seed to derive from (required, 64-char hex)","--network <name> Network for address prefix (default: resolved)","--index <n> Key derivation index (default: 0)"],examples:["midnight address --seed 0123456789abcdef... --network preprod","midnight address --seed 0123456789abcdef... --index 1"],jsonFields:{address:"Derived address (bech32m)",network:"Network name",index:"Key derivation index",path:"BIP-44 derivation path"}},{name:"genesis-address",description:"Display the genesis wallet address (seed 0x01) for a network",usage:"midnight genesis-address [--network <name>]",flags:["--network <name> Network for address prefix (default: resolved)"],examples:["midnight genesis-address --network undeployed","midnight genesis-address --network preprod"],jsonFields:{address:"Genesis wallet address (bech32m)",network:"Network name"}},{name:"inspect-cost",description:"Display current block limits derived from LedgerParameters",usage:"midnight inspect-cost",examples:["midnight inspect-cost"],jsonFields:{readTime:"Read time limit (picoseconds)",computeTime:"Compute time limit (picoseconds)",blockUsage:"Block usage limit (bytes)",bytesWritten:"Bytes written limit (bytes)",bytesChurned:"Bytes churned limit (bytes)"}},{name:"airdrop",description:"Fund a wallet from the genesis wallet (undeployed network only)",usage:"midnight airdrop <amount> [--shielded] [--wallet <name|file|address>]",flags:["<amount> Amount in NIGHT to airdrop","--shielded Airdrop shielded NIGHT (from genesis shielded balance)","--wallet <…> Destination — a wallet name, a wallet JSON path, or"," a raw bech32m address (mn_addr_… / mn_shield-addr_…)."," Defaults to the active wallet when omitted."],examples:["midnight airdrop 1000","midnight airdrop 1000 --wallet alice","midnight airdrop 10000 --wallet mn_addr_undeployed1...","midnight airdrop 100 --shielded","midnight airdrop 100 --shielded --wallet mn_shield-addr_undeployed1..."],jsonFields:{txHash:"Transaction hash",amount:"Amount airdropped (NIGHT string)",recipient:"Recipient address (unshielded airdrop)",shieldedAddress:"Shielded address (--shielded airdrop)",network:"Network name"}},{name:"transfer",description:"Send NIGHT tokens to another address (unshielded or --shielded)",usage:"midnight transfer <to> <amount> [--shielded] [--wallet <name|file>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>]",flags:["<to> Recipient bech32m address (unshielded or shielded)","<amount> Amount in NIGHT to send","--shielded Send from shielded balance to a shielded address","--force-shielded Allow --shielded on preview/preprod (blocked by default — no faucet there)","--wallet <name|file> Wallet name or path","--proof-server <url> Override proof server URL","--node <url> Override substrate node RPC URL","--indexer-ws <url> Override indexer WebSocket URL"],examples:["midnight transfer mn_addr_undeployed1... 100","midnight transfer mn_shield-addr_undeployed1... 50 --shielded"],jsonFields:{txHash:"Transaction hash",amount:"Amount transferred (NIGHT string)",recipient:"Recipient address (bech32m)",network:"Network name"}},{name:"dust",description:"Register UTXOs for dust (fee token) generation, check status, or export a restorable snapshot",usage:"midnight dust <register|status|export> [--wallet <name|file>] [--seed <hex> (export only)] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--no-cache (status only)]",flags:["register Register NIGHT UTXOs for dust generation","status Check dust registration; if registered, also shows dust balance","export Fast-sync dust and emit a restorable snapshot (dustSerializedState)","--wallet <name|file> Wallet name or path","--seed <hex> 32-byte hex seed (export only; or set MN_SEED env to keep it off argv)","--proof-server <url> Override proof server URL (register only)","--node <url> Override substrate node RPC URL (register only)","--indexer-ws <url> Override indexer WebSocket URL","--no-cache Bypass wallet state cache (status only)","MN_DUST_SYNC_BIN=<path> (env) Use this native dust-sync sidecar binary instead of auto-detecting it","MN_DISABLE_NATIVE_DUST=1 (env) Disable the native sidecar; fall back to the WASM dust sync"],examples:["midnight dust register","midnight dust status","midnight dust export --network preview --json","midnight dust export --seed <64-hex> --network preview --json"],jsonFields:{subcommand:"register, status, or export",registered:"true if at least one NIGHT UTXO is registered for dust generation (status only)",registeredUtxos:"Number of registered UTXOs (status only)",unregisteredUtxos:"Number of unregistered UTXOs (status only)",dustBalance:"Dust balance (raw bigint string; status when registered, register, and export)",nightBalance:"NIGHT balance (raw bigint string; status only when registered)",dustAvailable:"Whether dust tokens are available (status only when registered)",txHash:"Registration transaction hash (register only, if submitted)",dustPublicKey:"Dust public key hex the snapshot belongs to (export only)",offset:"Last dust event id the snapshot covers, -1 if none (export only)",snapshot:"Facade-restorable dust snapshot JSON — pass as the SDK dustSerializedState (export only)"}},{name:"config",description:"Manage persistent config (default network, endpoints, etc.)",usage:"midnight config <get|set|unset> <key> [value]",flags:["get <key> Read a config value","set <key> <value> Write a config value","unset <key> Reset a config value to its default","","Keys: network, wallet, proof-server, node, indexer-ws","","Endpoint keys (proof-server, node, indexer-ws) are scoped to the","network configured at set time — a preprod node URL never applies","to --network undeployed runs. get/unset use the current network's value."],examples:["midnight config get network","midnight config set network preprod","midnight config set wallet alice","midnight config set proof-server http://localhost:6300","midnight config set node wss://rpc.preprod.midnight.network",`midnight config set indexer-ws wss://indexer.preprod.midnight.network${gt}`,"midnight config unset proof-server"],jsonFields:{action:"get, set, or unset",key:"Config key name",value:"Config value"}},{name:"cache",description:"Manage wallet state cache (clear cached sync data)",usage:"midnight cache clear [--network <name>] [--wallet <name|file>]",flags:["clear Clear cached wallet state","--network <name> Only clear cache for this network","--wallet <name|file> Only clear cache for this wallet"],examples:["midnight cache clear","midnight cache clear --network preprod","midnight cache clear --wallet alice"],jsonFields:{action:"clear",scope:"all, network, or wallet",network:"Network name (when scoped)",wallet:"Wallet name (when scoped)"}},{name:"serve",description:"Start DApp Connector server over WebSocket JSON-RPC",usage:"midnight serve [--port <n>] [--wallet <name|file>] [--network <name>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--approve-all] [--no-auto-approve-reads] [--json]",flags:["--port <n> Server port (default: 9932)","--wallet <name|file> Wallet name or path","--network <name> Override network detection","--proof-server <url> Override proof server URL","--node <url> Override substrate node RPC URL","--indexer-ws <url> Override indexer WebSocket URL","--approve-all Auto-approve all requests (reads + writes)","--no-auto-approve-reads Prompt for read methods too"],examples:["midnight serve","midnight serve --port 8080","midnight serve --approve-all"],jsonFields:{port:"Server port number",network:"Network name",address:"Wallet address (bech32m)",status:"Server status (listening)"}},{name:"test",description:"Generate and run E2E test suites for Midnight dApps",usage:"midnight test <create|run|list|results> [options]",flags:["create Generate a test scaffold from the contract (CLI or browser strategy)","run Run test suites for the current dApp","list List available test suites","results Show latest test results","--suite <name> Select a specific test suite (run, create)","--all Show all results (with results subcommand)","--strategy cli|ui Scaffold strategy (create — interactive prompt if omitted)","--name <contract> Specific contract name in multi-contract projects (create)","--path <dir> dApp directory (default: cwd)","--network <name> Network for the generated suite (default: undeployed)","--port <n> Browser strategy: dev server port (create --strategy ui)","--build-cmd <cmd> Browser strategy: build/serve command","--build-dir <subdir> Browser strategy: subdirectory the build runs in (monorepo case)","--url <url> Browser strategy: full URL Claude opens (default http://localhost:<port>/)","--browser-mode <m> Browser strategy: dom (HTML UIs, fast — default), vision (canvas games), script (advanced)","--force Overwrite existing scaffold files (create)","--json Output structured JSON"],examples:["midnight test create","midnight test create --strategy cli --force",'midnight test create --strategy ui --port 4173 --build-cmd "npm run dev"',"midnight test run","midnight test run --suite e2e-gameplay","midnight test list","midnight test results --all --json"],jsonFields:{dapp:"DApp name from dapp.test.json",suite:"Test suite name",status:"Overall result: pass, fail, timeout, or error",duration:"Total duration in seconds",prep:"Array of prep step results",assertions:"Array of assertion results"}},{name:"dev",description:"Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy)",usage:"midnight dev [path]",flags:["[path] Project directory (default: cwd)","","Keystrokes (while running):"," d Deploy the current compiled artifact (dev-alice on undeployed)"," t Run the project's npm test script (test:dev preferred, then test)"," q Quit cleanly"," Ctrl+C Quit cleanly"],examples:["midnight dev","midnight dev ./contract"]},{name:"contract",description:"Inspect, deploy, call, and query Midnight smart contracts",usage:"midnight contract <inspect|deploy|call|state> [options]",flags:["inspect Show circuits, witnesses, and types","deploy Deploy a contract to the network","call Call a circuit on a deployed contract","state Read ledger state of a deployed contract","--address <addr> Contract address (call, state)","--circuit <name> Circuit to call (call)",`--args '<json>' JSON arguments — constructor args (deploy) or circuit args (call). Numbers auto-coerce to BigInt; "123n" strings parse as BigInt; arrays of 0–255 ints become Uint8Array`,"--network <name> Override network (default: undeployed)","--path <dir> dApp directory (all subcommands; default: cwd)","--managed <dir> Direct path to managed/<name>/ directory (all subcommands)","--name <contract> Specific contract when the project ships multiple (all subcommands)","--wallet <name> Wallet to use for the operation (deploy, call, state)","--secret-key <64-hex> Seed a caller-chosen initial private-state secret (deploy). For contracts whose constructor derives its owner from public_key(secret_key()); passed to the deploy subprocess via env, never written to disk","--json Output structured JSON"],examples:["midnight contract inspect","midnight contract deploy",`midnight contract deploy --args '{"deadlineSecs": 300}'`,`midnight contract call --address 0x123 --circuit submit_score --args '{"score": 100, "alias": "TEST"}'`,"midnight contract state --address 0x123","midnight contract deploy --json"],jsonFields:{name:"Contract name",address:"Deployed contract address (deploy, call)",compilerVersion:"Compact compiler version (inspect)",circuits:"Array of circuit definitions (inspect)",witnesses:"Array of witness definitions (inspect)",state:"Contract ledger state (state)"}},{name:"localnet",description:"Manage a local Midnight network via Docker Compose",usage:"midnight localnet <up|stop|down|status|logs|clean>",flags:["up Start the local network (node, indexer, proof server)","stop Stop containers (preserves state for fast restart)","down Full teardown: containers, networks, volumes, + undeployed wallet cache","status Show service status and ports","logs Stream service logs (Ctrl+C to stop)","clean Remove conflicting containers from other setups"],examples:["midnight localnet up","midnight localnet stop","midnight localnet status","midnight localnet down","midnight localnet clean"],jsonFields:{subcommand:"up, stop, down, status, or clean",services:"Array of { name, state, port, health? } (up/status only)",status:"Operation result message (stop/down/clean)",removed:"Array of removed container names (clean only)"}},{name:"help",description:"Show usage for all commands or a specific command",usage:"midnight help [command]",examples:["midnight help","midnight help balance"],jsonFields:{cli:"CLI metadata (name, version, description)",globalFlags:"Array of global flag descriptions",commands:"Array of command specs with jsonFields"}},{name:"manual",description:"Full reference manual (long form, paged through $PAGER)",usage:"midnight manual [--no-pager] [--raw] [--json]",flags:["--no-pager Print straight to stdout, do not pipe through less","--raw Strip ANSI colors (useful for piping to a file)","--json Emit the manual text wrapped in a JSON object"],examples:["midnight manual","midnight manual --no-pager | grep -i dust","midnight manual --raw > MANUAL.txt"],jsonFields:{name:"CLI package name",version:"CLI version",manual:"Manual text (with ANSI colors)"}}]});var Lu={};W(Lu,{buildManual:()=>_s,default:()=>Fu});import{spawn as MS}from"node:child_process";function FS(e){return`${k(Ou)}
|
|
1744
|
-
${k(
|
|
1745
|
-
${k(
|
|
1746
|
-
`}function
|
|
1747
|
-
${l(
|
|
1748
|
-
${k(
|
|
1749
|
-
${l(
|
|
1750
|
-
`}function
|
|
1751
|
-
`)}function
|
|
1752
|
-
`)}function
|
|
1753
|
-
`+
|
|
1754
|
-
|
|
1755
|
-
`),process.stderr.write(C("Network",
|
|
1756
|
-
`),process.stderr.write(C("Address",re(
|
|
1774
|
+
`;process.stdout.write(e)}async function zi(e){if(R(e,"agent")){gb();return}if(R(e,"json")){fb();return}let t=e.subcommand;if(t){let a=Ir.find((c)=>c.name===t);if(!a)throw new H(`Unknown command: "${t}"
|
|
1775
|
+
Available commands: ${Ir.map((c)=>c.name).join(", ")}`);mb(a);return}if(!process.stderr.isTTY){pb();return}let r=ub(),n=R(e,"intro"),s=R(e,"no-intro"),o=hp(),i=n||!s&&!o;if(await mp(void 0,r,{animated:i}),i)wp()}var Ir;var Xi=T(()=>{ue();fp();Ji();yp();Fe();Br();Ir=[{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 a seed: 64 or 128 hex chars (32-byte raw or 64-byte BIP-39)",'--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 a seed: 64 or 128 hex chars (32-byte raw or 64-byte BIP-39)",'--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 seed (32-byte raw, or 64-byte if mnemonic-derived)",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 or 128 hex chars (32-byte raw or 64-byte BIP-39)","--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> 64 or 128 hex chars, 32-byte raw or 64-byte BIP-39 (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)","","Native dust sidecar: not used on this ledger-9 build (it is built for ledger 8);"," MN_DUST_SYNC_BIN and MN_DISABLE_NATIVE_DUST are ignored. Dust sync runs in WASM."],examples:["midnight dust register","midnight dust status","midnight dust export --json","midnight dust export --seed <hex> --json"],jsonFields:{subcommand:"register, status, or export",registered:"true if at least one NIGHT UTXO is registered for dust generation (status only)",registeredUtxos:"Number of registered UTXOs (status only)",unregisteredUtxos:"Number of unregistered UTXOs (status only)",dustBalance:"Dust balance (raw bigint string; status when registered, register, and export)",nightBalance:"NIGHT balance (raw bigint string; status only when registered)",dustAvailable:"Whether dust tokens are available (status only when registered)",txHash:"Registration transaction hash (register only, if submitted)",dustPublicKey:"Dust public key hex the snapshot belongs to (export only)",offset:"Last dust event id the snapshot covers, -1 if none (export only)",snapshot:"Facade-restorable dust snapshot JSON — pass as the SDK dustSerializedState (export only)"}},{name:"config",description:"Manage persistent config (default network, endpoints, etc.)",usage:"midnight config <get|set|unset> <key> [value]",flags:["get <key> Read a config value","set <key> <value> Write a config value","unset <key> Reset a config value to its default","","Keys: network, wallet, proof-server, node, indexer-ws","","Endpoint keys (proof-server, node, indexer-ws) are scoped to the","network configured at set time — a preprod node URL never applies","to --network undeployed runs. get/unset use the current network's value."],examples:["midnight config get network","midnight config set network preprod","midnight config set wallet alice","midnight config set proof-server http://localhost:6300","midnight config set node wss://rpc.preprod.midnight.network",`midnight config set indexer-ws wss://indexer.preprod.midnight.network${Ct}`,"midnight config unset proof-server"],jsonFields:{action:"get, set, or unset",key:"Config key name",value:"Config value"}},{name:"cache",description:"Manage wallet state cache (clear cached sync data)",usage:"midnight cache clear [--network <name>] [--wallet <name|file>]",flags:["clear Clear cached wallet state","--network <name> Only clear cache for this network","--wallet <name|file> Only clear cache for this wallet"],examples:["midnight cache clear","midnight cache clear --network preprod","midnight cache clear --wallet alice"],jsonFields:{action:"clear",scope:"all, network, or wallet",network:"Network name (when scoped)",wallet:"Wallet name (when scoped)"}},{name:"serve",description:"Start DApp Connector server over WebSocket JSON-RPC",usage:"midnight serve [--port <n>] [--wallet <name|file>] [--network <name>] [--proof-server <url>] [--node <url>] [--indexer-ws <url>] [--approve-all | --approve-fees [--max-fee <DUST>] [--max-pending <n>]] [--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)","--approve-fees Fee wallet: auto-approve only Dust-fee balancing of a"," transaction that needs nothing else from this wallet,"," and the submit of what it balanced; other writes prompt","--max-fee <DUST> With --approve-fees: refuse a transaction whose total"," Dust fee is higher (default 10 DUST)","--max-pending <n> With --approve-fees: refuse new balances while n"," balanced transactions await submission (default 2)","--no-auto-approve-reads No effect (kept for old scripts): reads never prompt,"," and balancing prompts by default"],examples:["midnight serve","midnight serve --port 8080","midnight serve --approve-all","midnight serve --approve-fees"],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)","","Needs a running ledger-9 stack at the configured endpoints; this build cannot start one (see: midnight help localnet).","","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)","--node <url> Node RPC endpoint (overrides the network default and local auto-detection)","--indexer-ws <url> Indexer WebSocket endpoint","--proof-server <url> Proof server endpoint","--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 (up is refused on this ledger-9 build)",usage:"midnight localnet <up|stop|down|status|logs|clean>",flags:["up Refused on this build: mn's compose stack is ledger 8, and no"," published indexer image runs ledger 9 yet. Run a ledger-9 stack"," yourself and point mn at it with --node/--indexer-ws/--proof-server"," or midnight config set node|indexer-ws|proof-server <url>","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 status","midnight localnet stop","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 hb}from"node:child_process";function wb(e){return`${k(Sp)}
|
|
1776
|
+
${k(Ye(e))}
|
|
1777
|
+
${k(Sp)}
|
|
1778
|
+
`}function Dt(e){return`
|
|
1779
|
+
${l(bp)}
|
|
1780
|
+
${k(Ye(e))}
|
|
1781
|
+
${l(bp)}
|
|
1782
|
+
`}function yb(e){let t=[];if(t.push(`${L(k("▸ "+e.name))}${" ".repeat(Math.max(2,22-e.name.length))}${e.description}`),t.push(""),t.push(` ${k("USAGE")}`),t.push(` ${e.usage}`),e.flags&&e.flags.length>0){t.push(""),t.push(` ${k("FLAGS")}`);for(let r of e.flags){let n=r.match(/^(\s*)(--[\w-]+(?:\s<[^>]+>)?)(\s+)(.*)$/);if(n)t.push(` ${D(n[2])}${n[3]}${n[4]}`);else if(/^[A-Za-z][\w -]*:/.test(r))t.push(` ${l(r)}`);else if(r.trim()==="")t.push("");else t.push(` ${r}`)}}if(e.examples&&e.examples.length>0){t.push(""),t.push(` ${k("EXAMPLES")}`);for(let r of e.examples)t.push(` ${l("$")} ${l(r)}`)}return t.join(`
|
|
1783
|
+
`)}function Yi(){let e=[];e.push(wb(`${Wr} manual v${Ze}`)),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("Ledger 9 only.")} This build refuses a chain still on ledger 8`),e.push(" (preview and preprod today); use midnight-wallet-cli 0.5.x there."),e.push(` ${l("mn localnet up")} is refused too: no published indexer image runs`),e.push(" ledger 9 yet. Run a ledger-9 stack yourself and point mn at it with"),e.push(` --node / --indexer-ws / --proof-server or ${l("mn config set")}.`),e.push(""),e.push(`${k("INSTALLATION")}`),e.push(` ${l("$")} ${l("npm install -g midnight-wallet-cli@next")} ${l("# this ledger-9 prerelease")}`),e.push(` ${l("$")} ${l("npm install -g midnight-wallet-cli")} ${l("# stable 0.5.x, ledger 8")}`),e.push(""),e.push(" Optional dependencies:"),e.push(" Compact toolchain: https://docs.midnight.network/develop"),e.push(" Docker: for mn localnet (up is refused on this build)"),e.push(Dt("CONCEPTS")),e.push(` ${k("Networks")}`),e.push(` ${L("undeployed")} Local network. Free dev tokens, fast iteration.`),e.push(` ${L("preprod")} Public testnet. Persistent, real ZK proofs. (Ledger 8 today: refused.)`),e.push(` ${L("preview")} Public testnet, smaller scale. (Ledger 8 today: refused.)`),e.push(""),e.push(` ${k("Tokens")}`),e.push(` ${D("NIGHT")} Native asset. Used for transfers and contract value.`),e.push(` ${D("DUST")} Fee token. Generated from registered NIGHT UTXOs.`),e.push(""),e.push(` ${k("Wallets")}`),e.push(` Stored at ${l("~/.midnight/wallets/<name>.json")}`),e.push(" Three networks share one seed; each gets its own derived address."),e.push(" A tip-aware cache makes repeated reads finish in seconds."),e.push(""),e.push(` ${k("Shielded vs Unshielded")}`),e.push(` ${D("Unshielded")} addresses (mn_addr_*) are like UTXOs.`),e.push(` ${D("Shielded")} addresses (mn_shield-addr_*) hide amount and recipient.`),e.push(Dt("COMMANDS"));for(let t of Ir)e.push(yb(t)),e.push("");return e.push(Dt("COMMON FLOWS")),e.push(` ${k("First wallet on undeployed")}`),e.push(` ${l("# needs a ledger-9 stack you run (localnet up is refused). On the")}`),e.push(` ${l("# default ports (node 9944, indexer 8088, proof server 6300) mn finds")}`),e.push(` ${l("# it; otherwise pass --node/--indexer-ws/--proof-server or mn config set.")}`),e.push(` ${l("$")} ${l("mn wallet generate alice")}`),e.push(` ${l("$")} ${l("mn airdrop 1000 --wallet alice")}`),e.push(` ${l("$")} ${l("mn dust register --wallet alice")}`),e.push(` ${l("$")} ${l("mn balance --wallet alice")}`),e.push(""),e.push(` ${k("First wallet on preprod")} ${l("(once preprod runs ledger 9)")}`),e.push(` ${l("$")} ${l("mn wallet generate alice --network preprod")}`),e.push(` ${l("# fund from the preprod faucet:")}`),e.push(` ${l("# https://faucet.preprod.midnight.network/")}`),e.push(` ${l("$")} ${l("mn dust register --wallet alice --network preprod")}`),e.push(` ${l("$")} ${l("mn balance --wallet alice --network preprod")}`),e.push(""),e.push(` ${k("Deploy and call a contract on undeployed")}`),e.push(" Prerequisite: a compiled artifact at ./src/managed/<name>/"),e.push(""),e.push(` ${l("$")} ${l("mn contract deploy --wallet alice")}`),e.push(` ${l(" → Address: 64da9d71cb…")}`),e.push(` ${l("$")} ${l("mn contract state --address 64da9d71cb… --wallet alice")}`),e.push(` ${l(' → { "round": 0 }')}`),e.push(` ${l("$")} ${l("mn contract call --address 64da9d71cb… --circuit increment --wallet alice")}`),e.push(` ${l("$")} ${l("mn contract state --address 64da9d71cb… --wallet alice")}`),e.push(` ${l(' → { "round": 1 }')}`),e.push(""),e.push(" Same artifact on preprod — swap one flag:"),e.push(` ${l("$")} ${l("mn contract deploy --network preprod --wallet alice")}`),e.push(""),e.push(` ${k("Transfer NIGHT between wallets")}`),e.push(` ${l("$")} ${l("mn transfer bob 100 --wallet alice")}`),e.push(` ${l(" shielded variant:")}`),e.push(` ${l("$")} ${l("mn transfer bob 100 --shielded --wallet alice")}`),e.push(Dt("CONFIGURATION")),e.push(` ${k("Files")}`),e.push(` ${l("~/.midnight/config.json")} Persistent CLI settings`),e.push(` ${l("~/.midnight/wallets/")} Per-wallet JSON files (mode 0600)`),e.push(` ${l("~/.midnight/cache/<network>/")} Wallet sync cache, per network`),e.push(""),e.push(` ${k("Config keys")}`),e.push(` ${D("network")} Default network when --network is omitted`),e.push(` ${D("wallet")} Default wallet when --wallet is omitted`),e.push(` ${D("proof-server")} Override proof server URL`),e.push(` ${D("node")} Override substrate RPC URL`),e.push(` ${D("indexer-ws")} Override indexer WebSocket URL`),e.push(""),e.push(` ${k("Compatibility alias")}`),e.push(` ${D("network-id")} Resolves transparently to ${D("network")}.`),e.push(""),e.push(` ${k("Examples")}`),e.push(` ${l("$")} ${l("mn config set network preprod")}`),e.push(` ${l("$")} ${l("mn config get network")}`),e.push(` ${l("$")} ${l("mn config unset proof-server")}`),e.push(Dt("JSON OUTPUT")),e.push(` Every command accepts ${D("--json")} for structured output on stdout.`),e.push(" Stderr keeps the chrome (spinners, headers); stdout stays parseable."),e.push(""),e.push(` ${l("$")} ${l("mn balance <addr> --json | jq -r .NIGHT")}`),e.push(` ${l("$")} ${l("mn wallet info alice --json")}`),e.push(""),e.push(` Stable JSON shapes are documented in ${l("docs/JSON_CONTRACT.md")}.`),e.push(" We promise not to break those without a major version bump."),e.push(Dt("EXIT CODES")),e.push(` ${Sb("0")} Success`),e.push(` ${l("1")} Unknown error`),e.push(` ${bb("2")} Invalid arguments (usage error, see yellow message on stderr)`),e.push(` ${l("3")} Wallet not found`),e.push(` ${l("4")} Network error`),e.push(` ${l("5")} Insufficient balance / DUST_REQUIRED`),e.push(` ${l("6")} Transaction rejected / STALE_UTXO / PROOF_TIMEOUT`),e.push(` ${l("7")} Cancelled by user`),e.push(""),e.push(` ${k("Stable error code strings")} (in JSON ${D("--json")} error output):`),e.push(` ${D("DUST_REQUIRED")} No dust available to pay fees`),e.push(` ${D("STALE_UTXO")} UTXO consumed concurrently, retry`),e.push(` ${D("PROOF_TIMEOUT")} Proof generation exceeded deadline`),e.push(` ${D("PROOF_FAILURE")} Proof server rejected the proof`),e.push(` ${D("INVALID_DUST_PROOF")} Stale commitment tree, run ${l("mn cache clear")}`),e.push(` ${D("STALE_CACHE")} Local cache out of sync, run ${l("mn cache clear")}`),e.push(` ${D("SYNC_TIMEOUT")} Wallet sync exceeded its deadline`),e.push(Dt("TROUBLESHOOTING")),e.push(` ${k('Sync hangs forever or "applied > highest" error')}`),e.push(" Stale cache after a chain reset. Recover with:"),e.push(` ${l("$")} ${l("mn cache clear --wallet <name>")}`),e.push(""),e.push(` ${k('"DUST_REQUIRED" or "no dust available" on transfer')}`),e.push(" Wallet has NIGHT but no fee token. Register dust:"),e.push(` ${l("$")} ${l("mn dust register --wallet <name>")}`),e.push(" Then wait until status shows availability:"),e.push(` ${l("$")} ${l("mn dust status --wallet <name>")}`),e.push(""),e.push(` ${k('"Cannot find package @midnight-ntwrk/..." on contract deploy')}`),e.push(" The CLI bundles its own SDK. Reinstall to pick up the bundle:"),e.push(` ${l("$")} ${l("npm install -g midnight-wallet-cli@latest")}`),e.push(""),e.push(` ${k('"witnesses module not found" on contract deploy')}`),e.push(" Your contract declares witnesses but witnesses.js isn't built."),e.push(" Build the TypeScript source first:"),e.push(` ${l("$")} ${l("npm run build")}`),e.push(""),e.push(` ${k('"mn serve already running on port 9932 for network X"')}`),e.push(" A leftover serve from a previous network is in the way."),e.push(` ${l("$")} ${l("pkill -f 'mn serve'")}`),e.push(Dt("SEE ALSO")),e.push(` ${L("mn help")} Brief command list`),e.push(` ${L("mn help <command>")} Help for one command (flags and examples)`),e.push(` ${L("mn help --agent")} Comprehensive AI / MCP reference`),e.push(""),e.push(` Repository: ${l("github.com/nel349/midnight-wallet-cli")}`),e.push(` JSON contract: ${l("docs/JSON_CONTRACT.md")}`),e.push(""),e.join(`
|
|
1784
|
+
`)}function Sb(e){return`\x1B[32m${e}\x1B[0m`}function bb(e){return`\x1B[33m${e}\x1B[0m`}async function vb(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=hb(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 Zi(e){let t=!R(e,"no-pager");if(R(e,"json")){await Promise.resolve();_({name:Wr,version:Ze,manual:Yi()});return}if(R(e,"raw")){process.stdout.write(Yi().replace(/\x1b\[[0-9;]*m/g,""));return}await vb(Yi(),t)}var Sp,bp;var vp=T(()=>{Xi();Br();Sp="═".repeat(63),bp="─".repeat(64)});async function ra(e,t){kt(e);let r=A(e,"port"),n=r?parseInt(r,10):Mt;if(Number.isNaN(n)||n<1||n>65535)throw Error(`Invalid port: "${r}" — must be 1-65535`);let s=R(e,"approve-all"),o=R(e,"approve-fees");if(s&&o)throw new H("--approve-all and --approve-fees conflict: --approve-fees approves only fee payment, --approve-all approves everything. Pass one.");let i=A(e,"max-fee"),a=A(e,"max-pending");if(!o&&(i!==void 0||a!==void 0))throw new H("--max-fee and --max-pending only apply with --approve-fees.");let c=tl(i,a),d=!0,p=R(e,"no-auto-approve-reads"),u=R(e,"json"),g=ae(se(A(e,"wallet"))),m=Buffer.from(g.seed,"hex"),{name:h,config:f}=de({args:e}),y=g.addresses[h];Re(f,{proofServer:A(e,"proof-server"),node:A(e,"node"),indexerWS:A(e,"indexer-ws")},h),process.stderr.write(`
|
|
1785
|
+
`+j("DApp Connector Server")+`
|
|
1786
|
+
|
|
1787
|
+
`),process.stderr.write(C("Network",h)+`
|
|
1788
|
+
`),process.stderr.write(C("Address",re(y,!0))+`
|
|
1757
1789
|
`),process.stderr.write(C("Port",String(n))+`
|
|
1758
|
-
`),process.stderr.write(C("Auto-approve
|
|
1759
|
-
`),process.stderr.write(
|
|
1760
|
-
`)
|
|
1761
|
-
`)
|
|
1762
|
-
`)
|
|
1763
|
-
`)
|
|
1764
|
-
`),
|
|
1765
|
-
`)},
|
|
1766
|
-
`),
|
|
1767
|
-
`)}
|
|
1768
|
-
`)
|
|
1769
|
-
`)}}}),process.stderr.write(`
|
|
1770
|
-
|
|
1790
|
+
`);let S=zd({approveAll:s,approveFees:o,autoApproveReads:d},c);if(process.stderr.write(C("Auto-approve balancing",{auto:"yes","fee-only":"fee-only (Dust fee only)",prompt:"no"}[S.balancing])+`
|
|
1791
|
+
`),p)process.stderr.write(l(" --no-auto-approve-reads has no effect: read methods never prompt, and balancing prompts unless --approve-all or --approve-fees")+`
|
|
1792
|
+
`);if(process.stderr.write(C("Auto-approve writes",{auto:"yes","fee-only":"fee-only (submit of a fee-only balance)",prompt:"no"}[S.writes])+`
|
|
1793
|
+
`),S.feeLimits)process.stderr.write(C("Fee limits",`max ${Me(c.maxFeeSpecks)} DUST per tx, ${c.maxPending} unsubmitted at once`)+`
|
|
1794
|
+
`);process.stderr.write(`
|
|
1795
|
+
`);let w=xe((I,O)=>{let z=Xc();if(z)z.log(l(` SDK: ${O}`));else process.stderr.write(l(` SDK: ${O}`)+`
|
|
1796
|
+
`)}),b=_e();if(We(e))Ge();let x=G("Syncing wallet...");await ye().withFacade(m,f,async({bundle:I})=>{x.stop("Wallet synced");let O=G("Waiting for dust..."),z=await ar(I),Q=yt(z);O.stop(Q?"Dust ready":"Dust not yet available (writes may fail)");try{await Xe(y,h,I.facade)}catch{}if(t?.aborted)throw Error("Operation cancelled");let K,M;try{let F={approve:"Waiting for approval...",building:"Building transaction...",signing:"Signing...",proving:"Proving (ZK)...",submitting:"Submitting..."},ee;M=As({bundle:I,networkConfig:f,approvalOptions:{approveAll:s,approveFees:o,autoApproveReads:d},feeLimits:c,callbacks:{onPhaseStart:(le,ge,te)=>{if(te==="approve")return;let Oe=F[te]??`${te}...`;if(ee)ee.update(Oe);else ee=G(Oe)},onPhaseComplete:(le,ge,te,Oe)=>{if(te==="approve")return;if(te==="proving"||te==="submitting")ee?.stop(`${te} ${ta(Oe)}`),ee=void 0}}}),K=Cs({port:n,handlers:M.handlers,onConnect:(le)=>{process.stderr.write(l(` [${Qi()}] `)+B("connected")+l(` ${le.id}`)+`
|
|
1797
|
+
`)},onDisconnect:(le)=>{process.stderr.write(l(` [${Qi()}] `)+J("disconnected")+l(` ${le.id}`)+`
|
|
1798
|
+
`),M?.revertPendingTxs(le.id).catch(()=>{})},onRequest:(le,ge)=>{process.stderr.write(l(` [${Qi()}] ${le.id} #${le.requestCount} → ${ge.method}`)+`
|
|
1799
|
+
`)},onResponse:(le,ge,te,Oe,Ae,Se)=>{if(Ae&&ee)ee.fail("Failed"),ee=void 0;let st=ta(te);if(Ae){let Ve=Ae.code==="Rejected"&&Ae.message===Es?"rejected by operator":Ae.message;if(process.stderr.write(` ${J("✗")} ${l(`${le.id} ← ${ge.method} (${st})`)} ${J(Ve)}
|
|
1800
|
+
`),Ae.code!=="Rejected"&&Ae.message)process.stderr.write(` ${l(" error:")} ${Ae.message}
|
|
1801
|
+
`)}else{let Ve=Se?.phases,me=Ve&&Ve.length>0?": "+Ve.map((qe)=>`${qe.phase} ${ta(qe.durationMs)}`).join(", "):"";process.stderr.write(` ${B("✓")} ${l(`${le.id} ← ${ge.method} (${st}${me})`)}
|
|
1802
|
+
`);let fe=Oe?.txHash;if(ge.method==="submitTransaction"&&fe)process.stderr.write(` ${l(" tx:")} ${L(String(fe))}
|
|
1803
|
+
`)}}});try{await K.ready}catch(le){let ge=le.code;throw Error(ge==="EADDRINUSE"?`Port ${n} is already in use (another mn serve?). Stop it or pass --port <n>.`:`Could not listen on port ${n}: ${le.message}`)}if(process.stderr.write(`
|
|
1804
|
+
`+V()+`
|
|
1771
1805
|
`),process.stderr.write(" "+k(L(`Server ready — listening on ws://localhost:${n}`))+`
|
|
1772
1806
|
`),process.stderr.write(l(" Press Ctrl+C to stop")+`
|
|
1773
1807
|
|
|
1774
|
-
`),
|
|
1808
|
+
`),u)_({port:n,network:h,address:y,status:"listening",approval:S});if(await new Promise((le)=>{if(t)if(t.aborted)le();else t.addEventListener("abort",()=>le(),{once:!0})}),process.stderr.write(`
|
|
1775
1809
|
`+l(" Shutting down...")+`
|
|
1776
|
-
`),!
|
|
1810
|
+
`),!M.hasPendingTxs())try{await Xe(y,h,I.facade)}catch{}try{await K.close()}catch{}M.dispose(),M=void 0,K=void 0,process.stderr.write(l(" Server stopped.")+`
|
|
1777
1811
|
|
|
1778
|
-
`)}catch(
|
|
1779
|
-
Run "mn dev" from a Midnight project directory (expected .compact files in ./, ./src, ./contract, or ./contract/src).`);let s=
|
|
1812
|
+
`)}catch(F){if(x.fail("Failed"),K)try{await K.close()}catch{}throw M?.dispose(),F}},{syncMode:or(h,R(e,"force-shielded"))?"full":"lite",requireStrictSync:!0,skipAutoSave:!0,signal:t,onStatus:(I)=>x.update(I),onSyncProgress:(I,O)=>{if(O>0){let z=Math.min(Math.round(I/O*100),100);x.update(z>=100?"Syncing wallet...":`Syncing wallet... ${z}%`)}},onSyncDetail:(I)=>x.update(`Syncing wallet... (waiting on: ${I})`)}).finally(()=>{b(),w()})}function Qi(){let e=new Date;return`${ea(e.getHours())}:${ea(e.getMinutes())}:${ea(e.getSeconds())}`}function ea(e){return e<10?"0"+e:String(e)}function ta(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var kp=T(()=>{wt();Ie();Ce();we();ze();_t();bt();Pt();Si();xs();Un();ue();pi();di();tt();Fe()});import{existsSync as Ep,readFileSync as kb,readdirSync as Cb,statSync as xb}from"node:fs";import{dirname as Eb,join as na,resolve as Cp}from"node:path";function Ap(e){let t=Cp(e),r=new Set,n=new Set;for(let u of Nb){let g=Cp(t,u);if(!Ep(g))continue;$p(g,0,r,n)}if(r.size===0)throw Error(`No .compact source files found under ${t}
|
|
1813
|
+
Run "mn dev" from a Midnight project directory (expected .compact files in ./, ./src, ./contract, or ./contract/src).`);let s=_b([...n],t),o=s?.dir??t,i=s?.packageJson??Np(na(t,"package.json")),a=s?.script??Tp(i),c=[...r].filter((u)=>xp(u,o)).sort(),d=[...n].filter((u)=>xp(u,o)).sort(),p=Ib(i);return{projectRoot:o,sourceFiles:c.length>0?c:[...r].sort(),sourceDirs:d.length>0?d:[...n].sort(),compileScript:a,hasNpmCompileScript:a!==null,testScript:p,packageJson:i}}function Ib(e){for(let t of Tb)if(Rp(e,t))return t;return null}function xp(e,t){if(e===t)return!0;let r=t.endsWith("/")?t:t+"/";return e.startsWith(r)}function _b(e,t){for(let r of e){let n=r;while(!0){let s=na(n,"package.json"),o=Np(s),i=Tp(o);if(o&&i)return{dir:n,packageJson:o,script:i};if(n===t)break;let a=Eb(n);if(a===n)break;n=a}}return null}function Tp(e){for(let t of Ab)if(Rp(e,t))return t;return null}function Np(e){if(!Ep(e))return null;try{let t=JSON.parse(kb(e,"utf-8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Rp(e,t){if(!e)return!1;let r=e.scripts;if(!r||typeof r!=="object")return!1;return typeof r[t]==="string"}function $p(e,t,r,n){if(t>Rb)return;let s;try{s=Cb(e)}catch{return}for(let o of s){if(o.startsWith(".")||$b.has(o))continue;let i=na(e,o),a=!1;try{a=xb(i).isDirectory()}catch{continue}if(a)$p(i,t+1,r,n);else if(o.endsWith(".compact"))r.add(i),n.add(e)}}var Ab,Tb,Nb,Rb=4,$b;var Ip=T(()=>{Ab=["compact","compile"],Tb=["test:dev","test"],Nb=[".","contract/src","contract","src"],$b=new Set(["node_modules",".git","dist","build","managed","target"])});import{spawn as Pb}from"node:child_process";async function _p(e){let{bin:t,args:r,label:n}=Db(e),s=Date.now();return new Promise((o,i)=>{let a=Pb(t,r,{cwd:e.project.projectRoot,env:process.env,stdio:["ignore","pipe","pipe"]}),c="",d="";a.stdout?.on("data",(u)=>{c+=u.toString()}),a.stderr?.on("data",(u)=>{d+=u.toString()});let p=()=>{a.kill("SIGTERM")};if(e.signal)if(e.signal.aborted)p();else e.signal.addEventListener("abort",p,{once:!0});a.on("error",(u)=>{e.signal?.removeEventListener("abort",p),i(Error(`Failed to spawn "${n}": ${u.message}`))}),a.on("close",(u)=>{e.signal?.removeEventListener("abort",p),o({success:u===0,durationMs:Date.now()-s,command:n,stdout:c,stderr:d,exitCode:u??-1})})})}function Db(e){if(e.commandOverride){let{bin:t,args:r}=e.commandOverride;return{bin:t,args:r,label:[t,...r].join(" ")}}if(e.project.compileScript){let t=e.project.compileScript;return{bin:"npm",args:["run",t,"--silent"],label:`npm run ${t}`}}throw Error(`No compile script found in package.json.
|
|
1780
1814
|
Add one of:
|
|
1781
1815
|
"compact": "compact compile src/<your>.compact src/managed/<your>"
|
|
1782
1816
|
"compile": "compact compile src/<your>.compact src/managed/<your>"
|
|
1783
|
-
create-mn-app and midnight-starship templates ship with this script already wired.`)}var
|
|
1817
|
+
create-mn-app and midnight-starship templates ship with this script already wired.`)}var Pp=()=>{};import{spawn as Ob}from"node:child_process";async function Dp(e){let{bin:t,args:r,label:n}=Mb(e),s=Date.now();return new Promise((o,i)=>{let a=Ob(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 Mb(e){if(e.commandOverride){let{bin:r,args:n}=e.commandOverride;return{bin:r,args:n,label:[r,...n].join(" ")}}if(!e.project.testScript)throw Error(`No test script found in package.json.
|
|
1784
1818
|
Add a "test:dev" or "test" script that runs your contract tests
|
|
1785
|
-
(e.g. "test": "vitest run"), then press t again.`);let t=e.project.testScript;return{bin:"npm",args:["run",t,"--silent"],label:`npm run ${t}`}}var
|
|
1786
|
-
`)})};return t.on("data",s),{stop(){if(n)return;n=!0,t.off("data",s);try{t.setRawMode(r)}catch{}}}}var
|
|
1787
|
-
`+
|
|
1819
|
+
(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 Op=()=>{};import{watch as Fb}from"node:fs";import{join as Lb}from"node:path";function Mp(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=Fb(i,{persistent:!0},(c,d)=>{if(!d)return;if(!d.endsWith(e.extension))return;if(n.add(Lb(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 Fp=()=>{};async function Lp(e){let{name:t,config:r}=de({args:{command:"dev",subcommand:void 0,positionals:[],flags:{network:"undeployed"}}});return e?.(`Checking the ledger-9 stack at ${r.node}`),await zn(t,r),{state:"already-running"}}var Up=T(()=>{Ce();Kt()});import{existsSync as Ub}from"node:fs";import{join as jb}from"node:path";import{homedir as Wb}from"node:os";async function Bp(e){let t=[],r=Bb();try{for(let n of e.names){if(e.signal?.throwIfAborted(),Hp(n)){e.onProgress?.(n,"done","reused"),t.push({name:n,state:"reused"});continue}e.onProgress?.(n,"creating","created"),await Gb(n,e.signal),e.onProgress?.(n,"funding","created"),await Kb(n,e.amountNight,e.signal),e.onProgress?.(n,"dust","created"),await Jb(n,e.signal),e.onProgress?.(n,"done","created"),t.push({name:n,state:"created"})}}finally{Hb(r)}return t}function Bb(){try{return Nt()}catch{return null}}function Hb(e){if(!e)return;if(!Hp(e))return;try{Yr(e)}catch{}}function Hp(e){let t=jb(Wb(),ie,Yt,`${e}.json`);return Ub(t)}async function Gb(e,t){let r={command:"wallet",subcommand:"generate",positionals:[e],flags:{network:"undeployed"}};await Promise.resolve().then(() => ws());await q(yr,r,t)}async function Kb(e,t,r){let n={command:"airdrop",subcommand:String(t),positionals:[],flags:{wallet:e,network:"undeployed"}};await Promise.resolve().then(() => cs());await q(gr,n,r)}async function Jb(e,t){let r={command:"dust",subcommand:"register",positionals:[],flags:{wallet:e,network:"undeployed"}};await Promise.resolve().then(() => ls());await q(hr,r,t)}var jp,Wp=1000;var Gp=T(()=>{Pn();Ie();jp=["dev-alice","dev-bob","dev-carol"]});function Kp(e){if(!Vb)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}
|
|
1820
|
+
`)})};return t.on("data",s),{stop(){if(n)return;n=!0,t.off("data",s);try{t.setRawMode(r)}catch{}}}}var Vb;var Jp=T(()=>{Vb=typeof process.stdin.isTTY==="boolean"&&process.stdin.isTTY===!0});import{resolve as qb,relative as Vp}from"node:path";async function sa(e,t){let r=qb(e.positionals[0]??process.cwd());process.stderr.write(`
|
|
1821
|
+
`+j("mn dev")+`
|
|
1788
1822
|
|
|
1789
|
-
`);let n=
|
|
1823
|
+
`);let n=Ap(r);if(!n.compileScript)throw Error(`No compile script found in ${n.projectRoot}/package.json.
|
|
1790
1824
|
mn dev looks for a "compact" or "compile" npm script that invokes the
|
|
1791
1825
|
Compact toolchain. Add one of:
|
|
1792
1826
|
"scripts": { "compact": "compact compile src/my.compact src/managed/my" }
|
|
@@ -1795,50 +1829,51 @@ create-mn-app and midnight-starship templates ship with this already wired.`);pr
|
|
|
1795
1829
|
`),process.stderr.write(C("Sources",`${n.sourceFiles.length} .compact file(s)`)+`
|
|
1796
1830
|
`),process.stderr.write(C("Compile",`npm run ${n.compileScript}`)+`
|
|
1797
1831
|
|
|
1798
|
-
`);let s=
|
|
1832
|
+
`);let s=G("Checking localnet...");try{let w=await Lp((x)=>s.update(x)),b={"already-running":"Ledger-9 stack reachable"}[w.state];s.stop(b)}catch(w){throw s.fail("Localnet setup failed"),w}let o=G("Provisioning dev wallets...");try{let w=await Bp({names:jp,amountNight:Wp,signal:t,onProgress:(O,z)=>{let Q={creating:"generating",funding:"airdropping",dust:"registering dust",done:"ready"}[z];o.update(`${O}: ${Q}`)}}),b=w.filter((O)=>O.state==="created").length,x=w.length-b,I=[b?`${b} created`:"",x?`${x} reused`:""].filter(Boolean).join(", ");o.stop(`Dev wallets: ${w.map((O)=>O.name).join(", ")} (${I})`)}catch(w){throw o.fail("Wallet provisioning failed"),w}let i=null,a=!1,c=!1,d=!1,p=!1;if(i=await Xp(n,t),!i.success)process.stderr.write(l(`
|
|
1799
1833
|
Fix the errors above and save — mn dev will recompile automatically.
|
|
1800
|
-
`));let
|
|
1834
|
+
`));let u=async()=>{if(a||c)return;if(d){p=!0;return}d=!0;try{i=await Xp(n,t)}finally{if(d=!1,p)p=!1,u()}},g=Mp({dirs:n.sourceDirs,extension:".compact",onChange:async(w)=>{let b=w.map((x)=>Vp(n.projectRoot,x)).join(", ");process.stderr.write(`
|
|
1801
1835
|
`+l(` Changed: ${b}`)+`
|
|
1802
|
-
`),await
|
|
1836
|
+
`),await u()},onError:(w)=>{process.stderr.write(J(" watch error: ")+w.message+`
|
|
1803
1837
|
`)}});process.stderr.write(`
|
|
1804
|
-
`+
|
|
1805
|
-
`);let
|
|
1838
|
+
`+V()+`
|
|
1839
|
+
`);let m=n.sourceDirs.map((w)=>Vp(n.projectRoot,w)||".").join(", ");process.stderr.write(l(" Watching ")+L(m)+l(" — save to recompile.")+`
|
|
1806
1840
|
`);let h=n.testScript?k("[t]")+l(` test (${n.testScript}) `):"";process.stderr.write(l(" ")+k("[d]")+l(" deploy ")+h+k("[q]")+l(` quit
|
|
1807
1841
|
|
|
1808
|
-
`));let
|
|
1842
|
+
`));let f=new AbortController,y=()=>{if(!f.signal.aborted)f.abort()},S=Kp({actions:{d:async()=>{if(a){process.stderr.write(l(` Deploy already in flight — ignoring key press.
|
|
1809
1843
|
`));return}if(c){process.stderr.write(l(` Tests are running — wait for them to finish before deploying.
|
|
1810
|
-
`));return}if(!i?.success){process.stderr.write(
|
|
1811
|
-
`));return}a=!0;try{await
|
|
1844
|
+
`));return}if(!i?.success){process.stderr.write(D(` Cannot deploy — last compile did not succeed. Fix and save first.
|
|
1845
|
+
`));return}a=!0;try{await zb(n)}finally{a=!1}},t:async()=>{if(c){process.stderr.write(l(` Tests already in flight — ignoring key press.
|
|
1812
1846
|
`));return}if(a){process.stderr.write(l(` Deploy in flight — wait for it to finish before running tests.
|
|
1813
|
-
`));return}if(!n.testScript){process.stderr.write(
|
|
1814
|
-
`));return}if(!i?.success){process.stderr.write(
|
|
1815
|
-
`));return}c=!0;try{await
|
|
1847
|
+
`));return}if(!n.testScript){process.stderr.write(D(` No test script found. Add "test:dev" or "test" to package.json.
|
|
1848
|
+
`));return}if(!i?.success){process.stderr.write(D(` Cannot run tests — last compile did not succeed. Fix and save first.
|
|
1849
|
+
`));return}c=!0;try{await Xb(n,f.signal)}finally{c=!1}},q:()=>y()},onInterrupt:y});await new Promise((w)=>{let b=()=>{S.stop(),g.stop(),process.stderr.write(`
|
|
1816
1850
|
`+l(" mn dev stopped.")+`
|
|
1817
|
-
`),
|
|
1851
|
+
`),w()};if(f.signal.aborted){b();return}if(f.signal.addEventListener("abort",b,{once:!0}),t?.aborted){y();return}t?.addEventListener("abort",y,{once:!0})})}async function zb(e){let t=process.cwd();if(t!==e.projectRoot)try{process.chdir(e.projectRoot)}catch{}try{let r=await Yb(e.projectRoot);if(r.length>0&&!Rs(e.projectRoot)){let s=$s({projectRoot:e.projectRoot,witnessNames:r});process.stderr.write(D(` ✗ Cannot auto-deploy:
|
|
1818
1852
|
`));for(let o of s.split(`
|
|
1819
1853
|
`))process.stderr.write(l(` ${o}
|
|
1820
|
-
`));return}let n=
|
|
1821
|
-
`)}catch(s){n.fail("Deploy failed");let o=s instanceof Error?s.message:String(s);process.stderr.write(
|
|
1822
|
-
`)}}finally{if(process.cwd()!==t)try{process.chdir(t)}catch{}}}async function
|
|
1854
|
+
`));return}let n=G(`Deploying with ${qp} on ${zp}...`);try{await Promise.resolve().then(() => Ls());let o=await q(Er,{command:"contract",subcommand:"deploy",positionals:[],flags:{wallet:qp,network:zp}});n.stop("Deployed");let i=typeof o.address==="string"?o.address:"(unknown)";process.stderr.write(` ${l("address")} ${L(i)}
|
|
1855
|
+
`)}catch(s){n.fail("Deploy failed");let o=s instanceof Error?s.message:String(s);process.stderr.write(J(" "+o)+`
|
|
1856
|
+
`)}}finally{if(process.cwd()!==t)try{process.chdir(t)}catch{}}}async function Xb(e,t){process.stderr.write(l(`
|
|
1823
1857
|
Running npm run ${e.testScript}...
|
|
1824
|
-
`));try{let r=await
|
|
1825
|
-
`);else process.stderr.write(` ${l("─")} ${
|
|
1826
|
-
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(
|
|
1827
|
-
`)}}async function
|
|
1828
|
-
`),process.stderr.write(
|
|
1829
|
-
`);return n}catch(n){r.fail("Compile error");let s=n instanceof Error?n.message:String(n);return process.stderr.write(
|
|
1830
|
-
`),{success:!1,durationMs:0,command:"",stdout:"",stderr:s,exitCode:-1}}}function
|
|
1858
|
+
`));try{let r=await Dp({project:e,signal:t});if(r.success)process.stderr.write(` ${l("─")} Tests passed ${l(`(${Js(r.durationMs)})`)}
|
|
1859
|
+
`);else process.stderr.write(` ${l("─")} ${J("Tests failed")} ${l(`(exit ${r.exitCode}, ${Js(r.durationMs)})`)}
|
|
1860
|
+
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(J(" Test runner error: ")+n+`
|
|
1861
|
+
`)}}async function Yb(e){try{await Promise.resolve().then(() => fn());let{info:r}=rt(e);return r.witnesses.map((n)=>n.name)}catch{return[]}}async function Xp(e,t){let r=G("Compiling...");try{let n=await _p({project:e,signal:t});if(n.success)r.stop(`Compiled ${l(`(${Js(n.durationMs)})`)}`);else if(r.fail(`Compile failed ${l(`(${Js(n.durationMs)})`)}`),n.stderr.trim())process.stderr.write(l(" ─ stderr ─")+`
|
|
1862
|
+
`),process.stderr.write(D(Zb(n.stderr.trim()," "))+`
|
|
1863
|
+
`);return n}catch(n){r.fail("Compile error");let s=n instanceof Error?n.message:String(n);return process.stderr.write(J(" "+s)+`
|
|
1864
|
+
`),{success:!1,durationMs:0,command:"",stdout:"",stderr:s,exitCode:-1}}}function Js(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(2)}s`}function Zb(e,t){return e.split(`
|
|
1831
1865
|
`).map((r)=>t+r).join(`
|
|
1832
|
-
`)}var
|
|
1833
|
-
|
|
1866
|
+
`)}var qp="dev-alice",zp="undeployed";var Yp=T(()=>{Ip();Pp();Op();Fp();Up();Gp();Jp();Is();Pn();ue();tt()});ue();Fe();var im=["help","h","json","version","v"],er=["node","indexer-ws","proof-server"],am={address:["index","network","seed","wallet"],airdrop:["network","no-cache","shielded","verbose","wallet",...er],balance:["force-shielded","network","no-cache","seed","shielded","verbose","wallet",...er],cache:["network","wallet"],config:[],contract:["address","args","circuit","managed","name","network","path","secret-key","wallet",...er],dev:[],dust:["network","no-cache","seed","verbose","wallet",...er],generate:["force","mnemonic","network","output","seed"],"genesis-address":["network"],help:["agent","intro","no-intro"],info:["network","wallet"],"inspect-cost":[],localnet:["tail"],manual:["no-pager","raw"],serve:["approve-all","approve-fees","force-shielded","max-fee","max-pending","network","no-auto-approve-reads","no-cache","port","verbose","wallet",...er],status:["all","network","watch"],test:["all","browser-mode","build-cmd","build-dir","force","goal","name","network","no-ai","path","port","redeploy","screen","strategy","suite","url"],transfer:["force-shielded","network","no-cache","shielded","verbose","wallet",...er],wallet:["entropy","force","mnemonic","network","seed","wallet"]};function cm(e){let t=e.command===void 0?void 0:am[e.command];if(t===void 0)return[];return Object.keys(e.flags).filter((r)=>!im.includes(r)&&!t.includes(r))}function $a(e){let t=cm(e);if(t.length===0)return;let r=t.map((n)=>n.length===1?`-${n}`:`--${n}`).join(", ");throw new H(`Unknown flag${t.length>1?"s":""} for "midnight ${e.command}": ${r}
|
|
1867
|
+
Run "midnight help ${e.command}" for the flags it accepts.`)}so();Fe();Br();Ie();yo();var Zp=new Set(["airdrop","transfer","dust","balance","serve","test","contract","dev"]);if(process.argv.includes("--mcp"))await Zr(),await Promise.resolve().then(() => (cp(),{}));else{let i=function(){s.abort(),setTimeout(()=>process.exit(130),5000).unref()},e=aa(),t=R(e,"json");if(R(e,"version")||R(e,"v"))process.stdout.write(Ze+`
|
|
1868
|
+
`),process.exit(0);let r=R(e,"help")||R(e,"h");if(r)e.command="help";let n=e.command??"help";if(Zp.has(n))await Zr();za();let s=new AbortController,{signal:o}=s;process.on("SIGINT",i),process.on("SIGTERM",i);async function a(){if(!r)$a(e);switch(n){case"help":{await Promise.resolve().then(() => Xi());return zi(e)}case"manual":{await Promise.resolve().then(() => vp());return Zi(e)}case"wallet":{await Promise.resolve().then(() => ws());return yr(e)}case"generate":{process.stderr.write(`
|
|
1834
1869
|
Note: "midnight generate" is deprecated.
|
|
1835
1870
|
Use "midnight wallet generate <name>" instead.
|
|
1836
1871
|
|
|
1837
|
-
`);
|
|
1838
|
-
Run "midnight help" to see available commands.`)}}
|
|
1839
|
-
`+
|
|
1872
|
+
`);await Promise.resolve().then(() => bo());return Mn(e)}case"info":{await Promise.resolve().then(() => vo());return Fn(e)}case"balance":{await Promise.resolve().then(() => Jo());return ss(e)}case"address":{await Promise.resolve().then(() => Vo());return os(e)}case"genesis-address":{await Promise.resolve().then(() => qo());return is(e)}case"inspect-cost":{await Promise.resolve().then(() => zo());return as(e)}case"config":{await Promise.resolve().then(() => Zo());return ps(e)}case"cache":{await Promise.resolve().then(() => Yo());return us(e)}case"airdrop":{await Promise.resolve().then(() => cs());return gr(e,o)}case"transfer":{await Promise.resolve().then(() => Xo());return ds(e,o)}case"dust":{await Promise.resolve().then(() => ls());return hr(e,o)}case"localnet":{await Promise.resolve().then(() => ni());return hs(e)}case"status":throw Error('The "status" command is currently being reworked. Check back soon.');case"serve":{await Promise.resolve().then(() => kp());return ra(e,o)}case"test":{await Promise.resolve().then(() => Bi());return Hs(e,o)}case"contract":{await Promise.resolve().then(() => Ls());return Er(e,o)}case"dev":{await Promise.resolve().then(() => Yp());return sa(e,o)}default:throw new H(`Unknown command: "${n}"
|
|
1873
|
+
Run "midnight help" to see available commands.`)}}a().then(()=>{if(Zp.has(n))process.exit(0)}).catch((c)=>{let d=Ia(c.message);if(Ra(c)){if(t)io(c,"INVALID_ARGS",no);else process.stderr.write(`
|
|
1874
|
+
`+Na(d,'Run "midnight manual" for the full reference, or "midnight help <command>" for one command.')+`
|
|
1840
1875
|
|
|
1841
|
-
`);process.exit(
|
|
1842
|
-
`+
|
|
1876
|
+
`);process.exit(no)}else if(t){let{exitCode:p,errorCode:u}=Ur(c);io(c,u,p),process.exit(p)}else{process.stderr.write(`
|
|
1877
|
+
`+Ta(d,'Run "midnight help" for usage information.')+`
|
|
1843
1878
|
|
|
1844
|
-
`);let{exitCode:
|
|
1879
|
+
`);let{exitCode:p}=Ur(c);process.exit(p)}})}
|