midnight-wallet-cli 0.5.7 → 0.5.8
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 +26 -4
- package/dist/mcp-server.js +358 -349
- package/dist/wallet.js +581 -537
- package/docs/SKILL-CORE.md +47 -0
- package/docs/SKILL.md +22 -8
- package/package.json +7 -6
package/dist/mcp-server.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as ap}from"node:module";var sp=Object.defineProperty;var op=(e)=>e;function ip(e,t){this[e]=op.bind(null,t)}var fe=(e,t)=>{for(var r in t)sp(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ip.bind(t,r)})};var N=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var wi=ap(import.meta.url);function k(e,t){let r=e.flags[t];if(r===void 0||r===!0)return;return r}function D(e,t){return t in e.flags}function We(e){return D(e,"verbose")}function ct(e){return D(e,Jr)&&!D(e,ar)}function $t(e){if(D(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 Vr(e,t,r){let n=k(e,t);if(n===void 0)throw Error(`Missing required flag: --${t} <${r}>`);return n}var Jr="_minimal",
|
|
5
|
-
`;if(
|
|
4
|
+
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function Vr(e,t,r){let n=k(e,t);if(n===void 0)throw Error(`Missing required flag: --${t} <${r}>`);return n}var Jr="_minimal",ar="_full";function ms(e){fs=e}function I(e){let t=JSON.stringify(e)+`
|
|
5
|
+
`;if(fs)fs(t);else process.stdout.write(t)}var fs=null;function yi(e){return e instanceof W}var W;var Fe=N(()=>{W=class W extends Error{constructor(e){super(e);this.name="UsageError",Object.setPrototypeOf(this,W.prototype)}}});function yt(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 Qe="0000000000000000000000000000000000000000000000000000000000000001",cr="0000000000000000000000000000000000000000000000000000000000000000",Mt="/api/v4/graphql",qr="/api/v4/graphql/ws",ws=6,ys=1e6,xi=300000000000000n,Ai=5,Te=800000000000000n,Ti=5000000000n,Ni=8267n,Ri=10800n,Di=300000,Ss=30000,Ii=1e4,bs=120000,Yr=300000,vs=60000,_i=16384,Pi=0.7,$i=512,dr=10,Oi=3,Mi=600000,ks=15000,Fi=115,ie=".midnight",Xr="wallet.json",Ui="config.json",me=448,ge=384,Li="localnet",Cs=1,Ce="cache",Zr="wallets",Es="default",lr=10,xs=3000,Bi=120000,ur=9932,Qr="https://midnight-comp-tracker.vercel.app";function tn(e){return Object.hasOwn(et,e)}function Ft(){return Object.keys(et)}function Ut(e){return Ft().find((t)=>e.startsWith(et[t].prefix))}function rn(e){let t=e.trim(),r=/^[A-Za-z0-9]+$/.test(t)?Ut(t):void 0;if(r===void 0){let n=Ft().map((s)=>`"${et[s].prefix}" (${s})`).join(", ");throw new W(`That is not a Blockfrost project id mn can use: it should start with ${n}. Project ids are per network; create a project for the Midnight network you need at ${en}.`)}return{projectId:t,network:r}}function Rs(e,t){let{host:r}=et[e],n=t===void 0?"":`?${pr}=${t}`;return{indexer:`https://${r}/api/v0${n}`,indexerWS:`wss://${r}/api/v0/ws${n}`,node:`wss://rpc.${r}${n}`}}function nn(e){try{return new URL(e)}catch{return}}function Ji(e){return Ft().find((t)=>{let{host:r}=et[t];return e.hostname===r||e.hostname===`rpc.${r}`})}function Ds(e){let t=nn(e)?.hostname;return t!==void 0&&(t==="blockfrost.io"||t.endsWith(".blockfrost.io"))}function ye(e){let t=nn(e);if(t===void 0)return;if(Object.hasOwn(Gi,t.hostname))throw new sn(e);let r=Ji(t);if(r!==void 0&&!t.searchParams.get(pr))throw new Lt(r)}function fr(e,t){if(t===410)return new sn(e);let r=nn(e);if(r===void 0||!Ds(e))return;let n=Ji(r)??"this network";if(t===403)return r.searchParams.get(pr)?new Is(n):new Lt(n);if(t===402||t===429)return new _s(t);return}function Bt(e,t){let r=/Unexpected server response: (\d{3})/.exec(t instanceof Error?t.message:String(t))?.[1];return r===void 0?void 0:fr(e,Number(r))}function on(e){return e.replace(vp,`$1${Ki}`).replace(kp,`$1${Ki}`)}function Ps(e){return e.includes(`${pr}=`)||Object.values(et).some(({prefix:t})=>e.includes(t))}function Vi(e){let t=Ut(e);return`${t===void 0?"":et[t].prefix}…${e.slice(-4)}`}var et,pr="project_id",en="https://blockfrost.io",Ns="midnight config set blockfrost-project-id <project id>",Gi,Lt,Is,_s,sn,vp,kp,Ki="***";var _e=N(()=>{Fe();et={preprod:{host:"midnight-preprod.blockfrost.io",prefix:"nightpreprod"}},Gi={"indexer.preprod.midnight.network":"2026-10-09"};Lt=class Lt extends Error{code="BLOCKFROST_PROJECT_ID_REQUIRED";constructor(e){super(`${e}'s indexer and node are served by Blockfrost, which needs your own project id on every request, and none is set.
|
|
6
6
|
Create a project for Midnight ${e} at ${en} and set its id once:
|
|
7
|
-
${
|
|
7
|
+
${Ns}`);this.name="BlockfrostProjectIdRequiredError",Object.setPrototypeOf(this,Lt.prototype)}};Is=class Is extends Error{code="BLOCKFROST_PROJECT_ID_REJECTED";constructor(e){super(`Blockfrost refused the project id set for ${e} (HTTP 403).
|
|
8
8
|
Check it at ${en}: it must be the id of a Midnight ${e} project. Then set it again:
|
|
9
|
-
${
|
|
10
|
-
Wait and run the command again, or see the project's usage and plan at ${en}.`);this.name="BlockfrostLimitError",Object.setPrototypeOf(this,
|
|
9
|
+
${Ns}`);this.name="BlockfrostProjectIdRejectedError",Object.setPrototypeOf(this,Is.prototype)}};_s=class _s extends Error{code="BLOCKFROST_LIMIT_REACHED";constructor(e){super(`Blockfrost answered HTTP ${e}, which its API uses for `+(e===402?"a project that has used up its plan's daily requests":"too many requests in a short time")+`.
|
|
10
|
+
Wait and run the command again, or see the project's usage and plan at ${en}.`);this.name="BlockfrostLimitError",Object.setPrototypeOf(this,_s.prototype)}};sn=class sn extends Error{code="ENDPOINT_SHUT_DOWN";constructor(e){let t=nn(e)?.hostname??on(e),r=Gi[t];super(`${t} was shut down${r===void 0?"":` on ${r}`}: it no longer serves the network.
|
|
11
11
|
It is set as an endpoint, by a flag or with "midnight config set". Remove it (midnight config unset indexer-ws, or node) to use the network's current endpoints; preprod's are Blockfrost's and need a project id:
|
|
12
|
-
${
|
|
13
|
-
`,{mode:ge})}function
|
|
14
|
-
Valid keys: ${an.join(", ")}`)}function
|
|
15
|
-
Valid networks: preprod, preview, undeployed`);
|
|
16
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(n===
|
|
12
|
+
${Ns}`);this.name="EndpointShutDownError",Object.setPrototypeOf(this,sn.prototype)}};vp=new RegExp(`([?&]${pr}=)[A-Za-z0-9_.~%-]+`,"g"),kp=new RegExp(`\\b(${Object.values(et).map(({prefix:e})=>e).join("|")})[A-Za-z0-9]{12,}\\b`,"g")});import*as rt from"fs";import*as $s from"path";import{homedir as Ep}from"os";function Os(e){return xp[e]??e}function Ap(e){return/^(https?|wss?):\/\/\S+/.test(e)}function Xi(e){return e??$s.join(Ep(),ie)}function Zi(e){return $s.join(Xi(e),Ui)}function Tp(e){let t=Xi(e);if(!rt.existsSync(t))rt.mkdirSync(t,{recursive:!0,mode:me})}function Re(e){let t=Zi(e);if(!rt.existsSync(t))return{...mr};let r;try{r=rt.readFileSync(t,"utf-8")}catch{return{...mr}}let n;try{n=JSON.parse(r)}catch{return{...mr}}let s={network:n.network&&Ne(n.network)?n.network:mr.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(!Ne(i)||!a||typeof a!=="object")continue;let c={};for(let l of gr){let u=a[l];if(u&&typeof u==="string")c[l]=u}let d=a[tt];if(typeof d==="string"&&Ut(d)===i)c[tt]=d;if(Object.keys(c).length>0)o[i]=c}if(Object.keys(o).length>0)s.networks=o}return s}function Ms(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 Fs(e,t){return e.networks?.[t]?.[tt]}function cn(e,t){Tp(t);let r=Zi(t);rt.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
13
|
+
`,{mode:ge})}function Us(e,t){let r=Os(e),n=Re(t);if(r==="network")return n.network;if(r==="wallet")return n.wallet??"(not set)";if(r===tt){let s=Ft().flatMap((o)=>{let i=Fs(n,o);return i===void 0?[]:[`${Vi(i)} (${o})`]});return s.length>0?s.join(", "):"(not set)"}if(gr.has(r)){let o=Ms(n,n.network)[r];return typeof o==="string"?o:"(not set)"}throw Error(`Unknown config key: "${e}"
|
|
14
|
+
Valid keys: ${an.join(", ")}`)}function Np(e,t){let r={...e.networks?.[t]??{}},n=!1;for(let s of gr){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 Qi(e,t,r){let n=Os(e),s=Re(r);if(n==="network"){if(!Ne(t))throw Error(`Invalid network: "${t}"
|
|
15
|
+
Valid networks: preprod, preview, undeployed`);Np(s,s.network),s.network=t}else if(n==="wallet"){if(!yt(t))throw Error(`Invalid wallet name: "${t}"
|
|
16
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(n===tt){let{projectId:o,network:i}=rn(t);s.networks={...s.networks??{},[i]:{...s.networks?.[i]??{},[tt]:o}}}else if(gr.has(n)){if(!Ap(t))throw Error(`Invalid URL for "${e}": "${t}"
|
|
17
17
|
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: ${an.join(", ")}`);cn(s,r)}function
|
|
19
|
-
Valid keys: ${an.join(", ")}`);cn(n,t)}function
|
|
20
|
-
`)){if(!r)continue;let[n,s]=r.split("|"),o=(i)=>{let a=new RegExp(`0\\.0\\.0\\.0:(\\d+)->${i}/tcp`),c=s?.match(a);return c?parseInt(c[1],10):void 0};if(n.includes("indexer-standalone")||n.includes("indexer")){let i=o(8088);if(i)t.indexerPort=i}if(n.includes("midnight-node")){let i=o(9944);if(i)t.nodePort=i}if(n.includes("proof-server")){let i=o(6300);if(i)t.proofServerPort=i}}return t}catch{return{}}}function dn(e,t){let r=
|
|
21
|
-
Valid networks: ${
|
|
22
|
-
`,{mode:ge})}catch{}}function
|
|
23
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=be.join(
|
|
24
|
-
Run "midnight wallet list" to see available wallets.`);let r=
|
|
25
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=
|
|
26
|
-
Run "midnight wallet list" to see available wallets.`);let n=
|
|
27
|
-
Switch to another wallet first: midnight wallet use <other-wallet>`);if(
|
|
28
|
-
`+"Create another wallet first: midnight wallet generate <name>");
|
|
29
|
-
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=
|
|
30
|
-
${c.message}`)}let n;try{n=JSON.parse(r)}catch{throw Error(`Invalid JSON in wallet file: ${t}`)}if(!n.seed||!n.createdAt){let c=["seed","createdAt"];if(!n.addresses)c.push("address");let d=c.filter((l)=>!n[l]);if(d.length>0)throw Error(`Wallet file is missing required fields (${d.join(", ")}): ${t}`)}if(!/^[0-9a-fA-F]+$/.test(n.seed))throw Error(`Invalid seed format in wallet file (expected hex string): ${t}`);if(!n.addresses){if(!n.address)throw Error(`Wallet file is missing required fields (address): ${t}`);let c=Buffer.from(n.seed,"hex"),d=
|
|
31
|
-
`,{mode:ge}),l}if(typeof n.addresses!=="object")throw Error(`Wallet file has invalid addresses field: ${t}`);let s={seed:n.seed,addresses:n.addresses,createdAt:n.createdAt};if(n.mnemonic)s.mnemonic=n.mnemonic;let o=Buffer.from(n.seed,"hex"),i=
|
|
32
|
-
`,{mode:ge})}catch{}return s}function
|
|
33
|
-
`,{mode:ge}),r}var
|
|
34
|
-
`);for(let m of p)o.push(...
|
|
35
|
-
`)}function
|
|
36
|
-
`)}var
|
|
37
|
-
Use --force to overwrite, or --output <file> to save to a different path.`);let c,d;if(o!==void 0){let y=o.replace(/^0x/,"");if(y.length!==64||!/^[0-9a-fA-F]+$/.test(y))throw Error("Seed must be a 64-character hex string (32 bytes)");c=Buffer.from(y,"hex")}else if(i!==void 0){if(!
|
|
18
|
+
Valid keys: ${an.join(", ")}`);cn(s,r)}function ea(e,t){let r=Os(e),n=Re(t);if(r==="network")n.network=mr.network;else if(r==="wallet")delete n.wallet;else if(r===tt){for(let s of Ft()){let o=n.networks?.[s];if(!o)continue;if(delete o[tt],Object.keys(o).length===0)delete n.networks[s]}if(n.networks&&Object.keys(n.networks).length===0)delete n.networks}else if(gr.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}"
|
|
19
|
+
Valid keys: ${an.join(", ")}`);cn(n,t)}function Ls(){return an}var tt="blockfrost-project-id",mr,an,xp,gr;var Wt=N(()=>{_e();Ue();mr={network:"undeployed"},an=["network","proof-server","node","indexer-ws","wallet",tt],xp={"network-id":"network"};gr=new Set(["proof-server","node","indexer-ws"])});import{execSync as Rp}from"child_process";function Ne(e){return ta.includes(e)}function Bs(e){return{...Dp[e]}}function hr(){return ta}function Ip(){try{let e=Rp('docker ps --format "{{.Image}}|{{.Ports}}"',{encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]}),t={};for(let r of e.trim().split(`
|
|
20
|
+
`)){if(!r)continue;let[n,s]=r.split("|"),o=(i)=>{let a=new RegExp(`0\\.0\\.0\\.0:(\\d+)->${i}/tcp`),c=s?.match(a);return c?parseInt(c[1],10):void 0};if(n.includes("indexer-standalone")||n.includes("indexer")){let i=o(8088);if(i)t.indexerPort=i}if(n.includes("midnight-node")){let i=o(9944);if(i)t.nodePort=i}if(n.includes("proof-server")){let i=o(6300);if(i)t.proofServerPort=i}}return t}catch{return{}}}function dn(e,t){let r=Bs(e);if(tn(e))Object.assign(r,Rs(e,t));if(e==="undeployed"){let n=Ip();if(n.indexerPort)r.indexer=`http://localhost:${n.indexerPort}${Mt}`,r.indexerWS=`ws://localhost:${n.indexerPort}${qr}`;if(n.nodePort)r.node=`ws://localhost:${n.nodePort}`;if(n.proofServerPort)r.proofServer=`http://localhost:${n.proofServerPort}`}return r}function Le(e,t,r,n){let s=Re(n),o=Ms(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=_p(e.indexerWS);return e}function _p(e){let t=e.indexOf("?"),[r,n]=t===-1?[e,""]:[e.slice(0,t),e.slice(t)];return r.replace(/^wss:/,"https:").replace(/^ws:/,"http:").replace(/\/ws$/,"")+n}var Dp,ta;var Ue=N(()=>{_e();Wt();Dp={preprod:{...Rs("preprod",void 0),proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:`https://indexer.preview.midnight.network${Mt}`,indexerWS:`wss://indexer.preview.midnight.network${qr}`,node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:`http://localhost:8088${Mt}`,indexerWS:`ws://localhost:8088${qr}`,node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},ta=["preprod","preview","undeployed"]});import{HDWallet as Pp,Roles as Ws}from"@midnight-ntwrk/wallet-sdk-hd";function js(e,t){let r=Pp.fromSeed(e);if(r.type!=="seedOk")throw Error("Invalid seed for HD wallet");let n=r.hdWallet.selectAccount(0).selectRole(t).deriveKeyAt(0);if(n.type==="keyOutOfBounds")throw Error("Key derivation out of bounds");return n.key}function St(e){return js(e,Ws.Zswap)}function ra(e){return js(e,Ws.NightExternal)}function dt(e){return js(e,Ws.Dust)}var bt=()=>{};import{HDWallet as $p,Roles as Op}from"@midnight-ntwrk/wallet-sdk-hd";import{createKeystore as Mp,PublicKey as Fp}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{MidnightBech32m as Up,ShieldedAddress as Lp,ShieldedCoinPublicKey as Bp,ShieldedEncryptionPublicKey as Wp}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as Hs}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as na from"@midnight-ntwrk/ledger-v8";function Se(e,t,r=0){let n=sa[t],s=$p.fromSeed(e);if(s.type!=="seedOk")throw Error("Invalid seed for HD wallet");let o=s.hdWallet.selectAccount(0).selectRole(Op.NightExternal).deriveKeyAt(r);if(o.type==="keyOutOfBounds")throw Error(`Key index ${r} out of bounds`);let i=Mp(o.key,n);return Fp.fromKeyStore(i).address}function vt(e,t=0){let r={};for(let n of hr())r[n]=Se(e,n,t);return r}function wr(e){let t=yr(e),r={};for(let n of hr()){let s=sa[n];r[n]=Up.encode(s,t).asString()}return r}function yr(e){let t=St(e),r=na.ZswapSecretKeys.fromSeed(t);return new Lp(new Bp(Buffer.from(r.coinPublicKey,"hex")),new Wp(Buffer.from(r.encryptionPublicKey,"hex")))}var sa;var je=N(()=>{Ue();bt();sa={preprod:Hs.NetworkId.PreProd,preview:Hs.NetworkId.Preview,undeployed:Hs.NetworkId.Undeployed}});function Pe(e){let t=k(e.args,"network");if(t!==void 0){if(!Ne(t))throw Error(`Invalid network: "${t}"
|
|
21
|
+
Valid networks: ${hr().join(", ")}`);return t}let r=Re(e.configDir);if(r.network&&Ne(r.network))return r.network;return"undeployed"}function Ks(e,t,r=process.env){if(!tn(e))return;let n=r[jp]?.trim();if(n){let{projectId:o,network:i}=rn(n);if(i===e)return o}let s=r[Hp]?.trim();if(s&&/^[A-Za-z0-9]+$/.test(s)&&Ut(s)===e)return s;return Fs(Re(t),e)}function Q(e){let t=Pe(e),r=dn(t,Ks(t,e.configDir));return Le(r,{proofServer:k(e.args,"proof-server"),node:k(e.args,"node"),indexerWS:k(e.args,"indexer-ws")},t,e.configDir),{name:t,config:r}}var jp="MN_BLOCKFROST_PROJECT_ID",Hp="BLOCKFROST_PROJECT_ID";var pe=N(()=>{Ue();_e();Wt()});import*as te from"fs";import*as be from"path";import{homedir as Kp}from"os";function jt(e,t,r){let n=be.resolve(e);if(!te.existsSync(n))return;try{let s=JSON.parse(te.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;te.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
22
|
+
`,{mode:ge})}catch{}}function Gs(){return be.join(Kp(),ie)}function Sr(){return be.join(Gs(),Zr)}function ia(){return be.join(Gs(),Xr)}function Gp(){let e=Gs();if(!te.existsSync(e))te.mkdirSync(e,{recursive:!0,mode:me})}function Jp(e){return e.includes("/")||e.includes("\\")||e.endsWith(".json")}function ae(e){if(e!==void 0){if(Jp(e))return be.resolve(e);return be.join(Sr(),`${e}.json`)}let r=Re().wallet??Es;return be.join(Sr(),`${r}.json`)}function Ht(){return Re().wallet??Es}function Js(e){if(!yt(e))throw Error(`Invalid wallet name: "${e}"
|
|
23
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=be.join(Sr(),`${e}.json`);if(!te.existsSync(t))throw Error(`Wallet "${e}" not found.
|
|
24
|
+
Run "midnight wallet list" to see available wallets.`);let r=Re();r.wallet=e,cn(r)}function Vs(){let e=Sr();if(!te.existsSync(e))return[];let t=Ht();return te.readdirSync(e).filter((n)=>n.endsWith(".json")).sort().map((n)=>{let s=n.replace(/\.json$/,""),o=be.join(e,n);try{let i=JSON.parse(te.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=vt(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=wr(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 Vp(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 aa(e){return Vp(Vs(),e)}function ca(e){if(!yt(e))throw Error(`Invalid wallet name: "${e}"
|
|
25
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=Sr(),r=be.join(t,`${e}.json`);if(!te.existsSync(r))throw Error(`Wallet "${e}" not found.
|
|
26
|
+
Run "midnight wallet list" to see available wallets.`);let n=Ht();if(e===n)throw Error(`Cannot remove the active wallet "${e}".
|
|
27
|
+
Switch to another wallet first: midnight wallet use <other-wallet>`);if(te.readdirSync(t).filter((o)=>o.endsWith(".json")).length<=1)throw Error(`Cannot remove "${e}" — it is the only wallet.
|
|
28
|
+
`+"Create another wallet first: midnight wallet generate <name>");te.unlinkSync(r)}function ce(e){let t=e?be.resolve(e):ia();if(!te.existsSync(t))throw Error(`Wallet file not found: ${t}
|
|
29
|
+
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=te.readFileSync(t,"utf-8")}catch(c){throw Error(`Failed to read wallet file: ${t}
|
|
30
|
+
${c.message}`)}let n;try{n=JSON.parse(r)}catch{throw Error(`Invalid JSON in wallet file: ${t}`)}if(!n.seed||!n.createdAt){let c=["seed","createdAt"];if(!n.addresses)c.push("address");let d=c.filter((l)=>!n[l]);if(d.length>0)throw Error(`Wallet file is missing required fields (${d.join(", ")}): ${t}`)}if(!/^[0-9a-fA-F]+$/.test(n.seed))throw Error(`Invalid seed format in wallet file (expected hex string): ${t}`);if(!n.addresses){if(!n.address)throw Error(`Wallet file is missing required fields (address): ${t}`);let c=Buffer.from(n.seed,"hex"),d=vt(c),l={seed:n.seed,addresses:d,createdAt:n.createdAt};if(n.mnemonic)l.mnemonic=n.mnemonic;let u=oa(n,c);if(u)l.shieldedAddresses=u;let p={...n,addresses:d};if(u)p.shieldedAddresses=u,delete p.shieldedAddress;return te.writeFileSync(t,JSON.stringify(p,null,2)+`
|
|
31
|
+
`,{mode:ge}),l}if(typeof n.addresses!=="object")throw Error(`Wallet file has invalid addresses field: ${t}`);let s={seed:n.seed,addresses:n.addresses,createdAt:n.createdAt};if(n.mnemonic)s.mnemonic=n.mnemonic;let o=Buffer.from(n.seed,"hex"),i=oa(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,te.writeFileSync(t,JSON.stringify(c,null,2)+`
|
|
32
|
+
`,{mode:ge})}catch{}return s}function oa(e,t){let r;try{r=wr(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 ln(e,t){let r=t?be.resolve(t):ia();if(!t)Gp();else{let n=be.dirname(r);if(!te.existsSync(n))te.mkdirSync(n,{recursive:!0,mode:me})}return te.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
33
|
+
`,{mode:ge}),r}var $e=N(()=>{Wt();je()});function br(){return!("NO_COLOR"in process.env)}function vr(e,t){if(!br())return e;return`\x1B[38;5;${t}m${e}\x1B[0m`}function _(e){if(!br())return e;return`\x1B[1m${e}\x1B[0m`}function g(e){if(!br())return e;return`\x1B[2m${e}\x1B[0m`}function G(e){return vr(e,38)}function le(e){return vr(e,196)}function B(e){return vr(e,40)}function ee(e){return vr(e,226)}function kr(e){return vr(e,245)}function U(e,t=la){let r=` ${e} `,n=t-r.length;if(n<=0)return _(r);let s=Math.floor(n/2),o=n-s;return _("═".repeat(s)+r+"═".repeat(o))}function V(e=la){return g("─".repeat(e))}function C(e,t,r=16){let n=(e+":").padEnd(r);return` ${kr(n)}${t}`}function kt(e){let t=e<0n,r=t?-e:e,n=BigInt(10**ws),s=r/n,i=(r%n).toString().padStart(ws,"0");return`${t?"-":""}${s}.${i}`}function un(e){return`${kt(e)} NIGHT`}function Gt(e){let t=e<0n,r=t?-e:e,n=10n**BigInt(da),s=r/n,a=(r%n).toString().padStart(da,"0").replace(/0+$/,"").padEnd(6,"0");return`${t?"-":""}${s}.${a}`}function Cr(e){return`${Gt(e)} DUST`}function re(e,t=!1){let r=t&&e.length>20?e.slice(0,10)+"…"+e.slice(-8):e;return G(r)}function zp(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 qp(e,t){if(Kt(e).length<=t)return[e];let n=e.split(/(\s+)/).flatMap((a)=>Kt(a).length>t?zp(a,t):[a]),s=[],o="",i=0;for(let a of n){let c=Kt(a).length;if(i+c>t&&i>0)s.push(o),o=a.trimStart(),i=Kt(o).length;else o+=a,i+=c}if(o.length>0)s.push(o);return s}function ua(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 p=u.split(`
|
|
34
|
+
`);for(let m of p)o.push(...qp(m,s))}let i=Math.max(...o.map((u)=>Kt(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,l=o.map((u)=>{let p=Kt(u).length,m=a-p-2;return`${n.v} ${u}${" ".repeat(Math.max(0,m))} ${n.v}`});return[c,...l,d].join(`
|
|
35
|
+
`)}function lt(e,t){let n=[`${B("✓")} ${e}`];if(t)n.push(C("Transaction",G(t)));return n.join(`
|
|
36
|
+
`)}var la=60,da=15,Kt=(e)=>e.replace(/\x1b\[[0-9;]*m/g,"");var he=()=>{};var ha={};fe(ha,{default:()=>ga});import*as ma from"fs";import*as pn from"path";import{homedir as Yp}from"os";import{generateMnemonic as Xp,mnemonicToSeedSync as pa,validateMnemonic as Zp}from"@scure/bip39";import{wordlist as fa}from"@scure/bip39/wordlists/english.js";async function ga(e){let t=Pe({args:e}),r=k(e,"output"),n=k(e,"seed"),s=process.env.MN_SEED?.trim(),o=n??(s?s:void 0),i=k(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?pn.resolve(r):pn.join(Yp(),ie,Xr);if(ma.existsSync(a)&&!D(e,"force"))throw Error(`Wallet file already exists: ${a}
|
|
37
|
+
Use --force to overwrite, or --output <file> to save to a different path.`);let c,d;if(o!==void 0){let y=o.replace(/^0x/,"");if(y.length!==64||!/^[0-9a-fA-F]+$/.test(y))throw Error("Seed must be a 64-character hex string (32 bytes)");c=Buffer.from(y,"hex")}else if(i!==void 0){if(!Zp(i,fa))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");d=i,c=Buffer.from(pa(d))}else d=Xp(fa,256),c=Buffer.from(pa(d));let l=vt(c),u=l[t],p={seed:c.toString("hex"),addresses:l,createdAt:new Date().toISOString()};if(d)p.mnemonic=d;let m=ln(p,r);if(D(e,"json")){let y={addresses:l,activeAddress:u,activeNetwork:t,seed:c.toString("hex"),file:m,createdAt:p.createdAt};if(d)y.mnemonic=d;I(y);return}if(process.stdout.write(u+`
|
|
38
38
|
`),process.stderr.write(`
|
|
39
|
-
`+
|
|
39
|
+
`+U("Wallet Generated")+`
|
|
40
40
|
|
|
41
41
|
`),process.stderr.write(C("Network",t)+`
|
|
42
|
-
`),process.stderr.write(C("Address",
|
|
42
|
+
`),process.stderr.write(C("Address",re(u))+`
|
|
43
43
|
`),process.stderr.write(C("File",m)+`
|
|
44
44
|
`),process.stderr.write(`
|
|
45
45
|
`),d)process.stderr.write(ee(_(" MNEMONIC (save securely!):"))+`
|
|
@@ -51,14 +51,14 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
51
51
|
`),process.stderr.write(V()+`
|
|
52
52
|
`),process.stderr.write(g(" Next: midnight info | midnight balance")+`
|
|
53
53
|
|
|
54
|
-
`),process.stderr.write(
|
|
55
|
-
`)}var
|
|
54
|
+
`),process.stderr.write(B("✓")+` Wallet saved
|
|
55
|
+
`)}var wa=N(()=>{je();pe();$e();he()});var Sa={};fe(Sa,{default:()=>ya});async function ya(e){let t=ae(k(e,"wallet")),r=ce(t),n=Pe({args:e}),s=r.addresses[n];if(D(e,"json")){let i={addresses:r.addresses,activeNetwork:n,activeAddress:s,createdAt:r.createdAt,file:t};if(r.shieldedAddresses)i.shieldedAddresses=r.shieldedAddresses;I(i);return}process.stdout.write(s+`
|
|
56
56
|
`),process.stderr.write(`
|
|
57
|
-
`+
|
|
57
|
+
`+U("Wallet Info")+`
|
|
58
58
|
|
|
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],l=r.shieldedAddresses?.[a],u=c?_(
|
|
60
|
-
`),process.stderr.write(` ${g("unshielded")} ${
|
|
61
|
-
`),l)process.stderr.write(` ${g("shielded ")} ${
|
|
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],l=r.shieldedAddresses?.[a],u=c?_(G(a))+g(" (active)"):a;if(process.stderr.write(` ${u}
|
|
60
|
+
`),process.stderr.write(` ${g("unshielded")} ${re(d)}
|
|
61
|
+
`),l)process.stderr.write(` ${g("shielded ")} ${re(l)}
|
|
62
62
|
`);else process.stderr.write(` ${g("shielded ")} ${g("(unavailable)")}
|
|
63
63
|
`);if(i<o.length-1)process.stderr.write(`
|
|
64
64
|
`)}process.stderr.write(`
|
|
@@ -67,11 +67,18 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
67
67
|
`),process.stderr.write(` ${g("created")} ${r.createdAt}
|
|
68
68
|
`),process.stderr.write(` ${g("file ")} ${t}
|
|
69
69
|
|
|
70
|
-
`)}var
|
|
71
|
-
`)}
|
|
70
|
+
`)}var ba=N(()=>{$e();pe();he();he()});function Ca(){return nt}function ka(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function z(e){let t=!1;if(!br()){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,nt=null,process.stderr.write(`\r✓ ${d??a}\x1B[K
|
|
71
|
+
`)},fail(d){if(t)return;t=!0,nt=null,process.stderr.write(`\r✗ ${d??a}\x1B[K
|
|
72
|
+
`)},log(d){process.stderr.write(`\r\x1B[K${d}
|
|
73
|
+
`),process.stderr.write(`⠋ ${a}`)},clear(){if(t)return;t=!0,nt=null,process.stderr.write("\r\x1B[K")}};return nt=c,c}let r=0,n=e,s=()=>{let a=G(va[r]),d=(process.stderr.columns||80)-4,l=n;if(ka(l).length>d)l=ka(l).slice(0,d);process.stderr.write(`\r${a} ${l}\x1B[K`),r=(r+1)%va.length};s();let o=setInterval(s,Qp),i={update(a){n=a},stop(a){if(t)return;t=!0,clearInterval(o),nt=null;let c=a??n;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${c}\x1B[K
|
|
74
|
+
`)},fail(a){if(t)return;t=!0,clearInterval(o),nt=null;let c=a??n;process.stderr.write(`\r\x1B[31m✗\x1B[0m ${c}\x1B[K
|
|
75
|
+
`)},log(a){process.stderr.write(`\r\x1B[K${a}
|
|
76
|
+
`),s()},clear(){if(t)return;t=!0,clearInterval(o),nt=null,process.stderr.write("\r\x1B[K")}};return nt=i,i}async function fn(e,t,r){let n=Date.now(),s=(a)=>{let c=Math.floor(a/1000),d=Math.floor(c/60).toString().padStart(2,"0"),l=(c%60).toString().padStart(2,"0");return`${d}:${l}`},o=()=>e.update(`${t} ${s(Date.now()-n)}`);o();let i=setInterval(o,1000);try{return await r}finally{clearInterval(i)}}var va,Qp=80,nt=null;var qe=N(()=>{va=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});function He(){xa=!0}function F(e,t){if(!xa)return;let r=new Date().toISOString().slice(11,23);process.stderr.write(g(` [${r}] ${e}: ${t}`)+`
|
|
77
|
+
`)}function Aa(e){if(Ea.has(e))return;Ea.add(e);let t=` ${e}`,r=Ca();if(r)r.log(t);else process.stderr.write(t+`
|
|
78
|
+
`)}var xa=!1,Ea;var ut=N(()=>{qe();Ea=new Set});function zs(e,t={}){let r=k(e,"seed"),n=r??process.env.MN_SEED;if(n){let a=n.trim().replace(/^0x/,"");if(a.length!==64||!/^[0-9a-fA-F]+$/.test(a))throw new W(`${r?"--seed":"MN_SEED"} must be a 64-character hex string (32 bytes)`);return{seed:Buffer.from(a,"hex"),walletPath:null,config:null}}let s=k(e,"wallet");if(s===void 0&&t.requireExplicit)throw new W(`${t.label??"This command"} needs a seed source. Provide one of:
|
|
72
79
|
--seed <hex> 32-byte seed as 64 hex characters
|
|
73
80
|
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
74
|
-
--wallet <name> derive from a saved wallet`);let o=
|
|
81
|
+
--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 mn(e,t){return zs(e,t).seed}var gn=N(()=>{Fe();$e()});function tf(e){return!ef.includes(e)}function hn(e,t=!1){return tf(e)||t}function wn(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var ef;var qs=N(()=>{ef=["preview","preprod"]});import{NetworkId as Ys}from"@midnight-ntwrk/wallet-sdk-abstractions";function Ct(e){let t=rf[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}var rf;var yn=N(()=>{rf={PreProd:Ys.NetworkId.PreProd,Preview:Ys.NetworkId.Preview,Undeployed:Ys.NetworkId.Undeployed}});import nf from"ws";function Jt(e,t,r){return new Promise((n,s)=>{ye(t);let o=new nf(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,l=!1,u=!1,p,m=()=>{let h=new Map,w=0,b=0,S=0;for(let v of i.values())if(!v.spent){w++;let R=h.get(v.tokenType)??0n;if(h.set(v.tokenType,R+v.value),v.tokenType===cr)if(v.registeredForDustGeneration)b++;else S++}return{balances:h,utxoCount:w,txCount:a,highestTxId:c,registeredUtxos:b,unregisteredUtxos:S}},y=()=>{clearTimeout(p)},f=()=>{if(!u&&l&&(c===0||d>=c))u=!0,y(),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",(h)=>{let w=JSON.parse(h.toString());switch(w.type){case"connection_ack":o.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:sf,variables:{address:e}}}));break;case"next":{if(w.payload?.errors){let S=w.payload.errors[0]?.message||"Unknown GraphQL error";if(!u)u=!0,y(),o.close(),s(Error(`GraphQL error: ${S}`));return}let b=w.payload?.data?.unshieldedTransactions;if(!b)return;if(b.__typename==="UnshieldedTransaction"){a++;let S=b;d=Math.max(d,S.transaction.id);for(let v of S.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 S.spentUtxos){let R=`${v.intentHash}:${v.outputIndex}`,P=i.get(R);if(P)P.spent=!0}if(r)r(d,c);f()}else if(b.__typename==="UnshieldedTransactionsProgress")c=b.highestTransactionId,l=!0,f();break}case"error":if(!u)u=!0,y(),o.close(),s(Error(`GraphQL subscription error: ${JSON.stringify(w.payload)}`));break;case"complete":break}}),o.on("error",(h)=>{if(!u){u=!0,y();let w=h.message?.trim()?h.message:`unable to reach ${t} (connection refused, DNS, or TLS error). Is the indexer running?`;s(Bt(t,h)??Error(`WebSocket connection failed: ${w}`))}}),o.on("close",()=>{if(!u)u=!0,y(),s(Error(`Indexer closed the connection before balance sync completed. Indexer: ${t}`))}),p=setTimeout(()=>{if(!u)u=!0,o.close(),s(Error(`Balance check timed out after ${vs/1000}s. Indexer: ${t}`))},vs)})}function Er(e){return e===cr}var sf=`
|
|
75
82
|
subscription UnshieldedTransactions($address: UnshieldedAddress!) {
|
|
76
83
|
unshieldedTransactions(address: $address) {
|
|
77
84
|
__typename
|
|
@@ -85,10 +92,10 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
85
92
|
}
|
|
86
93
|
}
|
|
87
94
|
}
|
|
88
|
-
`;var
|
|
89
|
-
`),y=await u()}}else F("facade","No cache, building fresh"),y=await u();return{facade:y,keystore:d,zswapSecretKeys:a,dustSecretKey:c,restoredFromCache:m}}function
|
|
95
|
+
`;var xr=N(()=>{_e()});function Ta(e,t,r){let n;for(let s of e)if(s.value>=t&&(n===void 0||s.value<n.value))n=s;return n===void 0?r(t):[n]}function Na({owed:e,coinCount:t,choose:r,feeWith:n}){let s=e;for(let o=0;o<=t*2;o++){let i=s>0n?r(s):[];if(i===void 0)return{kind:"short",atFirstChoice:o===0};let a=n(i),c=i.reduce((d,l)=>d+l.value,0n);if(a<=c)return{kind:"covered",fee:a,inputs:i};s=a}return{kind:"short",atFirstChoice:!1}}function Ra(e,t){let r=t;return e.map((n)=>{let s=r>=n.value?n.value:r;return r-=s,{...n,value:s}})}import{Imbalances as of,InsufficientFundsError as Da,getBalanceRecipe as af}from"@midnight-ntwrk/wallet-sdk-capabilities";import{CustomDustWallet as cf}from"@midnight-ntwrk/wallet-sdk-dust-wallet";import{Transacting as Ia,V1Builder as df}from"@midnight-ntwrk/wallet-sdk-dust-wallet/v1";import{LedgerOps as Xs}from"@midnight-ntwrk/wallet-sdk-utilities";function Zs(e){return cf(e,new df().withDefaults().withTransacting(lf))}var _a,lf=(e,t)=>new _a(e.networkId,e.costParameters,()=>t().coinSelection,()=>t().coinsAndBalancesCapability,()=>t().keysCapability);var Pa=N(()=>{_a=class _a extends Ia.TransactingCapabilityImplementation{computeBalancingRecipe(...e){let[t,r,n,s,o,i]=e,a;try{let c=-n.reduce((l,u)=>l+Ia.TransactingCapabilityImplementation.feeImbalance(u,this.calculateFee(u,i)),0n),d=this.getCoins().getAvailableCoinsWithGeneratedDust(r,o);a=Na({owed:c,coinCount:d.length,choose:(l)=>Ta(d,l,(u)=>this.#e(d,u)),feeWith:(l)=>this.dryRunFee(l,n,t,r,s,o,i)})}catch(c){return Xs.ledgerTry(()=>{throw c})}if(a.kind==="covered"){let{fee:c,inputs:d}=a;return Xs.ledgerTry(()=>({fee:c,recipeInputs:Ra(d,c)}))}if(a.atFirstChoice)return super.computeBalancingRecipe(...e);return Xs.ledgerTry(()=>{throw new Da("dust")})}#e(e,t){try{return af({coins:e.map((n)=>({type:"dust",value:n.value,token:n.token})),initialImbalances:of.fromEntry("dust",-t),feeTokenType:"dust",transactionCostModel:{inputFeeOverhead:0n,outputFeeOverhead:0n},createOutput:(n)=>n,isCoinEqual:(n,s)=>n.type===s.type&&n.value===s.value}).inputs.map((n)=>({token:n.token,value:n.value}))}catch(r){if(r instanceof Da)return;throw r}}}});import{existsSync as Ar,mkdirSync as uf,writeFileSync as pf,readFileSync as $a,unlinkSync as Sn,readdirSync as Qs,renameSync as ff}from"node:fs";import{join as Et,dirname as mf}from"node:path";import{homedir as Oa}from"node:os";import{randomBytes as gf}from"node:crypto";import*as bn from"@midnight-ntwrk/ledger-v8";function eo(e){return e.toString(16).padStart(64,"0")}function Ke(e){let t=dt(e),r=bn.DustSecretKey.fromSeed(t);return eo(r.publicKey)}function to(e,t){let r=t??Et(Oa(),ie,Ce);return Et(r,e)}function ro(e,t,r){let n=t.slice(0,20);return Et(to(e,r),`dust-${n}.json`)}function Vt(e,t,r){let n=ro(e,t,r);if(!Ar(n))return null;try{let s=JSON.parse($a(n,"utf-8"));if(s.version!==Ma)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:bn.DustLocalState.deserialize(o),lastAppliedEventId:s.lastAppliedEventId,retention:{ownedGenerationIndices:s.ownedGenerationIndices,generationFrontier:s.generationFrontier}}}catch{return null}}function no(e,t,r,n,s,o,i=hf){let a={version:Ma,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=ro(e,t,s),d=mf(c);if(!Ar(d))uf(d,{recursive:!0,mode:me});let l=c+`.tmp.${gf(4).toString("hex")}`;try{pf(l,JSON.stringify(a),{mode:ge}),ff(l,c)}catch(u){try{Sn(l)}catch{}throw u}}function Fa(e,t,r){if(!t)return[];let n=to(e,r);if(!Ar(n))return[];let s=[],o;try{o=Qs(n)}catch{return[]}for(let i of o){if(!i.startsWith("dust-")||!i.endsWith(".json"))continue;let a=Et(n,i);try{let c=JSON.parse($a(a,"utf-8"));if(!c.chainId)continue;if(c.chainId!==t)Sn(a),s.push(a)}catch{}}return s}function pt(e,t,r){let n=r??Et(Oa(),ie,Ce);if(e&&t){let o=ro(e,t,r);try{Sn(o)}catch{}return}let s=(o)=>{if(!Ar(o))return;try{for(let i of Qs(o))if(i.startsWith("dust-")&&i.endsWith(".json"))try{Sn(Et(o,i))}catch{}}catch{}};if(e){s(to(e,r));return}if(!Ar(n))return;try{for(let o of Qs(n))s(Et(n,o))}catch{}}var Ma=2,hf;var xt=N(()=>{bt();hf={ownedGenerationIndices:[],generationFrontier:0}});async function Ua(e,t=fetch){for(let s of[e.indexer,e.indexerWS,e.node])ye(s);if(!Ds(e.indexer))return;let r;try{r=(await t(e.indexer,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:"{ __typename }"}),signal:AbortSignal.timeout(wf)})).status}catch{return}let n=fr(e.indexer,r);if(n!==void 0)throw n}var wf=1e4;var La=N(()=>{_e()});import{ShieldedWallet as Ba}from"@midnight-ntwrk/wallet-sdk-shielded";import{UnshieldedWallet as Wa,createKeystore as yf,PublicKey as Sf}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{WalletFacade as ja}from"@midnight-ntwrk/wallet-sdk-facade";import*as zt from"@midnight-ntwrk/ledger-v8";import{NetworkId as so,InMemoryTransactionHistoryStorage as bf,TransactionHistoryStorage as vf}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as Ee from"rxjs";async function Ge(e,t,r){let n=kf[t.networkId];if(n===void 0)throw Error(`Unknown networkId: ${t.networkId}`);await Ua(t),F("facade",`Building facade for network ${t.networkId}`),F("facade",`Node: ${t.node}`),F("facade",`Indexer: ${t.indexerWS}`),F("facade",`Proof server: ${t.proofServer}`);let s=St(e),o=ra(e),i=dt(e),a=zt.ZswapSecretKeys.fromSeed(s),c=zt.DustSecretKey.fromSeed(i),d=yf(o,n),l={networkId:n,indexerClientConnection:{indexerHttpUrl:t.indexer,indexerWsUrl:t.indexerWS},costParameters:{additionalFeeOverhead:xi,feeBlocksMargin:Ai},txHistoryStorage:new bf(vf.TransactionHistoryCommonSchema),provingServerUrl:new URL(t.proofServer),relayURL:new URL(t.node)},u=()=>ja.init({configuration:l,shielded:(f)=>Ba(f).startWithSecretKeys(a),unshielded:(f)=>Wa(f).startWithPublicKey(Sf.fromKeyStore(d)),dust:(f)=>Zs(f).startWithSecretKey(c,zt.LedgerParameters.initialParameters().dust)}),p=r?Cf(r,t,c.publicKey):null,m=!1,y;if(p){F("facade","Restoring from cache...");try{y=await ja.init({configuration:l,shielded:(f)=>Ba(f).restore(p.shielded),unshielded:(f)=>Wa(f).restore(p.unshielded),dust:(f)=>Zs(f).restore(p.dust)}),m=!0,F("facade","Cache restore successful")}catch(f){F("facade",`Cache restore failed: ${f.message}`),process.stderr.write(` Cache restore failed, building from scratch: ${f.message}
|
|
96
|
+
`),y=await u()}}else F("facade","No cache, building fresh"),y=await u();return{facade:y,keystore:d,zswapSecretKeys:a,dustSecretKey:c,restoredFromCache:m}}function Nr(e,t){let r=JSON.parse(e);return r.state=Buffer.from(t.state.serialize()).toString("hex"),r.offset=t.lastAppliedEventId.toString(),JSON.stringify(r)}function Cf(e,t,r){try{let n=t.networkId.toLowerCase(),s=eo(r),o=Vt(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 F("facade",`Facade dust offset=${a} >= dust-direct offset=${o.lastAppliedEventId}; skipping bridge`),e;return F("facade",`Bridged dust-direct cache (facade offset ${a} → dust-direct offset ${o.lastAppliedEventId})`),{...e,dust:Nr(e.dust,o)}}catch(n){return F("facade",`Dust-direct bridge skipped: ${n.message}`),e}}function Tr(e,t="full"){let r=e.unshielded?.progress?.isStrictlyComplete()??!1,n=t!=="no-dust",s=!n;if(n){if(s=e.dust?.state?.progress?.isStrictlyComplete()??!1,!s)try{let i=e.dust?.state?.progress;if(i&&i.highestRelevantWalletIndex>0&&i.appliedIndex>=i.highestRelevantWalletIndex)s=!0;if(i&&i.highestRelevantWalletIndex===0&&i.appliedIndex===0&&r)s=!0}catch{}}if(t==="lite")return r&&s;let o=e.shielded?.state?.progress?.isStrictlyComplete()??!1;if(!o&&r)try{let i=e.shielded?.state?.progress;if(i&&i.highestRelevantWalletIndex===0&&i.appliedIndex===0)o=!0}catch{}return o&&r&&s}function Ef(e){if(e.dust?.state?.progress?.isStrictlyComplete())return!1;try{let t=e.dust?.state?.progress;if(t&&t.highestRelevantWalletIndex>0&&t.appliedIndex>=t.highestRelevantWalletIndex)return!1;if(t&&t.highestRelevantWalletIndex===0&&t.appliedIndex===0&&e.unshielded?.progress?.isStrictlyComplete())return!1}catch{}return!0}async function ft(e,t={}){let{onProgress:r,onSyncDetail:n,timeoutMs:s,syncMode:o="full",requireStrictSync:i=!1}=t,{facade:a,zswapSecretKeys:c,dustSecretKey:d}=e;F("sync","Starting facade (connecting to node and indexer)..."),await a.start(c,d),F("sync","Facade started, subscribing to state...");let l=s??Di;F("sync",`Sync timeout: ${l/1000}s, mode: ${o}`);let u=!i&&e.restoredFromCache,p=Date.now();return new Promise((m,y)=>{let f=!1,h=0,w="",b=null,S=setTimeout(()=>{if(!f){if(F("sync",`Sync timed out after ${l/1000}s (${h} emissions)`),b)try{let v=b.unshielded?.progress;F("sync",` unshielded: applied=${v?.appliedId} highest=${v?.highestTransactionId} complete=${v?.isStrictlyComplete()}`);let R=b.dust?.state?.progress;if(F("sync",` dust: applied=${R?.appliedIndex} highest=${R?.highestRelevantWalletIndex} complete=${R?.isStrictlyComplete?.()} connected=${R?.isConnected}`),o==="full"){let P=b.shielded?.state?.progress;F("sync",` shielded: complete=${P?.isStrictlyComplete()}`)}}catch{}y(Error("Wallet sync timed out"))}},l);e.keepAlive=a.state().subscribe({next:(v)=>{if(f)return;if(h++,b=v,e.restoredFromCache){let P=Af(v);if(P){f=!0,clearTimeout(S),F("sync",`Stale cache detected: ${P}`),y(new vn(P));return}}if(r){let P=v.unshielded.progress;if(P){let Y=Number(P.appliedId),J=Number(P.highestTransactionId);r(Math.min(Y,J),J)}}let R=[];try{if((o==="full"||o==="no-dust")&&!v.shielded?.state?.progress?.isStrictlyComplete())R.push("shielded");if(o!=="no-dust"&&Ef(v))R.push("dust");if(!v.unshielded?.progress?.isStrictlyComplete())R.push("unshielded")}catch{}if(R.length>0){n?.(R.join(", "));let P=R.join(",");if(h===1||P!==w||h%100===0)F("sync",`Waiting on: ${R.join(", ")} (emission #${h})`),w=P}if(Tr(v,o)){f=!0,clearTimeout(S),F("sync",`Sync complete after ${h} emissions`),m(v);return}if(u){let P=Date.now()-p;if(P>=xf&&Tr(v,"no-dust"))f=!0,clearTimeout(S),F("sync",`Sync resolved via cached-restore grace (${P}ms, ${h} emissions)`),m(v)}},error:(v)=>{if(!f)F("sync",`Sync error: ${v.message}`),clearTimeout(S),y(v)}})})}function Af(e){try{let t=e.unshielded?.progress;if(!t)return;let r=Number(t.appliedId??0),n=Number(t.highestTransactionId??0);if(n>0&&r>n)return`unshielded cache applied=${r} but chain highest=${n}.`}catch{}return}async function Ha(e){let t=(r)=>{let n=r.unshielded?.progress?.isStrictlyComplete()??!1,s=r.dust?.state?.progress?.isStrictlyComplete()??!1;return n&&s};try{return await Ee.firstValueFrom(e.facade.state().pipe(Ee.filter(t),Ee.timeout(15000)))}catch{return await Ee.firstValueFrom(e.facade.state())}}async function kn(e,t=60000){let r=(n)=>{try{let s=n.dust;return s?.availableCoins?.length>0||s?.balance(new Date)>0n}catch{return!1}};try{return await Ee.firstValueFrom(e.facade.state().pipe(Ee.filter(r),Ee.timeout(t)))}catch{return await Ee.firstValueFrom(e.facade.state())}}async function Ka(e){return(await Ee.firstValueFrom(e.facade.state())).dust.balance(new Date)}async function oo(e,t="full"){return Ee.firstValueFrom(e.facade.state().pipe(Ee.filter((r)=>Tr(r,t)),Ee.timeout(Ii)))}async function Oe(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 kf,xf=1e4,vn;var Ye=N(()=>{Pa();bt();xt();ut();La();kf={PreProd:so.NetworkId.PreProd,Preview:so.NetworkId.Preview,Undeployed:so.NetworkId.Undeployed};vn=class vn extends Error{code="STALE_CACHE";constructor(e){super(`Cached wallet state is stale (from a previous chain). ${e}
|
|
90
97
|
Run: midnight cache clear --wallet <name> --network <name>
|
|
91
|
-
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function
|
|
98
|
+
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function Tf(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 Cn(e){let t=e?.message?.toLowerCase()??"";return t.includes("not enough dust")||t.includes("dust generated")||t.includes("insufficient funds")||t.includes("no dust tokens")||Tf(e)}function Rr(e){let t=e?.message?.toLowerCase()??"";if(e?._tag==="Wallet.InsufficientFunds")return!0;return t==="insufficient funds"||t.startsWith("insufficient funds")}import{existsSync as Ir,mkdirSync as Nf,writeFileSync as Rf,readFileSync as Ga,unlinkSync as Dr,readdirSync as En,renameSync as Df}from"node:fs";import{join as Xe,dirname as If}from"node:path";import{homedir as io}from"node:os";import{randomBytes as _f}from"node:crypto";function ao(e,t,r){let n=r??Xe(io(),ie,Ce),s=e.slice(0,20);return Xe(n,t,`${s}.json`)}function mt(e,t,r){let n=ao(e,t,r);if(!Ir(n))return null;try{let s=Ga(n,"utf-8"),o=JSON.parse(s);if(o.version!==Cs)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 gt(e,t,r,n,s){let[o,i,a]=await Promise.all([r.shielded.serializeState(),r.unshielded.serializeState(),r.dust.serializeState()]),c={version:Cs,network:t,address:e,timestamp:new Date().toISOString(),wallets:{shielded:o,unshielded:i,dust:a},...s?{chainId:s}:{}},d=ao(e,t,n),l=If(d);if(!Ir(l))Nf(l,{recursive:!0,mode:me});let u=d+`.tmp.${_f(4).toString("hex")}`;try{Rf(u,JSON.stringify(c),{mode:ge}),Df(u,d)}catch(p){try{Dr(u)}catch{}throw p}}function Ja(e,t,r){if(!t)return[];let n=r??Xe(io(),ie,Ce),s=Xe(n,e);if(!Ir(s))return[];let o=[],i;try{i=En(s)}catch{return[]}for(let a of i){if(!a.endsWith(".json"))continue;let c=Xe(s,a);try{let d=JSON.parse(Ga(c,"utf-8"));if(!d.chainId)continue;if(d.chainId!==t)Dr(c),o.push(c)}catch{}}return o}function Je(e,t,r){let n=r??Xe(io(),ie,Ce);if(e&&t){let s=ao(e,t,r);try{Dr(s)}catch{}return}if(t){let s=Xe(n,t);if(!Ir(s))return;try{for(let o of En(s))if(o.endsWith(".json"))Dr(Xe(s,o))}catch{}return}if(!Ir(n))return;try{for(let s of En(n)){let o=Xe(n,s);try{for(let i of En(o))if(i.endsWith(".json"))Dr(Xe(o,i))}catch{}}}catch{}}var At=()=>{};import Pf from"ws";async function qt(e,t,r=[]){let n=e.timeoutMs??$f;return new Promise((s,o)=>{ye(e.url);let i=new Pf(e.url),a=!1,c=(l)=>{if(!a)a=!0,l()},d=setTimeout(()=>{c(()=>{try{i.close()}catch{}o(Error(`RPC ${t} timed out after ${n}ms`))})},n);i.on("open",()=>{try{i.send(JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:r}))}catch(l){clearTimeout(d),c(()=>o(l instanceof Error?l:Error(String(l))))}}),i.on("message",(l)=>{clearTimeout(d),c(()=>{try{let u=JSON.parse(l.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",(l)=>{clearTimeout(d),c(()=>o(Bt(e.url,l)??(l instanceof Error?l:Error(String(l)))))})})}var $f=5000;var xn=N(()=>{_e()});async function An(e){let t=Va.get(e);if(t&&Date.now()-t.fetchedAt<Of)return t.hash;try{let r=await qt({url:e,timeoutMs:5000},"chain_getBlockHash",[0]);if(typeof r!=="string"||!r.startsWith("0x"))return null;return Va.set(e,{hash:r,fetchedAt:Date.now()}),r}catch{return null}}var Va,Of=60000;var co=N(()=>{xn();Va=new Map});function Mf(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 Tn(e,t,r){let n=Mf(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 Ff from"ws";function Nn(e,t){let{query:r,variables:n,onNext:s,buildResult:o,timeoutMs:i,idleMs:a,idleBeforeFirstEvent:c,initialSilenceMs:d,signal:l}=t;return new Promise((u,p)=>{ye(e);let m=new Ff(e,["graphql-transport-ws"]),y=!1,f=!1,h,w,b,S=()=>{if(clearTimeout(h),w)clearTimeout(w);if(b)clearTimeout(b);try{m.close()}catch{}l?.removeEventListener("abort",P)},v=(J,q)=>{if(f)return;f=!0,S();try{u(o(q))}catch(M){p(M instanceof Error?M:Error(String(M)))}},R=(J)=>{if(f)return;f=!0,S(),p(J)},P=()=>R(Error("Operation cancelled"));l?.addEventListener("abort",P,{once:!0});let Y=()=>{if(w)clearTimeout(w);w=setTimeout(()=>{if(!f&&(y||c))v("idle",!1)},a)};m.on("open",()=>{m.send(JSON.stringify({type:"connection_init"}))}),m.on("message",(J)=>{let q;try{q=JSON.parse(J.toString())}catch{return}if(q.type==="connection_ack"){if(m.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:r,variables:n}})),c)Y();if(d&&d>0)b=setTimeout(()=>{if(!y&&!f)v("initial-silence",!1)},d);return}if(q.type==="error"){R(Error(`GraphQL subscription error: ${JSON.stringify(q.payload)?.slice(0,300)}`));return}if(q.type!=="next")return;if(q.payload?.errors){R(Error(`GraphQL error: ${q.payload.errors[0]?.message||"unknown"}`));return}if(y=!0,b)clearTimeout(b),b=void 0;let M;try{M=s(q.payload?.data)}catch(O){R(O instanceof Error?O:Error(String(O)));return}if(Y(),M)v("caught-up",!1)}),m.on("error",(J)=>R(Bt(e,J)??Error(`WebSocket error: ${J.message}`))),m.on("close",()=>{if(f)return;v(y?"closed-early":"graceful-close",y)}),h=setTimeout(()=>v("timeout",!0),i)})}var lo=N(()=>{_e()});import*as Yt from"@midnight-ntwrk/ledger-v8";function Lf(){let e=new Yt.DustParameters(Ti,Ni,Ri);return new Yt.DustLocalState(e)}function za(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:l=0,initialRetention:u,collapse:p}=r,m=p!==!1&&process.env[uo]!=="1",y=500,f=d??Lf(),h=[],w=e.publicKey,b=new Set((u?.ownedGenerationIndices??[]).map(BigInt)),S=BigInt(u?.generationFrontier??0),v=(M)=>{let O=M.content;if(O?.tag!=="dustInitialUtxo"||O.generationIndex===void 0)return;let ne=O.generationIndex;if(ne+1n>S)S=ne+1n;if(O.generation?.owner===w)b.add(ne)},R=()=>({ownedGenerationIndices:[...b].map(Number),generationFrontier:Number(S)}),P=0,Y=l-1,J=-1,q=()=>{if(h.length===0)return;if(f=f.replayEvents(e,h),P+=h.length,h.length=0,m)f=Tn(f,b,S).state;if(s&&Y>=0)try{s(f,Y,R())}catch{}};return Nn(t,{query:Uf,variables:{id:l},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(M)=>{let O=M?.dustLedgerEvents;if(!O)return!1;let ne;try{ne=Yt.Event.deserialize(Buffer.from(O.raw,"hex"))}catch(ue){throw Error(`Failed to deserialize dust event ${O.id}: ${ue.message}`)}if(v(ne),h.push(ne),Y=O.id,O.maxId>J)J=O.maxId;if(h.length>=500)try{q()}catch(ue){throw Error(`Failed applying dust events: ${ue.message}`)}return n?.(P+h.length,J),Y>=J},buildResult:(M)=>{try{q();let O=new Date;return f=f.processTtls(O),{balance:f.walletBalance(O),availableCoins:f.utxos.length,eventCount:P,ownedUtxoCount:f.utxos.length,syncTime:f.syncTime,state:f,retention:R(),lastAppliedEventId:Y,partial:M}}catch(O){throw Error(`Failed to build dust state: ${O.message}`)}}})}var uo="MN_DISABLE_DUST_COLLAPSE",Uf=`
|
|
92
99
|
subscription DustLedgerEvents($id: Int) {
|
|
93
100
|
dustLedgerEvents(id: $id) {
|
|
94
101
|
type: __typename
|
|
@@ -97,10 +104,11 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
97
104
|
maxId
|
|
98
105
|
}
|
|
99
106
|
}
|
|
100
|
-
`;var
|
|
101
|
-
`,{mode:ge}),d>0?{previous:c,current:n,removed:d}:void 0}function
|
|
107
|
+
`;var po=N(()=>{lo()});import{existsSync as qa,mkdirSync as Bf,readFileSync as Wf,readdirSync as jf,unlinkSync as Hf,writeFileSync as Kf}from"node:fs";import{homedir as Gf}from"node:os";import{join as Rn}from"node:path";function zf(e){return new URL(e).host}function st(e,t,r){let n=zf(t),s=Rn(r??Rn(Gf(),ie,Ce),e),o=Rn(s,Jf),i=qa(o)?Wf(o,"utf-8").trim():void 0;if(i===n)return;let a=qa(s)?jf(s).filter((l)=>l.endsWith(".json")):[],c=i??Vf[e]??n,d=0;if(c!==n)for(let l of a)Hf(Rn(s,l)),d++;return Bf(s,{recursive:!0,mode:me}),Kf(o,n+`
|
|
108
|
+
`,{mode:ge}),d>0?{previous:c,current:n,removed:d}:void 0}function Dn(e,t){return`${e} is now read from ${t.current}; sync state saved from ${t.previous} can't be resumed there, so this sync starts from the beginning.`}var Jf="indexer.host",Vf;var _r=N(()=>{Vf={preprod:"indexer.preprod.midnight.network",preview:"indexer.preview.midnight.network"}});import{spawn as qf}from"node:child_process";import{existsSync as Tt,mkdirSync as Yf,readFileSync as Qa,readdirSync as Ya,unlinkSync as Xa,writeFileSync as Xf}from"node:fs";import{homedir as ec}from"node:os";import{dirname as Za,join as ot}from"node:path";import{fileURLToPath as Zf}from"node:url";import*as tc from"@midnight-ntwrk/ledger-v8";function In(){let e=process.env.MN_DUST_SYNC_BIN;if(e&&Tt(e))return e;let t=process.platform==="win32"?"dust-sync.exe":"dust-sync",r=Za(Zf(import.meta.url));for(let n of[["..",".."],[".."]]){let s=ot(r,...n,"sidecar","dust-sync","target","release",t);if(Tt(s))return s}try{let n=Qf(import.meta.url),s=ot(Za(n.resolve(`${rc()}/package.json`)),t);if(Tt(s))return s}catch{}return null}function Qf(e){return globalThis.require??wi("node:module").createRequire(e)}function rc(){return`@nel349/dust-sync-${process.platform}-${process.arch}`}function nc(){if(process.env.MN_DISABLE_NATIVE_DUST==="1")return"disabled by MN_DISABLE_NATIVE_DUST=1";if(In()===null)return`not installed (${rc()})`;return}function em(e,t,r){if(e+1>=t)return"existing";if(r)return"seed";return"fresh"}function tm(e){if(!Tt(e))return-2;try{let t=JSON.parse(Qa(e,"utf-8"));return typeof t.last_applied_event_id==="number"?t.last_applied_event_id:-2}catch{return-2}}function rm(e,t){let r=ot(ec(),ie,Ce,e);if(!Tt(r))Yf(r,{recursive:!0,mode:me});return ot(r,`dust-native-${t.slice(0,20)}.json`)}function _n(e,t){let r=ot(ec(),ie,Ce);if(e&&t){try{Xa(ot(r,e,`dust-native-${t.slice(0,20)}.json`))}catch{}return}let n=(s)=>{if(!Tt(s))return;try{for(let o of Ya(s))if(o.startsWith("dust-native-")&&o.endsWith(".json"))try{Xa(ot(s,o))}catch{}}catch{}};if(e){n(ot(r,e));return}if(!Tt(r))return;try{for(let s of Ya(r))n(ot(r,s))}catch{}}function sc(e,t,r){return new Promise((n,s)=>{let o=In();if(!o){s(Error("dust-sync sidecar not found"));return}ye(t.indexerWS);let i=t.networkId.toLowerCase(),a=Ke(e),c=rm(i,a),d=["--indexer-ws",t.indexerWS,"--out",c],l=em(tm(c),r.startFromId,!!r.initialState);if(l==="seed"){let h={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};Xf(c,JSON.stringify(h),{mode:ge})}if(l!=="fresh")d.push("--resume",c);let u=qf(o,d,{stdio:["pipe","pipe","pipe"]}),p=()=>{try{u.kill("SIGINT")}catch{}};r.signal?.addEventListener("abort",p,{once:!0}),u.stdin.on("error",()=>{});let m=Buffer.from(dt(e)).toString("hex");u.stdin.write(m+`
|
|
102
109
|
`),u.stdin.end();let y="",f="";u.stdout.on("data",(h)=>{y+=h.toString()}),u.stderr.on("data",(h)=>{let w=h.toString();f=(f+w).slice(-2000);for(let b of w.matchAll(/applied (\d+) \/ (\d+)/g))r.onProgress?.(Number(b[1]),Number(b[2]))}),u.on("error",(h)=>{r.signal?.removeEventListener("abort",p),s(h)}),u.on("close",(h)=>{if(r.signal?.removeEventListener("abort",p),h!==0){s(Error(`dust-sync exited ${h}: ${f.trim().slice(-300)}`));return}try{let w=y.trim().split(`
|
|
103
|
-
`).filter(Boolean).pop(),b=w?JSON.parse(w):JSON.parse(
|
|
110
|
+
`).filter(Boolean).pop(),b=w?JSON.parse(w):JSON.parse(Qa(c,"utf-8"));n(nm(b))}catch(w){s(Error(`dust-sync output parse failed: ${w.message}`))}})})}function nm(e){let t=new Date,r=tc.DustLocalState.deserialize(new Uint8Array(Buffer.from(e.dust_state,"hex")));if(process.env[uo]!=="1"){let s=new Set(e.owned_generation_indices.map((o)=>BigInt(o)));r=Tn(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 fo=N(()=>{bt();po();xt();_e()});function oc(e){let{code:t,syscall:r}=e;if(t!==void 0&&String(r??"").startsWith("spawn"))return`can't start on this system (${t})`;return`failed (${(e instanceof Error?e.message:String(e)).split(`
|
|
111
|
+
`)[0].slice(0,120)})`}function ic(e){return`Native Dust reader ${e}: reading with the built-in one, several times slower on a long sync. See "Native dust acceleration" in the README.`}function ac(e,t,r){let n=!1;return(s,o)=>{if(!n&&o+1-e>50000)n=!0,r();t?.(s,o)}}import*as dc from"@midnight-ntwrk/ledger-v8";class lc{now;fetchTip;fetchUnshielded;fetchDust;fetchChainId;cacheDir;dustMemo=new Map;unshieldedMemo=new Map;tipMemo=new Map;constructor(e={}){this.now=e.now??Date.now,this.fetchTip=e.fetchTip??lm,this.fetchUnshielded=e.fetchUnshielded??um,this.fetchDust=e.fetchDust??fm,this.fetchChainId=e.fetchChainId??An,this.cacheDir=e.cacheDir}keepCachesOfThisIndexer(e,t,r){let n=st(e,t.indexerWS,this.cacheDir);if(n)r?.(Dn(e,n))}async freshWalletOnDustCheckpoint(e,t,r){let n=Vt(r,Ke(e),this.cacheDir);if(!n||n.lastAppliedEventId<0)return null;let s=await Ge(e,t,null);try{let{shielded:o,unshielded:i,dust:a}=s.facade,[c,d,l]=await Promise.all([o.serializeState(),i.serializeState(),a.serializeState()]);return{shielded:c,unshielded:d,dust:Nr(l,n)}}finally{await Oe(s).catch(()=>{})}}async dust(e,t,r={}){let n=Pn(t),s=Ke(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);Fa(n,i,this.cacheDir),this.keepCachesOfThisIndexer(n,t,r.onStatus);let a=i??void 0,c=r.forceFresh?null:Vt(n,s,this.cacheDir),d=c!==null,l=0,u=c?.lastAppliedEventId??-1,p=null,m=this.now(),y=0;for(let h=0;;h++){if(r.signal?.aborted)throw Error("Operation cancelled");let w=c?c.lastAppliedEventId+1:0;if(r.onStatus?.(h>0?`Resuming dust from event ${w} (continuation ${h+1})…`:c?`Resuming dust from event ${w}…`:"Reading dust events…"),p=await this.fetchDust(e,t,{startFromId:w,initialState:c?.state,initialRetention:c?.retention,signal:r.signal,onProgress:(b,S)=>{let v=Math.max(1,S+1-w);r.onStatus?.(`Reading dust events… ${b}/${v}`),r.onProgress?.(b,S)},onCheckpoint:(b,S,v)=>{try{no(n,s,b,S,this.cacheDir,a,v)}catch{}}}),u=p.lastAppliedEventId>=0?p.lastAppliedEventId:c?.lastAppliedEventId??-1,p.lastAppliedEventId>=0||!c)try{no(n,s,p.state,u,this.cacheDir,a,p.retention)}catch{}if(l+=p.eventCount,!p.partial)break;if(y=p.eventCount>0?0:y+1,y>=im||this.now()-m>=om)break;c=Vt(n,s,this.cacheDir)}if(!p)throw Error("Dust sync exhausted retries without producing a result");let f={state:p.state,balance:p.balance,availableCoins:p.availableCoins,ownedUtxoCount:p.ownedUtxoCount,syncTime:p.syncTime,fromCache:d,eventsApplied:l,lastAppliedEventId:u,partial:p.partial,fetchedAt:this.now()};return await this.memoize(this.dustMemo,o,f,t,r.signal),f}async unshielded(e,t,r={}){let n=Pn(t),s=typeof e==="string"?e:Se(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=Pn(t),c=Se(e,a),d=t.networkId!=="Undeployed",l=n.syncTimeoutMs??(d?cm:am),u=await this.fetchChainId(t.node).catch(()=>null);Ja(a,u,this.cacheDir),this.keepCachesOfThisIndexer(a,t,n.onStatus);let p=u??void 0;if(i&&!n.noPrime&&!n.forceFresh)try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch(w){n.onSyncWarning?.("PrePrime",w.message)}let m,y,f=!1,h=async()=>{if(f||!m)return;f=!0;try{await Oe(m)}catch{}};try{for(let S=1;S<=Pr;S++){if(n.signal?.aborted)throw Error("Operation cancelled");let v=n.forceFresh?null:mt(c,a,this.cacheDir)??await this.freshWalletOnDustCheckpoint(e,t,a);m=await Ge(e,t,v);try{y=await ft(m,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:l,syncMode:s,requireStrictSync:o});break}catch(R){if(n.signal?.aborted)throw Error("Operation cancelled");if(R instanceof vn&&S<Pr&&i){n.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${S+1}/${Pr})...`),await Oe(m).catch(()=>{}),m=void 0,Je(c,a,this.cacheDir),pt(a,Ke(e),this.cacheDir);try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch{}continue}if(S<Pr&&String(R?.message??"").includes("timed out")){try{await gt(c,a,m.facade,this.cacheDir,p)}catch{}n.onStatus?.(`Sync timed out, retrying (attempt ${S+1}/${Pr})...`),await Oe(m).catch(()=>{}),m=void 0;continue}throw R}}if(!m||!y)throw Error("Sync failed: no facade state after retries");let w,b=0;while(!0){if(b++,n.signal?.aborted)throw Error("Operation cancelled");try{w=await r({bundle:m,state:y});break}catch(S){if(!(i&&b<cc&&Rr(S)))throw S;if(n.onStatus?.(`Refreshing wallet state (attempt ${b+1}/${cc})...`),await Oe(m).catch(()=>{}),m=void 0,await new Promise((P)=>setTimeout(P,dm)),n.signal?.aborted)throw Error("Operation cancelled");let R=mt(c,a,this.cacheDir);m=await Ge(e,t,R),y=await ft(m,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:l,syncMode:s,requireStrictSync:o})}}if(!n.skipAutoSave)try{await gt(c,a,m.facade,this.cacheDir,p)}catch{}if(!n.readOnly)this.invalidate({network:t,seed:e});return w}finally{await h()}}invalidate(e){let t=Pn(e.network),r=e.kinds??["dust","unshielded","facade"];if(r.includes("dust"))if(e.seed){let n=Ke(e.seed);this.dustMemo.delete(`${t}:${n}`)}else this.deleteByPrefix(this.dustMemo,`${t}:`);if(r.includes("unshielded")){let n=e.address??(e.seed?Se(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=Se(e.seed,t);try{Je(n,t,this.cacheDir)}catch{}}}resetTipMemo(){this.tipMemo.clear()}async tryMemo(e,t,r,n){let s=r.get(e);if(!s)return null;let o;try{o=await this.getTip(t,n)}catch{return s.value}if(o===s.tipAtFetch)return s.value;return r.delete(e),null}async memoize(e,t,r,n,s){try{let o=await this.getTip(n,s);e.set(t,{value:r,fetchedAt:this.now(),tipAtFetch:o})}catch{F("repo",`tip unavailable; skipping memo for ${t}`)}}async getTip(e,t){let r=this.tipMemo.get(e.networkId);if(r&&this.now()-r.fetchedAt<sm)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 lm(e){return qt({url:e.node,timeoutMs:3000},"chain_getBlockHash",[])}function um(e,t,r){return Jt(e,t.indexerWS,r)}function pm(e,t,r){let n=dt(e),s=dc.DustSecretKey.fromSeed(n);return za(s,t.indexerWS,r)}async function fm(e,t,r){let n=nc();if(n===void 0)try{return F("dust",`native sidecar: ${In()}`),await sc(e,t,r)}catch(o){F("dust",`native sidecar failed, using WASM: ${o.message}`),n=oc(o)}else F("dust",`native sidecar ${n}, using WASM`);let s=n;return pm(e,t,{...r,onProgress:ac(r.startFromId,r.onProgress,()=>Aa(ic(s)))})}function Pn(e){let t=e.networkId.toLowerCase();if(Ne(t))return t;throw Error(`Unsupported network: ${e.networkId}`)}function ve(){if(!mo)mo=new lc;return mo}var sm=5000,om=3600000,im=3,am=30000,cm=120000,Pr=3,cc=5,dm=5000,mo=null;var ht=N(()=>{Ue();Ye();xt();At();co();xr();po();_r();fo();ut();xn();bt();je()});import*as Xt from"@midnight-ntwrk/ledger-v8";function gm(e){let t=Xt.unshieldedToken().raw,r=0n,n=0;for(let s of e.coins)if(s.type===t)r+=s.value,n++;return{balance:r,count:n}}function uc(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:l=0}=r,u=500,p=d??new Xt.ZswapLocalState,m=[],y=0,f=l-1,h=-1,w=()=>{if(m.length===0)return;if(p=p.replayEventsWithChanges(e,m).state,y+=m.length,m.length=0,s&&f>=0)try{s(p,f)}catch{}};return Nn(t,{query:mm,variables:{id:l},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(b)=>{let S=b?.zswapLedgerEvents;if(!S)return!1;let v;try{v=Xt.Event.deserialize(new Uint8Array(Buffer.from(S.raw,"hex")))}catch(R){throw Error(`Failed to deserialize zswap event ${S.id}: ${R.message}`)}if(m.push(v),f=S.id,S.maxId>h)h=S.maxId;if(m.length>=500)try{w()}catch(R){throw Error(`Failed applying zswap events: ${R.message}`)}return n?.(y+m.length,h),f>=h},buildResult:(b)=>{try{w();let{balance:S,count:v}=gm(p);return{balance:S,availableCoins:v,eventCount:y,state:p,lastAppliedEventId:f,partial:b}}catch(S){throw Error(`Failed to build shielded state: ${S.message}`)}}})}var mm=`
|
|
104
112
|
subscription ZswapLedgerEvents($id: Int) {
|
|
105
113
|
zswapLedgerEvents(id: $id) {
|
|
106
114
|
id
|
|
@@ -108,108 +116,102 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
108
116
|
maxId
|
|
109
117
|
}
|
|
110
118
|
}
|
|
111
|
-
`;var
|
|
112
|
-
Expected a bech32m address for network "${t.networkId}"`)}}function
|
|
113
|
-
Available: ${
|
|
119
|
+
`;var pc=N(()=>{lo()});import{existsSync as $n,mkdirSync as hm,writeFileSync as wm,readFileSync as ym,unlinkSync as ho,readdirSync as fc,renameSync as Sm}from"node:fs";import{join as Zt,dirname as bm}from"node:path";import{homedir as mc}from"node:os";import{randomBytes as vm}from"node:crypto";import*as $r from"@midnight-ntwrk/ledger-v8";function hc(e){return $r.ZswapSecretKeys.fromSeed(St(e)).coinPublicKey}function wc(e,t){let r=t??Zt(mc(),ie,Ce);return Zt(r,e)}function wo(e,t,r){let n=t.slice(0,20);return Zt(wc(e,r),`shielded-${n}.json`)}function km(e,t,r,n){let s=wo(e,t,r);if(!$n(s))return null;try{let o=JSON.parse(ym(s,"utf-8"));if(o.version!==gc)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:$r.ZswapLocalState.deserialize(new Uint8Array(Buffer.from(o.zswapState,"hex"))),lastAppliedEventId:o.lastAppliedEventId}}catch{return null}}function go(e,t,r,n,s,o){let i={version:gc,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=bm(a);if(!$n(c))hm(c,{recursive:!0,mode:me});let d=a+`.tmp.${vm(4).toString("hex")}`;try{wm(d,JSON.stringify(i),{mode:ge}),Sm(d,a)}catch(l){try{ho(d)}catch{}throw l}}function On(e,t,r){let n=r??Zt(mc(),ie,Ce);if(e&&t){let o=wo(e,t,r);try{ho(o)}catch{}return}let s=(o)=>{if(!$n(o))return;try{for(let i of fc(o))if(i.startsWith("shielded-")&&i.endsWith(".json"))try{ho(Zt(o,i))}catch{}}catch{}};if(e){s(wc(e,r));return}if(!$n(n))return;try{for(let o of fc(n))s(Zt(n,o))}catch{}}async function yc(e,t,r,n={}){let s=$r.ZswapSecretKeys.fromSeed(St(e)),o=s.coinPublicKey;st(t,r);let i=n.forceFresh?null:km(t,o,void 0,n.chainId),a=i?i.lastAppliedEventId+1:0,c=await uc(s,r,{initialState:i?.state,startFromId:a,onProgress:n.onProgress,signal:n.signal,timeoutMs:n.timeoutMs,onCheckpoint:(d,l)=>{try{go(t,o,d,l,void 0,n.chainId)}catch{}}});if(c.lastAppliedEventId>=0)go(t,o,c.state,c.lastAppliedEventId,void 0,n.chainId);else if(!i)go(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 gc=1;var yo=N(()=>{_r();bt();pc()});function Sc(e={}){let t=Math.min(Math.max(e.windowMs??15000,1000),60000),r=[],n=null,s=(i)=>{let a=i-t;while(r.length>0&&r[0].t<a)r.shift()},o=()=>{let i=r[r.length-1],a=r[0],c=i.highest>0?Math.min(100,Math.round(i.applied/i.highest*100)):null,d=null,l=null;if(r.length>=2){let u=i.applied-a.applied,p=i.t-a.t;if(p>=1000&&u>0){d=u/(p/1000);let m=Math.max(0,i.highest-i.applied);l=m>0?m/d:0}}return{applied:i.applied,highest:i.highest,percent:c,ratePerSec:d,etaSec:l}};return{sample(i){return r.push(i),s(i.t),n=o(),n},snapshot(){return n},reset(){r.length=0,n=null}}}function bc(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 ${Cm(e.etaSec)}`);if(e.ratePerSec!==null&&e.ratePerSec>0)r.push(`${Math.round(e.ratePerSec)} evt/s`);return r.join(" · ")}function Cm(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 vo from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Em,UnshieldedAddress as xm}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as So}from"@midnight-ntwrk/wallet-sdk-abstractions";function Or(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 Mr(e){let t=Number(e);if(Number.isNaN(t)||!Number.isFinite(t))throw new W(`Invalid amount: "${e}" — must be a positive number`);if(t<=0)throw new W(`Invalid amount: "${e}" — must be greater than 0`);return t}function Tm(e,t){let r=Am[t.networkId];if(r===void 0)throw Error(`Unknown networkId: ${t.networkId}`);try{return Em.parse(e).decode(xm,r)}catch(n){throw Error(`Invalid recipient address: ${n.message}
|
|
120
|
+
Expected a bech32m address for network "${t.networkId}"`)}}function wt(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 bo(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 De(){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 Nm(e,t,r){let n=new Date(Date.now()+dr*60*1000);await Promise.race([e.facade.dust.waitForSyncedState(),new Promise((d,l)=>setTimeout(()=>l(Error("Insufficient funds: dust wallet sync timed out")),Ss))]);let s=await e.facade.dust.createDustGenerationTransaction(new Date,n,t,e.keystore.getPublicKey(),r),o=s.intents?.get(1);if(!o)throw Error("Dust generation intent not found on transaction");let i=e.keystore.signData(o.signatureData(1)),a=await e.facade.dust.addDustGenerationSignature(s,i),c=await e.facade.finalizeTransaction(a);return await e.facade.submitTransaction(c)}async function Rm(e,t,r,n){let s=Date.now(),o=s+Mi,i,a=!1,c=setInterval(()=>{if(a&&n){let d=bo(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 Nm(e,t,r)}catch(d){if(i=d,Cn(d)&&Date.now()+ks<o){a=!0;let l=bo(Date.now()-s);n?.(`Waiting for dust generation capacity (${l} elapsed, ~5 min on fresh wallets)...`),await new Promise((u)=>setTimeout(u,ks));continue}throw d}throw i??Error("Dust registration timed out")}finally{clearInterval(c)}}async function Ze(e,t,r){let n=r??await e.facade.waitForSyncedState();if(n.dust.availableCoins.length>0||n.dust.balance(new Date)>0n)return t?.("Dust available"),{alreadyAvailable:!0};let s=n.unshielded.availableCoins.filter((a)=>a.meta?.registeredForDustGeneration!==!0),o;if(s.length>0){t?.(`Registering ${s.length} UTXO(s) for dust generation...`);let a=s.map((c)=>({...c.utxo,ctime:new Date(c.meta.ctime)}));o=await Rm(e,a,n.dust.address,t)}else t?.("UTXOs already registered, waiting for dust generation...");t?.("Waiting for dust tokens...");let i=Date.now();while(Date.now()-i<bs){try{if((await Promise.race([e.facade.waitForSyncedState(),new Promise((c,d)=>setTimeout(()=>d(Error("Poll sync timed out")),Ss))])).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 Dm(e,t,r,n,s,o,i){let a=Date.now(),c=a+bs,d,l=0;while(!0)try{if(d)await oo(e,"lite");let u=new Date(Date.now()+dr*60*1000);F("transfer","Building transfer transaction...");let p=await e.facade.transferTransaction([{type:"unshielded",outputs:[{amount:r,receiverAddress:t,type:vo.unshieldedToken().raw}]}],{shieldedSecretKeys:e.zswapSecretKeys,dustSecretKey:e.dustSecretKey},{ttl:u,payFees:!0});F("transfer","Signing recipe...");let m=await e.facade.signRecipe(p,(b)=>e.keystore.signData(b));F("transfer","Generating ZK proof..."),n?.();let y=await Promise.race([e.facade.finalizeRecipe(m),new Promise((b,S)=>{setTimeout(()=>S(Error("ZK proof generation timed out")),Yr)})]);F("transfer","Submitting transaction to node..."),s?.();let f=Date.now(),h=i?setInterval(()=>i(Date.now()-f),1000):void 0,w;try{w=await e.facade.submitTransaction(y)}finally{if(h)clearInterval(h)}return F("transfer",`Transaction submitted: ${w}`),w}catch(u){if(d=u,(u?.code===Fi||u?.message?.includes("115")||u?.message?.toLowerCase().includes("stale"))&&++l<Oi)continue;if(Rr(u))throw u;if(Cn(u)&&Date.now()<c){let m=bo(Date.now()-a);o?.(`Dust insufficient, re-ensuring (${m} elapsed)...`);try{let y=await oo(e,"lite"),f=y.dust.balance(new Date);if(f>0n&&f<Te)throw Error(`Insufficient dust for transaction fees.
|
|
121
|
+
Available: ${wt(f)} DUST, need ≥${wt(Te)} DUST.
|
|
114
122
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
115
|
-
Check status: midnight dust status`);await
|
|
116
|
-
Available: ${
|
|
123
|
+
Check status: midnight dust status`);await Ze(e,o,y)}catch(y){if(String(y?.message).startsWith("Insufficient dust"))throw y;await new Promise((f)=>setTimeout(f,5000))}continue}throw u}}async function Qt(e){let{seedBuffer:t,networkConfig:r,recipientAddress:n,amountNight:s,signal:o,onSync:i,onSyncDetail:a,onDust:c,onProving:d,onSubmitting:l,onSubmittingTick:u,onSyncWarning:p}=e,m=Or(s),y=Tm(n,r),f=xe(p),h=De();try{return await ve().withFacade(t,r,async({bundle:w,state:b})=>{if(o?.aborted)throw Error("Operation cancelled");F("transfer","Sync complete, checking balance...");let S=b.unshielded.balances[vo.unshieldedToken().raw]??0n,v=b.unshielded.availableCoins?.length??0;if(F("transfer",`Balance: ${Number(S)/ys} NIGHT, coins: ${v}`),S<m){let Y=Number(S)/ys;throw Error(`Insufficient balance: ${Y.toFixed(6)} NIGHT available, ${s} NIGHT requested`)}let R=b.dust.balance(new Date);if(R>0n&&R<Te)throw Error(`Insufficient dust for transaction fees.
|
|
124
|
+
Available: ${wt(R)} DUST, need ≥${wt(Te)} DUST.
|
|
117
125
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
118
|
-
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(F("transfer","Ensuring dust availability..."),await
|
|
119
|
-
|
|
120
|
-
`)},log(d){process.stderr.write(`\r\x1B[K${d}
|
|
121
|
-
`),process.stderr.write(`⠋ ${a}`)}};return Yt=c,c}let r=0,n=e,s=()=>{let a=K(sc[r]),d=(process.stderr.columns||80)-4,l=n;if(oc(l).length>d)l=oc(l).slice(0,d);process.stderr.write(`\r${a} ${l}\x1B[K`),r=(r+1)%sc.length};s();let o=setInterval(s,lm),i={update(a){n=a},stop(a){if(t)return;t=!0,clearInterval(o),Yt=null;let c=a??n;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${c}\x1B[K
|
|
122
|
-
`)},fail(a){if(t)return;t=!0,clearInterval(o),Yt=null;let c=a??n;process.stderr.write(`\r\x1B[31m✗\x1B[0m ${c}\x1B[K
|
|
123
|
-
`)},log(a){process.stderr.write(`\r\x1B[K${a}
|
|
124
|
-
`),s()}};return Yt=i,i}async function On(e,t,r){let n=Date.now(),s=(a)=>{let c=Math.floor(a/1000),d=Math.floor(c/60).toString().padStart(2,"0"),l=(c%60).toString().padStart(2,"0");return`${d}:${l}`},o=()=>e.update(`${t} ${s(Date.now()-n)}`);o();let i=setInterval(o,1000);try{return await r}finally{clearInterval(i)}}var sc,lm=80,Yt=null;var nt=N(()=>{sc=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var dc={};fe(dc,{default:()=>ac});import*as ic from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as um}from"@midnight-ntwrk/wallet-sdk-address-format";async function ac(e){if(e.subcommand)return fm(e);return cc(e)}function pm(e){let t=e.match(/^mn_addr_([a-z]+)1/);if(!t)return null;let r=t[1];return xe(r)?r:null}async function fm(e){if(Le(e))We();let t=e.subcommand;F("balance",`address=${t}`);let r=pm(t),n=k(e,"network");if(n&&r&&n!==r)throw Error(`Address belongs to ${r} but --network is ${n}.
|
|
125
|
-
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}=Q({args:e});if(I(e,"shielded")){let a=Qi(t);if(a){F("balance",`shielded positional → wallet ${a.wallet.name} on ${a.network}`);let c={...e,flags:{...e.flags,wallet:a.wallet.file,network:a.network}};return cc(c)}throw Error("Shielded balances are private — they can only be read with the wallet's secret key, "+`not from an address alone.
|
|
126
|
+
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(F("transfer","Ensuring dust availability..."),await Ze(w,c,b),F("transfer","Dust available"),o?.aborted)throw Error("Operation cancelled");return F("transfer","Building and submitting transaction..."),{txHash:await Dm(w,y,m,d,l,c,u),amountMicroNight:m}},{syncMode:"lite",requireStrictSync:!0,signal:o,onStatus:c,onSyncProgress:i,onSyncDetail:a,onSyncWarning:p})}finally{h(),f()}}var Am;var Nt=N(()=>{Fe();Ye();ht();ut();Am={PreProd:So.NetworkId.PreProd,Preview:So.NetworkId.Preview,Undeployed:So.NetworkId.Undeployed}});var Ec={};fe(Ec,{default:()=>kc});import*as vc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Im}from"@midnight-ntwrk/wallet-sdk-address-format";async function kc(e){if(e.subcommand)return Pm(e);return Cc(e)}function _m(e){let t=e.match(/^mn_addr_([a-z]+)1/);if(!t)return null;let r=t[1];return Ne(r)?r:null}async function Pm(e){if(We(e))He();let t=e.subcommand;F("balance",`address=${t}`);let r=_m(t),n=k(e,"network");if(n&&r&&n!==r)throw Error(`Address belongs to ${r} but --network is ${n}.
|
|
127
|
+
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}=Q({args:e});if(D(e,"shielded")){let a=aa(t);if(a){F("balance",`shielded positional → wallet ${a.wallet.name} on ${a.network}`);let c={...e,flags:{...e.flags,wallet:a.wallet.file,network:a.network}};return Cc(c)}throw Error("Shielded balances are private — they can only be read with the wallet's secret key, "+`not from an address alone.
|
|
126
128
|
This address isn't one of your wallets. Check its shielded balance from the wallet that owns it:
|
|
127
|
-
midnight balance --wallet <name> --shielded --network ${s}`)}
|
|
128
|
-
`);else for(let[c,d]of a.balances)process.stdout.write(`${
|
|
129
|
+
midnight balance --wallet <name> --shielded --network ${s}`)}Le(o,{proofServer:k(e,"proof-server"),node:k(e,"node"),indexerWS:k(e,"indexer-ws")},s);let i=z(`Checking balance on ${s}...`);try{let a=await ve().unshielded(t,o,{forceFresh:D(e,"no-cache"),onProgress:(c,d)=>{if(d>0){let l=Math.round(c/d*100);i.update(`Syncing transactions... ${l}%`)}}});if(i.stop(`Synced ${a.txCount} transactions`),D(e,"json")){let c={};for(let[l,u]of a.balances){let p=Er(l)?"NIGHT":l;c[p]=Er(l)?kt(u):u.toString()}let d=c.NIGHT!==void 0?{NIGHT:c.NIGHT}:{};if(ct(e)){I({network:s,balances:c,...d,utxoCount:a.utxoCount});return}I({address:t,network:s,balances:c,...d,utxoCount:a.utxoCount,txCount:a.txCount});return}if(a.balances.size===0)process.stdout.write(`0
|
|
130
|
+
`);else for(let[c,d]of a.balances)process.stdout.write(`${Er(c)?"NIGHT":c}=${d}
|
|
129
131
|
`);if(process.stderr.write(`
|
|
130
|
-
`+
|
|
132
|
+
`+U("Balance")+`
|
|
131
133
|
|
|
132
|
-
`),process.stderr.write(C("Address",
|
|
134
|
+
`),process.stderr.write(C("Address",re(t))+`
|
|
133
135
|
`),process.stderr.write(C("Network",s)+`
|
|
134
136
|
`),process.stderr.write(C("UTXOs",a.utxoCount.toString())+`
|
|
135
137
|
`),process.stderr.write(C("Transactions",a.txCount.toString())+`
|
|
136
138
|
`),process.stderr.write(`
|
|
137
139
|
`),a.balances.size===0)process.stderr.write(` ${g("No balance found")}
|
|
138
|
-
`);else for(let[c,d]of a.balances)if(
|
|
140
|
+
`);else for(let[c,d]of a.balances)if(Er(c))process.stderr.write(C("NIGHT",_(un(d)))+`
|
|
139
141
|
`);else{let l=c.slice(0,8)+"…"+c.slice(-8);process.stderr.write(C(`Token ${l}`,_(d.toString()))+`
|
|
140
142
|
`)}process.stderr.write(`
|
|
141
143
|
`+V()+`
|
|
142
144
|
|
|
143
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
144
|
-
`+
|
|
145
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Cc(e){if(We(e))He();let{name:t,config:r}=Q({args:e});F("balance",`network=${t} indexerWS=${r.indexerWS}`);let{seed:n,walletPath:s,config:o}=zs(e);F("balance",`wallet path=${s??"(from --seed/MN_SEED)"}`);let i=o?.addresses[t]??Se(n,t),a=o?.shieldedAddresses?.[t]??"";Le(r,{proofServer:k(e,"proof-server"),node:k(e,"node"),indexerWS:k(e,"indexer-ws")},t);let c=xe(),d=De(),l=D(e,"no-cache"),u=D(e,"json"),p=vc.unshieldedToken().raw,m=null;try{if(!u){if(process.stderr.write(`
|
|
146
|
+
`+U("Balance")+`
|
|
145
147
|
|
|
146
|
-
`),process.stderr.write(C("Address",
|
|
147
|
-
`),a)process.stderr.write(C("Shielded",
|
|
148
|
+
`),process.stderr.write(C("Address",re(i))+`
|
|
149
|
+
`),a)process.stderr.write(C("Shielded",re(a))+`
|
|
148
150
|
`);process.stderr.write(C("Network",t)+`
|
|
149
151
|
`),process.stderr.write(`
|
|
150
152
|
`+_("Unshielded")+`
|
|
151
|
-
`)}if(!u)m=
|
|
153
|
+
`)}if(!u)m=z("Checking unshielded...");F("balance",`phase=unshielded forceFresh=${l}`);let y=await ve().unshielded(i,r,{forceFresh:l}),f=y.balances.get(p)??0n,h=y.utxoCount;if(F("balance",`unshielded fromCache=${y.fromCache} utxos=${h} txs=${y.txCount}`),m)if(m.stop("Unshielded ready"),m=null,f>0n)process.stderr.write(C(" NIGHT",_(un(f)))+`
|
|
152
154
|
`),process.stderr.write(C(" UTXOs",h.toString())+`
|
|
153
155
|
`);else process.stderr.write(` ${g("No unshielded balance")}
|
|
154
156
|
`);if(!u)process.stdout.write(`NIGHT=${f}
|
|
155
157
|
`),process.stderr.write(`
|
|
156
158
|
`+_("Shielded")+`
|
|
157
|
-
`);let w=
|
|
159
|
+
`);let w=hn(t,D(e,"force-shielded")),b=a,S=0n,v=0,R=0;if(w){if(!u)m=z("Syncing shielded...");let P=Sc(),Y=Ct(r.networkId);if(b=Im.encode(Y,yr(n)).asString(),s)jt(s,t,b);let J=await An(r.node).catch(()=>null)??void 0,q=await yc(n,t,r.indexerWS,{forceFresh:l,chainId:J,onProgress:(M,O)=>{if(!m)return;let ne=P.sample({applied:M,highest:O,t:Date.now()});m.update(bc(ne,"Syncing shielded"))}});if(S=q.balance,v=q.availableCoins,R=0,m)if(m.stop("Shielded ready"),m=null,S>0n)process.stderr.write(C(" NIGHT",_(un(S)))+`
|
|
158
160
|
`),process.stderr.write(C(" Coins",`${v} available, ${R} pending`)+`
|
|
159
161
|
`);else process.stderr.write(` ${g("No shielded balance")}
|
|
160
|
-
`)}else if(!u)process.stderr.write(` ${g("Skipped — "+
|
|
161
|
-
`);if(u){if(
|
|
162
|
+
`)}else if(!u)process.stderr.write(` ${g("Skipped — "+wn(t))}
|
|
163
|
+
`);if(u){if(ct(e)){I({network:t,unshielded:{NIGHT:kt(f),utxoCount:h},shielded:{NIGHT:kt(S),availableCoins:v,pendingCoins:R},shieldedSynced:w});return}I({address:i,shieldedAddress:b,network:t,unshielded:{NIGHT:kt(f),utxoCount:h},shielded:{NIGHT:kt(S),availableCoins:v,pendingCoins:R},shieldedSynced:w});return}process.stdout.write(`SHIELDED_NIGHT=${w?S:"skipped"}
|
|
162
164
|
`),process.stderr.write(`
|
|
163
165
|
`+V()+`
|
|
164
166
|
|
|
165
|
-
`)}catch(y){throw m?.fail("Failed"),y}finally{d(),c()}}var
|
|
167
|
+
`)}catch(y){throw m?.fail("Failed"),y}finally{d(),c()}}var xc=N(()=>{ut();Ue();$e();gn();pe();Ue();qs();yn();xr();ht();yo();je();co();Ye();Nt();he();qe()});var Tc={};fe(Tc,{default:()=>Ac});async function Ac(e){let t=mn(e,{requireExplicit:!0,label:"address"}),r=k(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=Pe({args:e}),o=Se(t,s,n),i=`m/44'/2400'/0'/NightExternal/${n}`;if(D(e,"json")){I({address:o,network:s,index:n,path:i});return}process.stdout.write(o+`
|
|
166
168
|
`),process.stderr.write(`
|
|
167
169
|
`),process.stderr.write(C("Network",s)+`
|
|
168
170
|
`),process.stderr.write(C("Index",n.toString())+`
|
|
169
|
-
`),process.stderr.write(C("Address",
|
|
171
|
+
`),process.stderr.write(C("Address",re(o))+`
|
|
170
172
|
`),process.stderr.write(C("Path",g(i))+`
|
|
171
173
|
`),process.stderr.write(V()+`
|
|
172
174
|
|
|
173
|
-
`)}var
|
|
175
|
+
`)}var Nc=N(()=>{gn();je();pe();he()});var Dc={};fe(Dc,{default:()=>Rc});async function Rc(e){let t=Pe({args:e}),r=Buffer.from(Qe,"hex"),n=Se(r,t);if(D(e,"json")){I({address:n,network:t});return}process.stdout.write(n+`
|
|
174
176
|
`),process.stderr.write(`
|
|
175
177
|
`),process.stderr.write(C("Network",t)+`
|
|
176
|
-
`),process.stderr.write(C("Address",
|
|
178
|
+
`),process.stderr.write(C("Address",re(n))+`
|
|
177
179
|
`),process.stderr.write(C("Seed",g("0x01 (genesis)"))+`
|
|
178
180
|
`),process.stderr.write(V()+`
|
|
179
181
|
|
|
180
|
-
`)}var
|
|
182
|
+
`)}var Ic=N(()=>{je();pe();he()});var $c={};fe($c,{default:()=>Pc});import*as _c from"@midnight-ntwrk/ledger-v8";function Fr(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 $m(e){return{readTime:Fr(e,"readTime",1000000000n),computeTime:Fr(e,"computeTime",1000000000n),blockUsage:Fr(e,"blockUsage",10000n),bytesWritten:Fr(e,"bytesWritten",10000n),bytesChurned:Fr(e,"bytesChurned",1000000n)}}async function Pc(e){let t=_c.LedgerParameters.initialParameters(),r=$m(t);if(D(e,"json")){I(r);return}for(let[n,s]of Object.entries(r))process.stdout.write(`${n}=${s}
|
|
181
183
|
`);process.stderr.write(`
|
|
182
|
-
`+
|
|
184
|
+
`+U("Block Limits")+`
|
|
183
185
|
|
|
184
186
|
`),process.stderr.write(g(" Derived from LedgerParameters.initialParameters()")+`
|
|
185
187
|
|
|
186
|
-
`);for(let[n,s]of Object.entries(r)){let o=
|
|
188
|
+
`);for(let[n,s]of Object.entries(r)){let o=Om[n]??"";process.stderr.write(C(n,`${_(s.toLocaleString())} ${g(o)}`)+`
|
|
187
189
|
`)}process.stderr.write(`
|
|
188
190
|
`+V()+`
|
|
189
191
|
`),process.stderr.write(g(" bytesWritten is typically the tightest constraint")+`
|
|
190
192
|
`),process.stderr.write(g(" for large contract deployments.")+`
|
|
191
193
|
|
|
192
|
-
`)}var
|
|
194
|
+
`)}var Om;var Oc=N(()=>{he();Om={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});var Lc={};fe(Lc,{default:()=>Uc});import*as Mc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Fc,ShieldedAddress as Mm}from"@midnight-ntwrk/wallet-sdk-address-format";async function Uc(e,t){$t(e);let r=e.subcommand;if(!r)throw Error(`Missing amount.
|
|
193
195
|
Usage: midnight airdrop <amount> [--wallet <name|file|address>]
|
|
194
196
|
Example: midnight airdrop 1000
|
|
195
197
|
Example: midnight airdrop 1000 --wallet alice
|
|
196
|
-
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=
|
|
198
|
+
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=Mr(r),{name:s,config:o}=Q({args:e});if(Le(o,{proofServer:k(e,"proof-server"),node:k(e,"node"),indexerWS:k(e,"indexer-ws")},s),s!=="undeployed")throw Error(`Airdrop is only available on the "undeployed" network (local devnet).
|
|
197
199
|
Current network: "${s}"
|
|
198
|
-
On preprod/preview, use a faucet or transfer from another wallet.`);let i=k(e,"wallet"),a=
|
|
200
|
+
On preprod/preview, use a faucet or transfer from another wallet.`);let i=k(e,"wallet"),a=D(e,"shielded")||i!==void 0&&i.startsWith("mn_shield-addr_"),c=Um(e,s,o,a);if(a)return Wm(e,c,n,s,o,t);return Bm(e,c,n,s,o,t)}function Fm(e){return e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_")}function Um(e,t,r,n){let s=k(e,"wallet");if(s!==void 0&&Fm(s))return Lm(s,t,r,n);let o=ae(s),i=ce(o);if(n){let a=Ct(r.networkId),c=Buffer.from(i.seed,"hex"),d=yr(c),l=Fc.encode(a,d).asString();return{kind:"wallet",raw:d,bech32m:l,walletPath:o}}return{kind:"address",address:i.addresses[t]}}function Lm(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.
|
|
199
201
|
Pass a shielded address (mn_shield-addr_...) or drop --shielded.
|
|
200
202
|
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}".
|
|
201
203
|
Expected prefix: ${o}
|
|
202
|
-
Got: ${e}`);if(n){let i=
|
|
203
|
-
`+
|
|
204
|
+
Got: ${e}`);if(n){let i=Ct(r.networkId),a;try{a=Fc.parse(e).decode(Mm,i)}catch(c){throw Error(`Invalid shielded address: ${c.message}`)}return{kind:"address",raw:a,bech32m:e}}return{kind:"address",address:e}}async function Bm(e,t,r,n,s,o){if(We(e))He();let i=t.address,a=Buffer.from(Qe,"hex");process.stderr.write(`
|
|
205
|
+
`+U("Airdrop")+`
|
|
204
206
|
|
|
205
207
|
`),process.stderr.write(C("Network",n)+`
|
|
206
208
|
`),process.stderr.write(C("From",g("genesis (seed 0x01)"))+`
|
|
207
|
-
`),process.stderr.write(C("To",
|
|
209
|
+
`),process.stderr.write(C("To",re(i,!0))+`
|
|
208
210
|
`),process.stderr.write(C("Amount",_(r+" NIGHT"))+`
|
|
209
211
|
`),process.stderr.write(`
|
|
210
|
-
`);let c=
|
|
212
|
+
`);let c=z("Starting genesis wallet...");try{let d=await Qt({seedBuffer:a,networkConfig:s,recipientAddress:i,amountNight:r,signal:o,onSync(l,u){if(u>0){let p=Math.round(l/u*100);c.update(`Syncing genesis wallet... ${p}%`)}},onDust(l){c.update(`Dust: ${l}`)},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(l){let u=Math.floor(l/1000),p=Math.floor(u/60).toString().padStart(2,"0"),m=(u%60).toString().padStart(2,"0");c.update(`Submitting and waiting for finalization... ${p}:${m} elapsed (typically 12 to 30s)`)},onSyncWarning(l,u){c.update(`Syncing genesis wallet... (${u}, retrying)`)}});if(c.stop("Transaction submitted"),D(e,"json")){I({txHash:d.txHash,amount:r,recipient:i,network:n});return}process.stdout.write(d.txHash+`
|
|
211
213
|
`),process.stderr.write(`
|
|
212
|
-
`+
|
|
214
|
+
`+lt(`Airdropped ${r} NIGHT to your wallet`,d.txHash)+`
|
|
213
215
|
`),process.stderr.write(`
|
|
214
216
|
`+V()+`
|
|
215
217
|
`),process.stderr.write(g(" Verify: midnight balance")+`
|
|
@@ -220,66 +222,66 @@ Got: ${e}`);if(n){let i=St(r.networkId),a;try{a=kc.parse(e).decode(hm,i)}catch(c
|
|
|
220
222
|
`)}catch(d){if(c.fail("Failed"),d instanceof Error&&d.message.toLowerCase().includes("dust"))throw Error(`${d.message}
|
|
221
223
|
|
|
222
224
|
On a fresh localnet, the minimum airdrop is ~1 NIGHT.
|
|
223
|
-
Try: midnight airdrop 1`);throw d}}async function
|
|
224
|
-
`+
|
|
225
|
+
Try: midnight airdrop 1`);throw d}}async function Wm(e,t,r,n,s,o){let i=Or(r);if(We(e))He();let a=Buffer.from(Qe,"hex"),c=Mc.unshieldedToken().raw,{raw:d,bech32m:l}=t;if(t.kind==="wallet")jt(t.walletPath,n,l);process.stderr.write(`
|
|
226
|
+
`+U("Shielded Airdrop")+`
|
|
225
227
|
|
|
226
228
|
`),process.stderr.write(C("Network",n)+`
|
|
227
229
|
`),process.stderr.write(C("From",g("genesis shielded (seed 0x01)"))+`
|
|
228
|
-
`),process.stderr.write(C("To",
|
|
230
|
+
`),process.stderr.write(C("To",re(l,!0))+`
|
|
229
231
|
`),process.stderr.write(C("Amount",_(r+" NIGHT (shielded)"))+`
|
|
230
232
|
`),process.stderr.write(`
|
|
231
|
-
`);let u=
|
|
233
|
+
`);let u=xe(),p=De(),m=z("Syncing genesis wallet...");try{let y=await ve().withFacade(a,s,async({bundle:f,state:h})=>{let w=h.shielded.balances[c]??0n;if(w<i){let P=Number(w)/1e6;throw Error(`Genesis wallet has insufficient shielded balance: ${P.toFixed(6)} NIGHT available, ${r} NIGHT requested`)}if(m.update("Checking dust..."),await Ze(f,(P)=>m.update(P)),o?.aborted)throw Error("Operation cancelled");m.update("Building shielded transaction...");let b=await f.facade.transferTransaction([{type:"shielded",outputs:[{type:c,amount:i,receiverAddress:d}]}],{shieldedSecretKeys:f.zswapSecretKeys,dustSecretKey:f.dustSecretKey},{ttl:new Date(Date.now()+3600000)});m.update("Signing...");let S=await f.facade.signRecipe(b,(P)=>f.keystore.signData(P));m.update("Generating ZK proof (this may take a few minutes)...");let v=await f.facade.finalizeRecipe(S),R=await fn(m,"Submitting and waiting for finalization (typically 12 to 30s)...",f.facade.submitTransaction(v));return String(R)},{syncMode:"full",requireStrictSync:!0,signal:o,onStatus:(f)=>m.update(f),onSyncProgress:(f,h)=>{if(h>0){let w=Math.min(Math.round(f/h*100),100);m.update(w>=100?"Syncing genesis wallet...":`Syncing genesis wallet... ${w}%`)}},onSyncDetail:(f)=>m.update(`Syncing genesis wallet... (waiting on: ${f})`)});if(m.stop("Transaction submitted"),D(e,"json")){I({txHash:y,amount:r,shieldedAddress:l,network:n,type:"shielded"});return}process.stdout.write(y+`
|
|
232
234
|
`),process.stderr.write(`
|
|
233
|
-
`+
|
|
235
|
+
`+lt(`Airdropped ${r} shielded NIGHT to your wallet`,y)+`
|
|
234
236
|
`),process.stderr.write(`
|
|
235
237
|
`+V()+`
|
|
236
238
|
`),process.stderr.write(g(" Verify: midnight balance --shielded")+`
|
|
237
239
|
|
|
238
|
-
`)}catch(y){throw m.fail("Failed"),y}finally{p(),u()}}var
|
|
240
|
+
`)}catch(y){throw m.fail("Failed"),y}finally{p(),u()}}var Bc=N(()=>{ut();$e();pe();Ue();yn();je();Nt();Ye();ht();he();qe()});var Kc={};fe(Kc,{default:()=>Hc});import*as jc from"@midnight-ntwrk/ledger-v8";import{MidnightBech32m as Wc,ShieldedAddress as jm}from"@midnight-ntwrk/wallet-sdk-address-format";async function Hc(e,t){$t(e);let r=e.subcommand,n=e.positionals[0];if(!r)throw Error(`Missing recipient address.
|
|
239
241
|
Usage: midnight transfer <to> <amount>
|
|
240
242
|
Example: midnight transfer mn_addr_undeployed1... 100
|
|
241
243
|
Example: midnight transfer alice 100`);if(!n)throw Error(`Missing amount.
|
|
242
244
|
Usage: midnight transfer <to> <amount>
|
|
243
|
-
Example: midnight transfer mn_addr_undeployed1... 100`);let s=
|
|
244
|
-
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function
|
|
245
|
-
`+
|
|
245
|
+
Example: midnight transfer mn_addr_undeployed1... 100`);let s=D(e,"shielded"),o=Hm(r,e,s);if(s)return Gm(e,o,n,t);return Km(e,o,n,t)}function Hm(e,t,r){if(e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_"))return e;let n=ae(e),s=ce(n),{name:o}=Q({args:t});if(r){let i=s.shieldedAddresses?.[o];if(!i)throw Error(`Wallet "${e}" has no shielded address for network "${o}".
|
|
246
|
+
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function Km(e,t,r,n){let s=Mr(r),o=ae(k(e,"wallet")),i=ce(o),a=Buffer.from(i.seed,"hex"),{name:c,config:d}=Q({args:e}),l=i.addresses[c];if(Le(d,{proofServer:k(e,"proof-server"),node:k(e,"node"),indexerWS:k(e,"indexer-ws")},c),process.stderr.write(`
|
|
247
|
+
`+U("Transfer")+`
|
|
246
248
|
|
|
247
249
|
`),process.stderr.write(C("Network",c)+`
|
|
248
|
-
`),process.stderr.write(C("From",
|
|
249
|
-
`),process.stderr.write(C("To",
|
|
250
|
+
`),process.stderr.write(C("From",re(l,!0))+`
|
|
251
|
+
`),process.stderr.write(C("To",re(t,!0))+`
|
|
250
252
|
`),process.stderr.write(C("Amount",_(s+" NIGHT"))+`
|
|
251
253
|
`),process.stderr.write(`
|
|
252
|
-
`),
|
|
254
|
+
`),We(e))He();let u=z("Starting wallet...");try{let p=await Qt({seedBuffer:a,networkConfig:d,recipientAddress:t,amountNight:s,signal:n,onSync(m,y){if(y>0){let f=Math.min(Math.round(m/y*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 y=Math.floor(m/1000),f=Math.floor(y/60).toString().padStart(2,"0"),h=(y%60).toString().padStart(2,"0");u.update(`Submitting and waiting for finalization... ${f}:${h} elapsed (typically 12 to 30s)`)},onSyncWarning(m,y){u.update(`Syncing wallet... (${y}, retrying)`)}});if(u.stop("Transaction submitted"),D(e,"json")){I({txHash:p.txHash,amount:s,recipient:t,network:c});return}process.stdout.write(p.txHash+`
|
|
253
255
|
`),process.stderr.write(`
|
|
254
|
-
`+
|
|
256
|
+
`+lt(`Transferred ${s} NIGHT`,p.txHash)+`
|
|
255
257
|
`),process.stderr.write(`
|
|
256
258
|
`+V()+`
|
|
257
259
|
`),process.stderr.write(g(" Verify: midnight balance")+`
|
|
258
260
|
|
|
259
|
-
`)}catch(p){throw u.fail("Failed"),p}}async function
|
|
261
|
+
`)}catch(p){throw u.fail("Failed"),p}}async function Gm(e,t,r,n){let s=Mr(r),o=Or(s),i=ae(k(e,"wallet")),a=ce(i),c=Buffer.from(a.seed,"hex"),{name:d,config:l}=Q({args:e});if(!hn(d,D(e,"force-shielded")))throw Error(wn(d));let u=a.addresses[d],p=Ct(l.networkId),m=jc.unshieldedToken().raw;Le(l,{proofServer:k(e,"proof-server"),node:k(e,"node"),indexerWS:k(e,"indexer-ws")},d);let y;try{y=Wc.parse(t).decode(jm,p)}catch(b){throw Error(`Invalid shielded address: ${b.message}
|
|
260
262
|
Expected a shielded address (mn_shield-addr_...) for network "${l.networkId}"`)}if(process.stderr.write(`
|
|
261
|
-
`+
|
|
263
|
+
`+U("Shielded Transfer")+`
|
|
262
264
|
|
|
263
265
|
`),process.stderr.write(C("Network",d)+`
|
|
264
|
-
`),process.stderr.write(C("To",
|
|
266
|
+
`),process.stderr.write(C("To",re(t,!0))+`
|
|
265
267
|
`),process.stderr.write(C("Amount",_(s+" NIGHT (shielded)"))+`
|
|
266
268
|
`),process.stderr.write(`
|
|
267
|
-
`),
|
|
268
|
-
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(w.update("Checking dust..."),await
|
|
269
|
+
`),We(e))He();let f=xe(),h=De(),w=z("Syncing wallet...");try{let b=await ve().withFacade(c,l,async({bundle:S,state:v})=>{let R=Wc.encode(p,v.shielded.address).asString();jt(i,d,R);let P=v.shielded.balances[m]??0n;if(P<o){let O=Number(P)/1e6;throw Error(`Insufficient shielded balance: ${O.toFixed(6)} NIGHT available, ${s} NIGHT requested.
|
|
270
|
+
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(w.update("Checking dust..."),await Ze(S,(O)=>w.update(O)),n?.aborted)throw Error("Operation cancelled");w.update("Building shielded transaction...");let Y=await S.facade.transferTransaction([{type:"shielded",outputs:[{type:m,amount:o,receiverAddress:y}]}],{shieldedSecretKeys:S.zswapSecretKeys,dustSecretKey:S.dustSecretKey},{ttl:new Date(Date.now()+3600000)});w.update("Signing...");let J=await S.facade.signRecipe(Y,(O)=>S.keystore.signData(O));w.update("Generating ZK proof (this may take a few minutes)...");let q=await S.facade.finalizeRecipe(J),M=await fn(w,"Submitting and waiting for finalization (typically 12 to 30s)...",S.facade.submitTransaction(q));return String(M)},{syncMode:"full",requireStrictSync:!0,signal:n,onStatus:(S)=>w.update(S),onSyncProgress:(S,v)=>{if(v>0){let R=Math.min(Math.round(S/v*100),100);w.update(R>=100?"Syncing wallet...":`Syncing wallet... ${R}%`)}},onSyncDetail:(S)=>w.update(`Syncing wallet... (waiting on: ${S})`)});if(w.stop("Transaction submitted"),D(e,"json")){I({txHash:b,amount:s,recipient:t,network:d,type:"shielded"});return}process.stdout.write(b+`
|
|
269
271
|
`),process.stderr.write(`
|
|
270
|
-
`+
|
|
272
|
+
`+lt(`Transferred ${s} shielded NIGHT`,b)+`
|
|
271
273
|
`),process.stderr.write(`
|
|
272
274
|
`+V()+`
|
|
273
275
|
`),process.stderr.write(g(" Verify: midnight balance --shielded")+`
|
|
274
276
|
|
|
275
|
-
`)}catch(b){throw w.fail("Failed"),b}finally{h(),f()}}var
|
|
277
|
+
`)}catch(b){throw w.fail("Failed"),b}finally{h(),f()}}var Gc=N(()=>{ut();$e();pe();Ue();qs();yn();Nt();Ye();ht();he();qe()});async function Jm(e,t){let r=await Ge(e,t,null);try{return await r.facade.dust.serializeState()}finally{await Oe(r)}}async function Jc(e,t,r,n={}){let s=Ke(e),i=await(n.repository??ve()).dust(e,r,{signal:n.signal,onProgress:n.onProgress}),a=await(n.buildBaseDust??Jm)(e,r),c=i.lastAppliedEventId>=0?Nr(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 Vc=N(()=>{xt();Ye();ht()});var qc={};fe(qc,{default:()=>zc});async function zc(e,t){let r=e.subcommand;if(!r||r!=="register"&&r!=="status"&&r!=="export")throw new W(`Missing or invalid subcommand.
|
|
276
278
|
Usage:
|
|
277
279
|
midnight dust register Register NIGHT UTXOs for dust generation
|
|
278
280
|
midnight dust status Check dust registration status
|
|
279
|
-
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=Q({args:e});if(
|
|
281
|
+
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=Q({args:e});if(Le(s,{proofServer:k(e,"proof-server"),node:k(e,"node"),indexerWS:k(e,"indexer-ws")},n),We(e))He();let o=D(e,"json"),i=ct(e);if(r==="export"){await Vm(mn(e),n,s,o,i,t);return}let a=ce(ae(k(e,"wallet"))),c=Buffer.from(a.seed,"hex"),d=a.addresses[n];if(r==="status"){let m=await zm(d,n,s.indexerWS,t);if(!m.isRegistered){qm(n,m,o,i);return}let y=!D(e,"no-cache");await Xm(c,s,m,o,i,y,t);return}$t(e);let l={},u=xe((m,y)=>l.current?.(m,y)),p=De();try{await Ym(c,s,o,t,l)}finally{p(),u()}}async function Vm(e,t,r,n,s,o){let i=z(`Reading dust events from ${t}...`);try{let a=await Jc(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){I({subcommand:"export",network:a.network,dustPublicKey:a.dustPublicKey,offset:a.offset,dustBalance:Gt(a.balance),eventCount:a.eventCount,fromCache:a.fromCache,partial:a.partial,snapshot:a.snapshot});return}if(process.stdout.write(a.snapshot+`
|
|
280
282
|
`),s)return;if(process.stderr.write(`
|
|
281
283
|
`+C("Network",a.network)+`
|
|
282
|
-
`),process.stderr.write(C("Dust balance",
|
|
284
|
+
`),process.stderr.write(C("Dust balance",Cr(a.balance))+`
|
|
283
285
|
`),process.stderr.write(C("Snapshot offset",String(a.offset))+`
|
|
284
286
|
`),a.partial)process.stderr.write(`
|
|
285
287
|
`+ee(_("⚠ Snapshot is INCOMPLETE — the sync did not reach the chain tip."))+`
|
|
@@ -287,12 +289,12 @@ Usage:
|
|
|
287
289
|
`+g(" Re-run `mn dust export` to resume from this checkpoint and finish.")+`
|
|
288
290
|
`);process.stderr.write(`
|
|
289
291
|
`+g("Restore with the wallet SDK dustSerializedState to skip the cold dust sync.")+`
|
|
290
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
291
|
-
`+
|
|
292
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function zm(e,t,r,n){process.stderr.write(`
|
|
293
|
+
`+U("Dust Status")+`
|
|
292
294
|
|
|
293
295
|
`),process.stderr.write(C("Network",t)+`
|
|
294
296
|
|
|
295
|
-
`);let s=
|
|
297
|
+
`);let s=z(`Checking registration on ${t}...`);try{let o=await Jt(e,r,(c,d)=>{if(d>0){let l=Math.min(Math.round(c/d*100),100);s.update(l>=100?"Checking registration...":`Checking registration... ${l}%`)}});if(n?.aborted)throw Error("Operation cancelled");let{registeredUtxos:i,unregisteredUtxos:a}=o;return s.stop("Registration checked"),{isRegistered:i>0,registeredUtxos:i,unregisteredUtxos:a}}catch(o){throw s.fail("Failed"),o}}function qm(e,t,r,n){let{registeredUtxos:s,unregisteredUtxos:o}=t,i=s+o;if(r){if(n){I({network:e,registered:!1,registeredUtxos:s,unregisteredUtxos:o});return}I({subcommand:"status",registered:!1,registeredUtxos:s,unregisteredUtxos:o,network:e});return}if(process.stdout.write(`registered=no
|
|
296
298
|
`),process.stdout.write(`registered_utxos=${s}
|
|
297
299
|
`),process.stdout.write(`unregistered_utxos=${o}
|
|
298
300
|
`),process.stderr.write(C("Registered",_("no"))+`
|
|
@@ -304,22 +306,22 @@ Usage:
|
|
|
304
306
|
`);process.stderr.write(`
|
|
305
307
|
`+V()+`
|
|
306
308
|
|
|
307
|
-
`)}async function
|
|
308
|
-
`+
|
|
309
|
+
`)}async function Ym(e,t,r,n,s){let o=t.networkId.toLowerCase();process.stderr.write(`
|
|
310
|
+
`+U("Dust Register")+`
|
|
309
311
|
|
|
310
312
|
`),process.stderr.write(C("Network",o)+`
|
|
311
313
|
|
|
312
|
-
`);let i=
|
|
314
|
+
`);let i=z("Syncing wallet...");if(s)s.current=(a,c)=>i.update(`Syncing wallet... (${c}, retrying)`);try{let{result:a,dustBal:c}=await ve().withFacade(e,t,async({bundle:d,state:l})=>{if(n?.aborted)throw Error("Operation cancelled");i.update("Checking dust status...");let u=await Ze(d,(m)=>i.update(m),l);if(n?.aborted)throw Error("Operation cancelled");let p=await Ha(d);return{result:u,dustBal:p.dust.balance(new Date)}},{syncMode:"lite",requireStrictSync:!0,signal:n,onStatus:(d)=>i.update(d),onSyncProgress:(d,l)=>{if(l>0){let u=Math.min(Math.round(d/l*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:Gt(c)};if(a.txHash)d.txHash=a.txHash;I(d);return}process.stdout.write(c.toString()+`
|
|
313
315
|
`),process.stderr.write(`
|
|
314
|
-
`+
|
|
316
|
+
`+lt(a.alreadyAvailable?`Dust tokens already available: ${Cr(c)}`:`Dust tokens available: ${Cr(c)}`)+`
|
|
315
317
|
|
|
316
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
318
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Xm(e,t,r,n,s,o,i){let a=t.networkId.toLowerCase(),c=z(`Reading dust events from ${a}...`);try{let d=await ve().dust(e,t,{forceFresh:!o,signal:i,onStatus:(p)=>c.update(p)});c.stop(d.fromCache&&d.eventsApplied===0?"Cache up to date":"Dust events applied");let{registeredUtxos:l,unregisteredUtxos:u}=r;if(n){if(s){I({network:a,registered:!0,registeredUtxos:l,unregisteredUtxos:u,dustBalance:Gt(d.balance),dustAvailable:d.availableCoins>0});return}I({subcommand:"status",registered:!0,registeredUtxos:l,unregisteredUtxos:u,dustBalance:Gt(d.balance),dustAvailable:d.availableCoins>0,eventsApplied:d.eventsApplied,ownedUtxos:d.ownedUtxoCount,cached:d.fromCache,network:a});return}if(process.stdout.write(`registered=yes
|
|
317
319
|
`),process.stdout.write(`dust=${d.balance}
|
|
318
320
|
`),process.stdout.write(`registered_utxos=${l}
|
|
319
321
|
`),process.stdout.write(`unregistered_utxos=${u}
|
|
320
322
|
`),process.stderr.write(C("Registered",_("yes"))+`
|
|
321
323
|
`),process.stderr.write(C("UTXOs",`${l} registered, ${u} unregistered`)+`
|
|
322
|
-
`),process.stderr.write(C("Dust Balance",_(
|
|
324
|
+
`),process.stderr.write(C("Dust Balance",_(Cr(d.balance)))+`
|
|
323
325
|
`),process.stderr.write(C("Dust Available",d.availableCoins>0?"yes":"no")+`
|
|
324
326
|
`),process.stderr.write(C("Events applied",d.eventsApplied.toString()+(d.fromCache?" (delta)":""))+`
|
|
325
327
|
`),u>0)process.stderr.write(`
|
|
@@ -327,21 +329,28 @@ Usage:
|
|
|
327
329
|
`);process.stderr.write(`
|
|
328
330
|
`+V()+`
|
|
329
331
|
|
|
330
|
-
`)}catch(d){throw c.fail("Failed"),d}}var
|
|
331
|
-
`)}else if(n){if(
|
|
332
|
-
`)}else{if(
|
|
333
|
-
`)}}var
|
|
334
|
-
Valid keys: ${
|
|
335
|
-
Valid keys: ${
|
|
336
|
-
`)}else if(t==="unset"){
|
|
337
|
-
`)}else{let n=e.positionals[1];if(n===void 0)throw new
|
|
338
|
-
Usage: midnight config set ${r} <value>`);
|
|
339
|
-
`)}}var
|
|
332
|
+
`)}catch(d){throw c.fail("Failed"),d}}var Yc=N(()=>{Fe();ut();$e();gn();pe();Ue();Ye();Nt();xr();Vc();ht();he();qe()});var Zc={};fe(Zc,{default:()=>Xc});async function Xc(e){if(e.subcommand!=="clear")throw new W("Usage: midnight cache clear [--network <name>] [--wallet <name|file>]");let r=k(e,"wallet"),n=k(e,"network"),s=D(e,"json");if(r){let o=ae(r),i=ce(o),{name:a}=Q({args:e}),c=i.addresses[a];Je(c,a);let d=Ke(Buffer.from(i.seed,"hex"));pt(a,d),_n(a,d);let l=hc(Buffer.from(i.seed,"hex"));if(On(a,l),s){I({action:"clear",scope:"wallet",wallet:r,network:a});return}process.stderr.write(B("✓")+` Cache cleared for wallet "${r}" on ${a}
|
|
333
|
+
`)}else if(n){if(Je(void 0,n),pt(n),_n(n),On(n),s){I({action:"clear",scope:"network",network:n});return}process.stderr.write(B("✓")+` Cache cleared for network "${n}"
|
|
334
|
+
`)}else{if(Je(),pt(),_n(),On(),s){I({action:"clear",scope:"all"});return}process.stderr.write(B("✓")+` Cache cleared
|
|
335
|
+
`)}}var Qc=N(()=>{Fe();At();xt();yo();fo();$e();pe()});var td={};fe(td,{default:()=>ed});async function ed(e){let t=e.subcommand;if(!t||!["get","set","unset"].includes(t))throw new W(`Usage: midnight config <get|set|unset> <key> [value]
|
|
336
|
+
Valid keys: ${Ls().join(", ")}`);let r=e.positionals[0];if(!r)throw new W(`Missing config key.
|
|
337
|
+
Valid keys: ${Ls().join(", ")}`);if(t==="get"){let n=Us(r);if(D(e,"json")){I({action:"get",key:r,value:n});return}process.stdout.write(n+`
|
|
338
|
+
`)}else if(t==="unset"){ea(r);let n=r==="network"?"(default)":"(removed)";if(D(e,"json")){I({action:"unset",key:r,value:n});return}process.stderr.write(B("✓")+` ${r} ${n}
|
|
339
|
+
`)}else{let n=e.positionals[1];if(n===void 0)throw new W(`Missing value for config set.
|
|
340
|
+
Usage: midnight config set ${r} <value>`);Qi(r,n);let s=r==="blockfrost-project-id"?Us(r):n;if(D(e,"json")){I({action:"set",key:r,value:s});return}process.stderr.write(B("✓")+` ${r} = ${s}
|
|
341
|
+
`)}}var rd=N(()=>{Fe();Wt()});import{execSync as Mn}from"child_process";import{existsSync as nd,mkdirSync as Zm,readFileSync as Qm,writeFileSync as sd}from"fs";import{homedir as eg}from"os";import{join as Co}from"path";function Ln(){try{return Mn("docker compose version",{...Un,timeout:1e4}).trim()}catch{try{throw Mn("docker --version",{...Un,timeout:5000}),Error(`Docker Compose v2 is required.
|
|
340
342
|
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.
|
|
341
|
-
Install Docker from https://docs.docker.com/get-docker/`)}}}function
|
|
342
|
-
`)
|
|
343
|
+
Install Docker from https://docs.docker.com/get-docker/`)}}}function Bn(){if(nd(ko)&&nd(Fn)&&Qm(ko,"utf-8").trim()===od)return!1;return Zm(Eo,{recursive:!0,mode:me}),sd(Fn,sg,"utf-8"),sd(ko,od,"utf-8"),!0}function it(e){return Mn(`docker compose -f "${Fn}" ${e}`,Un)}function ig(e){let t=[];for(let r of e.split(`
|
|
344
|
+
`)){if(!r.trim())continue;try{let n=JSON.parse(r),s=n.Service??"unknown";t.push({name:s,state:n.State??"unknown",health:n.Health??"",port:og[s]??"",image:n.Image??""})}catch{}}return t}function Rt(){try{return ig(it("ps -a --format json"))}catch{return[]}}function ag(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Wn(e=120000,t=3000){let r=Date.now()+e;while(Date.now()<r){let n=Rt();if(n.length===3&&n.every((o)=>o.state==="running")){if(n.every((i)=>i.health==="healthy"||i.health===""))return!0}ag(t)}return!1}function id(e){if(e.includes("Cannot connect to the Docker daemon"))return`Docker is installed but not running.
|
|
345
|
+
Start Docker (Docker Desktop on macOS and Windows), then run "midnight localnet up" again.`;if(e.includes("is already in use by container"))return`Container name conflict — containers with the same names already exist
|
|
346
|
+
`+`(likely from a previous midnight-local-network setup).
|
|
347
|
+
|
|
348
|
+
Run "midnight localnet clean" to remove them, then try again.`;if(e.includes("address already in use")||e.includes("port is already allocated")){let t=/(?:Bind for [^\s]*:|listen tcp[46]? [^\s]*:)(\d+)/.exec(e)?.[1];return`Port conflict — ${t?`port ${t} is`:"a port the local network needs is"} taken by another container or program.
|
|
349
|
+
The local network uses 9944 (node), 8088 (indexer) and 6300 (proof server).
|
|
350
|
+
|
|
351
|
+
Free the port, then run "midnight localnet up" again.`}return}function xo(){return Fn}function ad(){let e=[];for(let t of cg)try{Mn(`docker rm -f "${t}"`,{...Un,timeout:1e4}),e.push(t)}catch{}return e}var od="3.0.6",tg="midnightntwrk/midnight-node:1.0.0",rg="midnightntwrk/indexer-standalone:4.3.3",ng="midnightntwrk/proof-server:8.1.0",Eo,Fn,ko,sg,Un,og,cg;var Ao=N(()=>{Eo=Co(eg(),ie,Li),Fn=Co(Eo,"compose.yml"),ko=Co(Eo,".version"),sg=`services:
|
|
343
352
|
proof-server:
|
|
344
|
-
image: '${
|
|
353
|
+
image: '${ng}'
|
|
345
354
|
container_name: "proof-server"
|
|
346
355
|
# Self-heal across Docker Desktop restarts and transient stops. Without this,
|
|
347
356
|
# a stopped node/proof-server never comes back while the indexer (below) does,
|
|
@@ -352,7 +361,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function Ln(){if(jc(
|
|
|
352
361
|
- "6300:6300"
|
|
353
362
|
|
|
354
363
|
indexer:
|
|
355
|
-
image: '${
|
|
364
|
+
image: '${rg}'
|
|
356
365
|
container_name: "indexer"
|
|
357
366
|
# unless-stopped covers two cases: (1) indexer >=4.3.x runs an SPO sub-indexer
|
|
358
367
|
# that queries block #1 at startup and exits the whole process if it isn't there
|
|
@@ -388,7 +397,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function Ln(){if(jc(
|
|
|
388
397
|
condition: service_started
|
|
389
398
|
|
|
390
399
|
node:
|
|
391
|
-
image: '${
|
|
400
|
+
image: '${tg}'
|
|
392
401
|
container_name: "node"
|
|
393
402
|
# Self-heal across Docker Desktop restarts / transient stops (see proof-server).
|
|
394
403
|
restart: unless-stopped
|
|
@@ -402,38 +411,34 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function Ln(){if(jc(
|
|
|
402
411
|
start_period: 5s
|
|
403
412
|
environment:
|
|
404
413
|
CFG_PRESET: "dev"
|
|
405
|
-
`,
|
|
406
|
-
`)}async function
|
|
407
|
-
`);let r=
|
|
414
|
+
`,Un={encoding:"utf-8",timeout:30000};og={node:"9944",indexer:"8088","proof-server":"6300"};cg=["node","indexer","proof-server"]});async function cd(e,t={}){let r=t.timeoutMs??30000,n=t.pollIntervalMs??1000,s=Date.now()+r;while(Date.now()<s){try{let o=await qt({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 dd=N(()=>{xn()});async function ld(e,t,r={}){let n=r.timeoutMs??30000,s=r.pollIntervalMs??1000,o=Date.now()+n;while(Date.now()<o){try{if((await Jt(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 ud=N(()=>{xr()});async function pd(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 wd={};fe(wd,{default:()=>hd});import{spawn as fd}from"child_process";import{existsSync as dg,rmSync as lg}from"node:fs";import{resolve as ug}from"node:path";function pg(e){return md.includes(e)}function gd(e){let t=[];for(let r of e){let n=r.state==="running"?B:le,s=r.health?` (${r.health})`:"",o=r.port?`:${r.port}`:"",i=r.image?` ${g(r.image)}`:"";if(t.push(` ${r.name.padEnd(16)}${n(r.state)}${g(s)}${g(o)}`),i)t.push(i)}return t.join(`
|
|
415
|
+
`)}async function fg(e){if(Bn())process.stderr.write(g(` Wrote compose.yml to ${xo()}`)+`
|
|
416
|
+
`);let r=z("Starting local network...");try{if(it("up -d"),r.update("Waiting for services to be healthy..."),!Wn(120000))r.stop(ee("Services started but not all healthy yet")),process.stderr.write(`
|
|
408
417
|
`+g(" Tip: run ")+_("midnight localnet logs")+g(" to check for errors")+`
|
|
409
|
-
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() =>
|
|
418
|
+
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() => dd());await Promise.resolve().then(() => ud());await Promise.resolve();await Promise.resolve().then(() => Ue());await Promise.resolve().then(() => je());await Promise.resolve();let u=Bs("undeployed");await cd(u.node,{timeoutMs:30000}),r.update("Waiting for indexer to ingest genesis state...");let p=Se(Buffer.from(Qe,"hex"),"undeployed");await ld(u.indexerWS,p,{timeoutMs:30000}),r.update("Waiting for proof server..."),await pd(u.proofServer,{timeoutMs:30000}),r.stop("Local network is running")}catch(o){r.stop(ee("Services running but chain/indexer/proof-server not fully ready yet")),process.stderr.write(`
|
|
410
419
|
`+g(" Tip: give it a few more seconds then retry. Run ")+_("midnight localnet logs")+g(" if this persists.")+`
|
|
411
|
-
`)}}}catch(s){
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
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.
|
|
415
|
-
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=xt();if(e){D({subcommand:"up",services:n.map((s)=>({name:s.name,state:s.state,port:s.port,health:s.health,image:s.image}))});return}if(n.length>0)process.stderr.write(`
|
|
416
|
-
`+Qc(n)+`
|
|
420
|
+
`)}}}catch(s){r.fail("Failed to start local network");let o=s instanceof Error?id(s.message):void 0;if(o!==void 0)throw Error(o);throw s}let n=Rt();if(e){I({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(`
|
|
421
|
+
`+gd(n)+`
|
|
417
422
|
`);for(let s of n)process.stdout.write(`${s.name}=${s.state}:${s.port}
|
|
418
423
|
`);process.stderr.write(`
|
|
419
424
|
`+g(" Next: ")+_("midnight wallet generate dev --network undeployed")+`
|
|
420
|
-
`)}async function
|
|
421
|
-
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function
|
|
422
|
-
`+
|
|
425
|
+
`)}async function mg(e){let t=z("Stopping local network...");try{if(it("stop"),t.stop("Local network stopped (containers preserved)"),e){I({subcommand:"stop",status:"stopped"});return}}catch(r){throw t.fail("Failed to stop local network"),r}}async function gg(e){let t=z("Tearing down local network...");try{it("down --volumes");await Promise.resolve().then(() => At());await Promise.resolve().then(() => xt());Je(void 0,"undeployed"),pt("undeployed");let s=hg();if(t.stop("Local network removed (containers, networks, volumes, caches)"),e){I({subcommand:"down",status:"removed",cachesCleared:!0,dappLevelDbWiped:s});return}if(s)process.stderr.write(g(" Also cleared dapp leveldb at ./midnight-level-db (private state from old chain)")+`
|
|
426
|
+
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function hg(){let e=ug(process.cwd(),"midnight-level-db");if(!dg(e))return!1;try{return lg(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function wg(e){let t=Rt();if(e){I({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(`
|
|
427
|
+
`+U("Localnet Status")+`
|
|
423
428
|
|
|
424
429
|
`),process.stderr.write(g(" No services running.")+`
|
|
425
430
|
`),process.stderr.write(g(" Run ")+_("midnight localnet up")+g(" to start.")+`
|
|
426
431
|
|
|
427
432
|
`);return}process.stderr.write(`
|
|
428
|
-
`+
|
|
433
|
+
`+U("Localnet Status")+`
|
|
429
434
|
|
|
430
|
-
`),process.stderr.write(
|
|
435
|
+
`),process.stderr.write(gd(t)+`
|
|
431
436
|
`),process.stderr.write(`
|
|
432
437
|
`+V()+`
|
|
433
438
|
|
|
434
439
|
`);for(let r of t)process.stdout.write(`${r.name}=${r.state}:${r.port}
|
|
435
|
-
`)}async function
|
|
436
|
-
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",l)})}let s=
|
|
440
|
+
`)}async function yg(e){let t=z("Removing conflicting containers...");try{try{it("down")}catch{}let r=ad();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){I({subcommand:"clean",status:"cleaned",removed:r});return}}catch(r){throw t.fail("Failed to clean up"),r}}async function Sg(e){let t=xo(),r=k(e,"tail"),n=D(e,"json");if(r!==void 0||n){let o=r??"200",i=fd("docker",["compose","-f",t,"logs","--tail",o,"--no-color"],{stdio:["ignore","pipe","pipe"]}),a="",c="";return i.stdout.on("data",(d)=>{a+=d.toString()}),i.stderr.on("data",(d)=>{c+=d.toString()}),new Promise((d,l)=>{i.on("close",(u)=>{if(u!==0&&u!==null){l(Error(`docker compose logs exited with code ${u}: ${c.trim()}`));return}if(n)I({tail:Number(o),lines:a.split(`
|
|
441
|
+
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",l)})}let s=fd("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 hd(e){let t=e.subcommand;if(!t||!pg(t))throw new W(`Usage: midnight localnet <${md.join("|")}>
|
|
437
442
|
|
|
438
443
|
Subcommands:
|
|
439
444
|
up Start the local network
|
|
@@ -443,22 +448,22 @@ Subcommands:
|
|
|
443
448
|
logs Stream service logs
|
|
444
449
|
clean Remove conflicting containers
|
|
445
450
|
|
|
446
|
-
Example: midnight localnet up`);
|
|
447
|
-
`+
|
|
451
|
+
Example: midnight localnet up`);Ln();let r=D(e,"json");switch(process.stderr.write(`
|
|
452
|
+
`+U("Localnet")+`
|
|
448
453
|
|
|
449
|
-
`),t){case"up":return
|
|
454
|
+
`),t){case"up":return fg(r);case"stop":return mg(r);case"down":return gg(r);case"status":return wg(r);case"logs":return Sg(e);case"clean":return yg(r)}}var md;var yd=N(()=>{Fe();Ao();he();qe();md=["up","stop","down","status","logs","clean"]});var kd={};fe(kd,{default:()=>vd});import*as bd from"fs";import*as To from"path";import{homedir as bg}from"os";import{generateMnemonic as vg,mnemonicToSeedSync as Sd,mnemonicToEntropy as kg,validateMnemonic as Cg}from"@scure/bip39";import{wordlist as No}from"@scure/bip39/wordlists/english.js";async function vd(e){let t=e.subcommand;switch(t){case"generate":return Eg(e);case"list":case"ls":return xg(e);case"use":return Ag(e);case"info":return Tg(e);case"remove":case"rm":return Ng(e);case"seed":return Rg(e);default:throw new W(`Unknown wallet subcommand: "${t??"(none)"}"
|
|
450
455
|
Available: generate, list, use, info, remove, seed
|
|
451
|
-
Run "midnight help wallet" for usage.`)}}async function
|
|
452
|
-
Usage: midnight wallet generate <name> [--network <name>]`);if(!
|
|
453
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=
|
|
454
|
-
Use --force to overwrite.`);let a,c;if(n!==void 0){let f=n.replace(/^0x/,"");if(f.length!==64||!/^[0-9a-fA-F]+$/.test(f))throw Error("Seed must be a 64-character hex string (32 bytes)");a=Buffer.from(f,"hex")}else if(s!==void 0){if(!
|
|
456
|
+
Run "midnight help wallet" for usage.`)}}async function Eg(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
457
|
+
Usage: midnight wallet generate <name> [--network <name>]`);if(!yt(t))throw Error(`Invalid wallet name: "${t}"
|
|
458
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=Pe({args:e}),n=k(e,"seed"),s=k(e,"mnemonic");if(n!==void 0&&s!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let o=To.join(bg(),ie,Zr),i=To.join(o,`${t}.json`);if(bd.existsSync(i)&&!D(e,"force"))throw Error(`Wallet "${t}" already exists: ${i}
|
|
459
|
+
Use --force to overwrite.`);let a,c;if(n!==void 0){let f=n.replace(/^0x/,"");if(f.length!==64||!/^[0-9a-fA-F]+$/.test(f))throw Error("Seed must be a 64-character hex string (32 bytes)");a=Buffer.from(f,"hex")}else if(s!==void 0){if(!Cg(s,No))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");c=s,a=Buffer.from(Sd(c))}else c=vg(No,256),a=Buffer.from(Sd(c));let d=vt(a),l=wr(a),u=d[r],p={seed:a.toString("hex"),addresses:d,shieldedAddresses:l,createdAt:new Date().toISOString()};if(c)p.mnemonic=c;let m=ln(p,i);if(Js(t),D(e,"json")){let f={name:t,addresses:d,shieldedAddresses:l,activeAddress:u,activeNetwork:r,seed:a.toString("hex"),file:m,createdAt:p.createdAt,active:!0};if(c)f.mnemonic=c;I(f);return}process.stdout.write(u+`
|
|
455
460
|
`),process.stderr.write(`
|
|
456
|
-
`+
|
|
461
|
+
`+U("Wallet Generated")+`
|
|
457
462
|
|
|
458
463
|
`),process.stderr.write(C("Name",t)+`
|
|
459
464
|
`),process.stderr.write(C("Network",r)+`
|
|
460
|
-
`),process.stderr.write(C("Address",
|
|
461
|
-
`);let y=l[r];if(y)process.stderr.write(C("Shielded",
|
|
465
|
+
`),process.stderr.write(C("Address",re(u))+`
|
|
466
|
+
`);let y=l[r];if(y)process.stderr.write(C("Shielded",re(y))+`
|
|
462
467
|
`);if(process.stderr.write(C("File",m)+`
|
|
463
468
|
`),process.stderr.write(C("Active","yes")+`
|
|
464
469
|
`),process.stderr.write(`
|
|
@@ -471,29 +476,29 @@ Use --force to overwrite.`);let a,c;if(n!==void 0){let f=n.replace(/^0x/,"");if(
|
|
|
471
476
|
`),process.stderr.write(V()+`
|
|
472
477
|
`),process.stderr.write(g(" Next: midnight wallet list | midnight balance")+`
|
|
473
478
|
|
|
474
|
-
`),process.stderr.write(
|
|
475
|
-
`)}async function
|
|
479
|
+
`),process.stderr.write(B("✓")+` Wallet saved
|
|
480
|
+
`)}async function xg(e){let t=Vs(),r=Pe({args:e});if(D(e,"json")){if(ct(e)){I({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}I({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(`
|
|
476
481
|
No wallets found.
|
|
477
482
|
`),process.stderr.write(g(" Create one: midnight wallet generate <name> --network <name>")+`
|
|
478
483
|
|
|
479
484
|
`);return}process.stderr.write(`
|
|
480
|
-
`+
|
|
485
|
+
`+U("Wallets")+`
|
|
481
486
|
|
|
482
487
|
`);let n=Math.max(...t.map((a)=>a.name.length)),s=19,o=19,i=" ".repeat(n-4);process.stderr.write(` ${g("name")}${i} ${g("unshielded".padEnd(s))} ${g("shielded")}
|
|
483
|
-
`);for(let a of t){let c=a.isActive?
|
|
488
|
+
`);for(let a of t){let c=a.isActive?B("●"):" ",d=a.isActive?_(G(a.name)):G(a.name),l=" ".repeat(n-a.name.length),u=a.addresses[r]??"(unknown)",p=a.shieldedAddresses?.[r],m=p?re(p,!0):g("—".padEnd(o));process.stderr.write(` ${c} ${d}${l} ${re(u,!0)} ${m}
|
|
484
489
|
`)}process.stderr.write(`
|
|
485
490
|
`+V()+`
|
|
486
491
|
`),process.stderr.write(g(` ● = active wallet · network: ${r} · details: midnight wallet info <name>`)+`
|
|
487
492
|
|
|
488
|
-
`)}async function
|
|
489
|
-
Usage: midnight wallet use <name>`);if(
|
|
490
|
-
`)}async function
|
|
493
|
+
`)}async function Ag(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
494
|
+
Usage: midnight wallet use <name>`);if(Js(t),D(e,"json")){I({wallet:t,active:!0});return}process.stderr.write(B("✓")+` Active wallet set to "${t}"
|
|
495
|
+
`)}async function Tg(e){let t=k(e,"wallet")??e.positionals[0]??Ht(),r=ae(t),n=ce(r),s=t===Ht(),o=Pe({args:e}),i=n.addresses[o];if(D(e,"json")){if(ct(e)){I({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;I(c);return}process.stdout.write(i+`
|
|
491
496
|
`),process.stderr.write(`
|
|
492
|
-
`+
|
|
497
|
+
`+U(`Wallet: ${t}`)+`
|
|
493
498
|
|
|
494
|
-
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],l=d===o,u=n.addresses[d],p=n.shieldedAddresses?.[d],m=l?_(
|
|
495
|
-
`),process.stderr.write(` ${g("unshielded")} ${
|
|
496
|
-
`),p)process.stderr.write(` ${g("shielded ")} ${
|
|
499
|
+
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],l=d===o,u=n.addresses[d],p=n.shieldedAddresses?.[d],m=l?_(G(d))+g(" (active)"):d;if(process.stderr.write(` ${m}
|
|
500
|
+
`),process.stderr.write(` ${g("unshielded")} ${re(u)}
|
|
501
|
+
`),p)process.stderr.write(` ${g("shielded ")} ${re(p)}
|
|
497
502
|
`);else process.stderr.write(` ${g("shielded ")} ${g("(unavailable)")}
|
|
498
503
|
`);if(c<a.length-1)process.stderr.write(`
|
|
499
504
|
`)}process.stderr.write(`
|
|
@@ -501,17 +506,17 @@ Usage: midnight wallet use <name>`);if(Ks(t),I(e,"json")){D({wallet:t,active:!0}
|
|
|
501
506
|
|
|
502
507
|
`),process.stderr.write(` ${g("created")} ${n.createdAt}
|
|
503
508
|
`),process.stderr.write(` ${g("file ")} ${r}
|
|
504
|
-
`),process.stderr.write(` ${g("active ")} ${s?
|
|
509
|
+
`),process.stderr.write(` ${g("active ")} ${s?B("yes"):"no"}
|
|
505
510
|
|
|
506
|
-
`)}async function
|
|
507
|
-
Usage: midnight wallet remove <name>`);if(
|
|
508
|
-
`)}async function
|
|
509
|
-
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(
|
|
511
|
+
`)}async function Ng(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
512
|
+
Usage: midnight wallet remove <name>`);if(ca(t),D(e,"json")){I({wallet:t,removed:!0});return}process.stderr.write(B("✓")+` Wallet "${t}" removed
|
|
513
|
+
`)}async function Rg(e){let t=k(e,"wallet")??e.positionals[0]??Ht(),r=ae(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=D(e,"entropy"),i;if(o){if(!s.mnemonic)throw Error(`Wallet "${t}" has no mnemonic on file — cannot derive BIP-39 entropy.
|
|
514
|
+
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(kg(s.mnemonic,No)).toString("hex")}if(D(e,"json")){let c={name:t,seed:s.seed};if(s.mnemonic)c.mnemonic=s.mnemonic;if(i)c.entropy=i;I(c);return}if(process.stderr.write(`
|
|
510
515
|
`),process.stderr.write(ee(_(" ⚠ WARNING: This will display your wallet seed and mnemonic."))+`
|
|
511
516
|
`),process.stderr.write(ee(" Anyone with this seed can access your funds.")+`
|
|
512
517
|
`),process.stderr.write(ee(" Never share it. Never paste it into a website.")+`
|
|
513
518
|
`),process.stderr.write(`
|
|
514
|
-
`),!await
|
|
519
|
+
`),!await Dg(" Show seed? (y/N) ")){process.stderr.write(g(" Cancelled.")+`
|
|
515
520
|
|
|
516
521
|
`);return}if(process.stdout.write(s.seed+`
|
|
517
522
|
`),process.stderr.write(`
|
|
@@ -524,53 +529,53 @@ Usage: midnight wallet remove <name>`);if(ea(t),I(e,"json")){D({wallet:t,removed
|
|
|
524
529
|
`),process.stderr.write(g(" Note: seed and entropy derive DIFFERENT Midnight wallets from the")+`
|
|
525
530
|
`),process.stderr.write(g(" same mnemonic. Use the value your target project accepts.")+`
|
|
526
531
|
`);process.stderr.write(`
|
|
527
|
-
`)}function
|
|
528
|
-
`)[0];return{status:"unknown",latencyMs:0,lastChecked:t,notes:n}}}function
|
|
529
|
-
`)[0]}async function
|
|
532
|
+
`)}function Dg(e){return new Promise((t)=>{let r=wi("readline"),n=r.createInterface({input:process.stdin,output:process.stderr});n.question(e,(s)=>{n.close(),t(s.trim().toLowerCase()==="y")})})}var Cd=N(()=>{Fe();je();pe();$e();he()});var Dd={};fe(Dd,{default:()=>Rd});function Do(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 Ro(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 jn(e){let t=`${Qr}${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 $g(e){let t=k(e,"network");if(t)return t;try{await Promise.resolve().then(() => Wt());let n=Re();if(n.network&&Ne(n.network))return n.network}catch{}return}async function Kn(e,t={}){let r=new AbortController,n=setTimeout(()=>r.abort(),Pg),s=Date.now();try{return{response:await fetch(e,{...t,signal:r.signal}),latencyMs:Date.now()-s}}finally{clearTimeout(n)}}function Td(e,t){try{ye(e);return}catch(r){let n=r instanceof Lt?"Needs a Blockfrost project id: midnight config set blockfrost-project-id <project id>":r.message.split(`
|
|
533
|
+
`)[0];return{status:"unknown",latencyMs:0,lastChecked:t,notes:n}}}function Nd(e,t){return fr(e,t)?.message.split(`
|
|
534
|
+
`)[0]}async function Og(e){let t=new Date().toISOString(),r=Td(e,t);if(r)return r;try{let{response:n,latencyMs:s}=await Kn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"{ block { height } }"})});if(!n.ok){let a=Nd(e,n.status);if(a)return{status:"down",latencyMs:s,lastChecked:t,notes:a};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 o=await n.json();if(!o?.data)return{status:"down",latencyMs:s,lastChecked:t,notes:"No data field"};let i=o.data?.block?.height;return{status:s>Hn?"degraded":"up",latencyMs:s,lastChecked:t,...i!==void 0?{blockHeight:i}:{},...s>Hn?{notes:`Slow (${s}ms)`}:{}}}catch(n){return{status:"down",latencyMs:0,lastChecked:t,notes:n.message}}}async function Mg(e){let t=new Date().toISOString(),r=Td(e,t);if(r)return r;let n=e.replace(/^wss:/,"https:").replace(/^ws:/,"http:");try{let{response:s,latencyMs:o}=await Kn(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"system_health",params:[]})});if(!s.ok){let p=Nd(e,s.status);if(p)return{status:"down",latencyMs:o,lastChecked:t,notes:p};if(s.status===403)return{status:"degraded",latencyMs:o,lastChecked:t,notes:"HTTP 403 — likely WAF blocking"};return{status:"down",latencyMs:o,lastChecked:t,notes:`HTTP ${s.status}`}}let a=(await s.json())?.result;if(!a)return{status:"down",latencyMs:o,lastChecked:t,notes:"No result in response"};let c=a.peers??0,d=a.isSyncing??!1,l="up",u;if(d)l="degraded",u="Node is syncing";else if(c===0)l="degraded",u="No peers";return{status:l,latencyMs:o,lastChecked:t,peers:c,isSyncing:d,...u?{notes:u}:{}}}catch(s){return{status:"down",latencyMs:0,lastChecked:t,notes:s.message}}}async function Fg(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 Kn(e);if(!r.ok)return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`};return{status:n>xd?"degraded":"up",latencyMs:n,lastChecked:t,...n>xd?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function Ug(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 Kn(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>Hn?"degraded":"up",latencyMs:n,lastChecked:t,...n>Hn?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function Ad(e){if(!Ne(e))return{};let t=dn(e,Ks(e)),r=Ig[e];if(!r)return{};let[n,s,o,i]=await Promise.all([Og(t.indexer),Mg(t.node),Fg(r.faucet),Ug(r.explorer)]);return{indexer:n,rpc:s,faucet:o,explorer:i}}function Lg(e,t,r){process.stderr.write(`
|
|
530
535
|
`+_(e)+`
|
|
531
536
|
`),process.stderr.write(g(" "+"─".repeat(62))+`
|
|
532
|
-
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(
|
|
533
|
-
`)}else if(i){let c=
|
|
534
|
-
`)}}}function
|
|
535
|
-
`+
|
|
537
|
+
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(_g[s]??s).padEnd(18);if(o){let c=Ed[o.status]??g("—"),d=o.latencyMs>0?g(` ${o.latencyMs}ms`):"",l=o.notes?g(` — ${o.notes}`):"",u="";if(i&&i.status!==o.status&&i.status!=="unknown")u=g(` (canary: ${i.status}${i.lastChecked?" "+Do(i.lastChecked):""})`);process.stderr.write(` ${kr(a)}${c}${d}${l}${u}
|
|
538
|
+
`)}else if(i){let c=Ed[i.status]??g("—"),d=i.latencyMs>0?g(` ${i.latencyMs}ms`):"",l=i.lastChecked?g(` (${Do(i.lastChecked)})`):"",u=i.notes?g(` — ${i.notes}`):"";process.stderr.write(` ${kr(a)}${c}${d}${l}${u}
|
|
539
|
+
`)}}}function Bg(e,t){let r=t?e.filter((n)=>n.affects.toLowerCase().includes(t.toLowerCase())):e;if(r.length===0)return;process.stderr.write(`
|
|
540
|
+
`+U("Known Issues")+`
|
|
536
541
|
|
|
537
|
-
`);for(let n of r)process.stderr.write(` ${
|
|
542
|
+
`);for(let n of r)process.stderr.write(` ${le(n.id.padEnd(28))}${n.summary}
|
|
538
543
|
`),process.stderr.write(` ${" ".repeat(28)}${g(n.status)}
|
|
539
|
-
`)}async function
|
|
540
|
-
`+
|
|
541
|
-
`),i?.lastUpdated)process.stderr.write(g(` Canary: ${
|
|
544
|
+
`)}async function Rd(e){let t=D(e,"json"),r=D(e,"all"),n=D(e,"watch"),s=await $g(e)??"preprod",o=z("Checking network status..."),i=null,a=null,c,d;if(r)d=["preprod","preview"];else d=[s];let[l,...u]=await Promise.all([Promise.all([jn("/api/status"),jn("/api/issues")]).catch((f)=>(c=f.message,null)),...d.map((f)=>Ad(f))]);if(l)[i,a]=l;o.stop("Done");let p={};for(let f=0;f<d.length;f++)p[d[f]]=u[f];if(t){let f={lastUpdated:i?.lastUpdated??null,dashboard:Qr,canaryAvailable:i!==null,networks:{}};for(let w of d){let b=p[w]??{},S=i?.networks[w],v={...S,...b};f.networks[w]={overall:Ro(v),live:b,canary:S??null}}if(a){let w=r?void 0:d[0];f.issues=w?a.issues.filter((b)=>b.affects.toLowerCase().includes(w.toLowerCase())):a.issues}if(c)f.canaryError=c;I(f);let h=d.reduce((w,b)=>{let S={...i?.networks[b]??{},...p[b]??{}},v=Ro(S);if(v==="down")return"down";if(v==="degraded"&&w!=="down")return"degraded";return w},"up");if(h==="down")process.exitCode=2;else if(h==="degraded")process.exitCode=1;return}let m=()=>{if(process.stderr.write(`
|
|
545
|
+
`+U("Midnight Network Status")+`
|
|
546
|
+
`),i?.lastUpdated)process.stderr.write(g(` Canary: ${Do(i.lastUpdated)}`)+" ");if(process.stderr.write(g("Live: just now")+`
|
|
542
547
|
`),c)process.stderr.write(g(` (Dashboard unreachable: ${c})`)+`
|
|
543
548
|
`);if(d.length===0){process.stderr.write(`
|
|
544
549
|
`+g("No network data available.")+`
|
|
545
550
|
|
|
546
|
-
`);return}for(let f of d)
|
|
551
|
+
`);return}for(let f of d)Lg(f,i?.networks[f],p[f]??{});if(a){let f=r?void 0:d[0];Bg(a.issues,f)}process.stderr.write(`
|
|
547
552
|
`+V()+`
|
|
548
|
-
`),process.stderr.write(g(" Dashboard: ")+
|
|
549
|
-
|
|
550
|
-
`)};if(m(),n){let f=setInterval(async()=>{try{let[h,...w]=await Promise.all([Promise.all([
|
|
551
|
-
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(f),process.exit(0)})})}let y=d.reduce((f,h)=>{let w={...i?.networks[h]??{},...p[h]??{}},b=
|
|
552
|
-
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((l)=>l!==a),d=
|
|
553
|
-
Expected: managed/<name>/compiler/${
|
|
554
|
-
Searched: ${
|
|
555
|
-
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function
|
|
556
|
-
`),"approve";if(t.autoApproveReads&&
|
|
557
|
-
`),"approve";if(!process.stdin.isTTY){process.stderr.write(
|
|
558
|
-
`);let n=
|
|
559
|
-
`),"reject"}if(Ur)return process.stderr.write(
|
|
553
|
+
`),process.stderr.write(g(" Dashboard: ")+G(Qr)+`
|
|
554
|
+
|
|
555
|
+
`)};if(m(),n){let f=setInterval(async()=>{try{let[h,...w]=await Promise.all([Promise.all([jn("/api/status"),jn("/api/issues")]).catch(()=>null),...d.map((b)=>Ad(b))]);if(h)[i,a]=h;for(let b=0;b<d.length;b++)p[d[b]]=w[b];process.stderr.write("\x1B[2J\x1B[H"),m()}catch{process.stderr.write(g(" Refresh failed — retrying in 30s")+`
|
|
556
|
+
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(f),process.exit(0)})})}let y=d.reduce((f,h)=>{let w={...i?.networks[h]??{},...p[h]??{}},b=Ro(w);if(b==="down")return"down";if(b==="degraded"&&f!=="down")return"degraded";return f},"up");if(y==="down")process.exitCode=2;else if(y==="degraded")process.exitCode=1}var Ig,_g,Ed,Pg=15000,Hn=5000,xd=1e4;var Id=N(()=>{_e();Ue();pe();he();qe();Ig={preprod:{faucet:"https://faucet.preprod.midnight.network/",explorer:"https://preprod.midnightexplorer.com/"},preview:{faucet:"https://faucet.preview.midnight.network/",explorer:null},undeployed:{faucet:"",explorer:""}},_g={indexer:"Indexer",rpc:"RPC Node",faucet:"Faucet",explorer:"Explorer",chain:"Chain",dust:"Dust Generation",wallet:"Wallet Ops",dapp:"DApp Flow"},Ed={up:B("UP"),down:le("DOWN"),degraded:_("\x1B[33mDEGRADED\x1B[0m"),unknown:g("—")}});import{existsSync as Io,readFileSync as Wg,readdirSync as jg}from"node:fs";import{join as er,basename as Hg}from"node:path";function at(e,t){let r=er(e,"compiler",Gn);if(Io(r))return Pd(r,e,[]);for(let n of _d){let s=n?er(e,n,"managed"):er(e,"managed");if(!Io(s))continue;let o;try{o=jg(s).sort()}catch{continue}let i=o.filter((l)=>Io(er(s,l,"compiler",Gn)));if(i.length===0)continue;let a;if(t){if(!i.includes(t))throw Error(`Contract "${t}" not found in ${s}
|
|
557
|
+
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((l)=>l!==a),d=er(s,a,"compiler",Gn);return Pd(d,er(s,a),c)}throw Error(`No compiled contract found in ${e}
|
|
558
|
+
Expected: managed/<name>/compiler/${Gn}
|
|
559
|
+
Searched: ${_d.map((n)=>n?`${n}/managed/`:"managed/").join(", ")}
|
|
560
|
+
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function Pd(e,t,r){let n;try{n=JSON.parse(Wg(e,"utf-8"))}catch(o){throw Error(`Failed to parse ${e}: ${o.message}`)}return{info:Kg(n,e,t,r),infoPath:e}}function Kg(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:Hg(r),managedDir:r,compilerVersion:o,languageVersion:i,runtimeVersion:a,circuits:c,witnesses:d,siblings:n}}function Me(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(Me).join(", ")}]`;case"Boolean":return"boolean";case"String":return"string";case"Vector":return e.types?.[0]?`${Me(e.types[0])}[]`:"unknown[]";case"Map":if(e.types&&e.types.length>=2)return`Map<${Me(e.types[0])}, ${Me(e.types[1])}>`;return"Map<unknown, unknown>";case"Set":return e.types?.[0]?`Set<${Me(e.types[0])}>`:"Set<unknown>";case"Option":return e.types?.[0]?`${Me(e.types[0])} | null`:"unknown | null";default:return e["type-name"]??"unknown"}}function $d(e){let t=e.arguments.map((r)=>`${r.name}: ${Me(r.type)}`).join(", ");return`${e.name}(${t})`}function Od(e){if(e.pure)return"pure";let t=["impure"];if(e.proof)t.push("proof");return t.join(", ")}function Md(e){let t=e.arguments.map((s)=>`${s.name}: ${Me(s.type)}`).join(", "),r=Me(e["result type"]),n=r!=="void"?` → ${r}`:"";return`${e.name}(${t})${n}`}function Fd(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:Me(r.type)})),returnType:Me(t["result-type"])})),witnesses:e.witnesses.map((t)=>({name:t.name,arguments:t.arguments.map((r)=>({name:r.name,type:Me(r.type)})),returnType:Me(t["result type"])}))}}var Gn="contract-info.json",_d;var Jn=N(()=>{_d=["","contract/src","contract","contracts/src","contracts","src"]});import*as Ud from"node:readline";function Vg(e){return Gg.has(e)}function zg(e){return Jg.has(e)}function qg(e){let t=[],r=e.dappName?`Request from "${e.dappName}"`:"DApp Request";if(t.push(_(r)),t.push(""),t.push(` ${g("Action:")} ${G(e.method)}`),t.push(` ${g("Network:")} ${e.network}`),e.details.length>0){t.push("");for(let n of e.details)t.push(` ${g(n.label+":")} ${n.value}`)}return t.push(""),t.push(` ${B("[A]pprove")} ${le("[R]eject")}`),ua(t,"heavy")}async function Ld(e,t={}){if(t.approveAll)return process.stderr.write(g(` Auto-approved: ${e.method}`)+`
|
|
561
|
+
`),"approve";if(t.autoApproveReads&&Vg(e.method))return process.stderr.write(g(` Auto-approved (read-only): ${e.method}`)+`
|
|
562
|
+
`),"approve";if(!process.stdin.isTTY){process.stderr.write(le(" Cannot prompt for approval: stdin is not a TTY")+`
|
|
563
|
+
`);let n=zg(e.method)?"Balancing prompts like any other write":`${e.method} needs a terminal to approve`;return process.stderr.write(g(` ${n}: use --approve-all for non-interactive environments`)+`
|
|
564
|
+
`),"reject"}if(Ur)return process.stderr.write(le(" Rejected: another approval prompt is active")+`
|
|
560
565
|
`),"reject";process.stderr.write(`
|
|
561
|
-
`+
|
|
562
|
-
|
|
563
|
-
`),Ur=!0;let r;try{r=
|
|
564
|
-
`),"reject"}return new Promise((n)=>{let s=(o)=>{Ur=!1,r.close(),n(o)};r.on("close",()=>{if(Ur)s("reject")}),r.question(ee(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var
|
|
565
|
-
`)}),c.on("connection",(l)=>{let u=`conn_${
|
|
566
|
-
`)},
|
|
567
|
-
`)}function S(){return new Date(Date.now()+
|
|
568
|
-
`),!await O(
|
|
569
|
-
`)}};function
|
|
570
|
-
`)}var
|
|
571
|
-
${r}`)}}async function
|
|
572
|
-
${n}`)}}async function
|
|
573
|
-
${r}`)}}function
|
|
566
|
+
`+qg(e)+`
|
|
567
|
+
|
|
568
|
+
`),Ur=!0;let r;try{r=Ud.createInterface({input:process.stdin,output:process.stderr})}catch{return Ur=!1,process.stderr.write(le(" Cannot create readline interface")+`
|
|
569
|
+
`),"reject"}return new Promise((n)=>{let s=(o)=>{Ur=!1,r.close(),n(o)};r.on("close",()=>{if(Ur)s("reject")}),r.question(ee(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var Gg,Jg,Ur=!1;var Bd=N(()=>{he();Gg=new Set(["getShieldedBalances","getUnshieldedBalances","getDustBalance","getShieldedAddresses","getUnshieldedAddress","getDustAddress","getTxHistory","getConfiguration","getConnectionStatus"]),Jg=new Set(["balanceUnsealedTransaction","balanceSealedTransaction"])});import{WebSocketServer as Yg}from"ws";function Zg(e){if(_o(e))return Xg[e.code]??-32603;return-32603}function _o(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="DAppConnectorAPIError"}function Qg(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 Vn(e,t){if(typeof t==="bigint")return t.toString();return t}function eh(e,t){return t}function th(e){let t;try{t=JSON.parse(e,eh)}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 Wd(e){let{port:t,handlers:r,onConnect:n,onDisconnect:s,onRequest:o,onResponse:i}=e,a=new Map,c=new Yg({port:t,host:"127.0.0.1"});c.on("error",(l)=>{process.stderr.write(`WebSocket server error: ${l.message}
|
|
570
|
+
`)}),c.on("connection",(l)=>{let u=`conn_${++rh}`,p={ws:l,id:u,connectedAt:new Date,authenticated:!1,requestCount:0,notify(f,h){if(l.readyState!==l.OPEN)return;let w={jsonrpc:"2.0",method:f,...h&&{params:h}};l.send(JSON.stringify(w,Vn))}};a.set(u,p),n?.(p);let m=!1,y=()=>{if(m)return;m=!0,a.delete(u),s?.(p)};l.on("message",async(f)=>{let h=null,w,b,S=Date.now();try{w=th(f.toString("utf-8")),h=w.id,p.requestCount++,o?.(p,w);let v=r[w.method];if(!v){let J={jsonrpc:"2.0",id:w.id,error:{code:-32601,message:`Method not found: ${w.method}`}};l.send(JSON.stringify(J,Vn));return}b={notify:p.notify.bind(p),connectionId:u,requestId:w.id,metadata:{}};let R=await v(w.params??{},b),P=Date.now()-S;if(w.method==="connect"&&R&&typeof R==="object")p.authenticated=!0,p.networkId=R.networkId;let Y={jsonrpc:"2.0",id:w.id,result:R};l.send(JSON.stringify(Y,Vn)),i?.(p,w,P,R,void 0,b.metadata)}catch(v){let R=Date.now()-S,P=v?.rpcCode??Zg(v),Y=v instanceof Error?v.message:"Internal error",J=_o(v)?{type:v.type,code:v.code}:Qg(v),q={jsonrpc:"2.0",id:h,error:{code:P,message:Y,data:J}};if(l.send(JSON.stringify(q,Vn)),w){let M={message:Y,code:_o(v)?v.code:void 0};i?.(p,w,R,void 0,M,b?.metadata)}}}),l.on("close",y),l.on("error",()=>{y();try{l.close()}catch{}})});async function d(){for(let l of a.values())l.ws.close(1001,"Server shutting down");return a.clear(),new Promise((l,u)=>{c.close((p)=>{if(p)u(p);else l()})})}return{wss:c,connections:a,close:d}}function Ie(e,t){let r=Error(t);return r.type="DAppConnectorAPIError",r.code=e,r.reason=t,r}var Xg,rh=0;var Po=N(()=>{Xg={Rejected:-32000,PermissionRejected:-32001,Disconnected:-32002,InvalidRequest:-32602,InternalError:-32603}});function jd(e){let t=[],r,n;function s(){if(r!==void 0&&n!==void 0){let a=Date.now()-n;t.push({phase:r,durationMs:a}),e?.onComplete?.(r,a),r=void 0,n=void 0}}function o(a){s(),r=a,n=Date.now(),e?.onStart?.(a)}function i(){return[...t]}return{start:o,complete:s,getTimings:i}}import{Transaction as Hd}from"@midnight-ntwrk/ledger-v8";function $o(e){return Buffer.from(e).toString("hex")}function zn(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 Jd(e){return $o(e.serialize())}function Lr(e){return Hd.deserialize(Kd,Gd,sh,zn(e))}function Oo(e){return Hd.deserialize(Kd,Gd,nh,zn(e))}var Kd="signature",Gd="proof",nh="binding",sh="pre-binding";var Mo=()=>{};function Vd(e){let t=Buffer.from(`midnight_signed_message:${e.length}:`,"utf-8");return new Uint8Array(Buffer.concat([t,e]))}function oh(e){let t=[];for(let r of e.intents?.values()??[])for(let n of[r.guaranteedUnshieldedOffer,r.fallibleUnshieldedOffer])n?.inputs.forEach((s,o)=>t.push(n.signatures[o]!==void 0));return t}function zd(e){let t=oh(e),r=t.filter(Boolean).length;if(r===0)return"none";return r===t.length?"all":"some"}function ah(e){return[...new Set([ih,...e.intents?.keys()??[],...e.fallibleOffer?.keys()??[]])].filter((r)=>[...e.imbalances(r)].some(([n,s])=>n.tag==="unshielded"&&s!==0n))}function qd(e){let t=zd(e);if(t==="some")throw new tr;if(t==="all"){let r=ah(e);if(r.length>0)throw new Br(r)}}async function Yd(e,t,r){if(t.type!=="UNBOUND_TRANSACTION")return e.signRecipe(t,r);let n=zd(Lr($o(t.baseTransaction.serialize())));if(n==="none")return e.signRecipe(t,r);if(n==="some")throw new tr;if(!t.balancingTransaction)return t;let s=await e.signRecipe({type:"UNPROVEN_TRANSACTION",transaction:t.balancingTransaction},r);if(s.type!=="UNPROVEN_TRANSACTION")throw Error(`The wallet SDK signed an unproven transaction into a ${s.type} recipe`);return{...t,balancingTransaction:s.transaction}}var tr,Br,ih=0;var Xd=N(()=>{Mo();tr=class tr 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,tr.prototype)}};Br=class Br 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,Br.prototype)}}});import{Transaction as ch}from"@midnight-ntwrk/ledger-v8";function qn(e,t){let r=[];r.push({label:"Tx size",value:ph(e.length/2)});let n=dh(e,t);if(n){let s=lh(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 dh(e,t){let r=uh(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 ch.deserialize(s,o,i,r).toString(!0)}catch{}return null}function lh(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 uh(e){return new Uint8Array(Buffer.from(e,"hex"))}function ph(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 Zd=()=>{};import{DustLocalState as fh}from"@midnight-ntwrk/ledger-v8";import{CoreWallet as Ve}from"@midnight-ntwrk/wallet-sdk-dust-wallet/v1";var Dt,mh,gh,Nx;var Qd=N(()=>{Dt=new Map,mh=Ve.applyEventsWithChanges;Ve.applyEventsWithChanges=function(t,r,n,s){let o=mh.call(Ve,t,r,n,s),i=Array.isArray(o)?o[0]:o;if(Dt.size>0&&i?.pendingDust){let a=new Set(i.pendingDust.map((c)=>c.nullifier));for(let c of Dt.keys())if(!a.has(c))Dt.delete(c)}return o};gh=Ve.spendCoins;Ve.spendCoins=function(t,r,n,s){let o=null;try{o=t.state.serialize()}catch{}let i=gh.call(Ve,t,r,n,s),a=i[1]??i;if(o&&a?.pendingDust){for(let c of a.pendingDust)if(!Dt.has(c.nullifier))Dt.set(c.nullifier,o)}return i};Nx=Ve.revertTransaction;Ve.revertTransaction=function(t,r){let n=Ve.pendingDustToMap(t.pendingDust),s=[],o=r.intents;if(o)for(let a of o.values()){let c=a.dustActions?.spends;if(!c)continue;for(let d of c)if(n.has(d.oldNullifier))s.push(d.oldNullifier)}let i=t.state;for(let a of s){let c=Dt.get(a);if(c){try{i=fh.deserialize(c)}catch{}Dt.delete(a)}}return{...t,state:i,pendingDust:t.pendingDust.filter((a)=>!s.includes(a.nullifier))}};Ve.applyFailed=Ve.revertTransaction});import*as It from"rxjs";import{MidnightBech32m as Fo,UnshieldedAddress as hh,ShieldedAddress as wh}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as Uo}from"@midnight-ntwrk/wallet-sdk-abstractions";function Sh(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 el(e){let{bundle:t,networkConfig:r,approvalOptions:n,callbacks:s}=e,{facade:o,keystore:i,zswapSecretKeys:a,dustSecretKey:c}=t,d=yh[r.networkId];if(d===void 0)throw Error(`Unknown networkId: ${r.networkId}`);let l=e.isCurrent??((E)=>E.isSynced),u=e.initialState,p=o.state().pipe(It.filter((E)=>l(E))).subscribe((E)=>{u=E});function m(){if(!u)throw Ie("Disconnected","Wallet not synced yet");return u}let y={shieldedSecretKeys:a,dustSecretKey:c},f=new Map;function h(E,x,A){let T=f.get(E);if(!T)T=new Map,f.set(E,T);let j=setTimeout(async()=>{if(T.delete(x),T.size===0)f.delete(E);try{await o.revert(A)}catch{}process.stderr.write(g(` abandoned tx reverted (${E})`)+`
|
|
571
|
+
`)},Bi);T.set(x,{recipe:A,timer:j})}function w(E,x){let A=f.get(E);if(!A)return;let T=A.get(x);if(T)clearTimeout(T.timer),A.delete(x);if(A.size===0)f.delete(E)}async function b(E){let x=f.get(E);if(!x||x.size===0)return;f.delete(E);for(let[,A]of x){clearTimeout(A.timer);try{await o.revert(A.recipe)}catch{}}process.stderr.write(g(` reverted ${x.size} pending tx(s) on disconnect`)+`
|
|
572
|
+
`)}function S(){return new Date(Date.now()+dr*60*1000)}async function v(E,x){x?.start("signing");let A=await Yd(o,E,(L)=>i.signData(L));x?.start("proving");let T,j=await Promise.race([o.finalizeRecipe(A),new Promise((L,se)=>{T=setTimeout(()=>se(Error("ZK proof generation timed out")),Yr)})]);return clearTimeout(T),x?.complete(),{hex:Jd(j),finalized:j}}function R(E){let x;try{x=Lr(E)}catch{return}try{qd(x)}catch(A){if(A instanceof tr||A instanceof Br)throw Ie("InvalidRequest",A.message);throw A}}async function P(E,x=[],A){A?.notify("approval:pending",{method:E});let T=await Ld({method:E,network:r.networkId,details:x,dappName:A?.connectionId},n),j=T==="reject"?"rejected":"approved";if(A?.notify("approval:resolved",{method:E,result:j}),T==="reject")throw Ie("Rejected","User rejected the request")}function Y(E){return Fo.encode(d,E).asString()}function J(E){let x={};for(let A of E){let T=A.kind;if(T!=="shielded"&&T!=="unshielded")throw Ie("InvalidRequest",`Invalid output kind: "${T}" — must be "shielded" or "unshielded"`);if(!x[T])x[T]=[];let j=BigInt(A.value),L;if(T==="unshielded")L=Fo.parse(A.recipient).decode(hh,d);else L=Fo.parse(A.recipient).decode(wh,d);x[T].push({type:A.type,receiverAddress:L,amount:j})}return Object.entries(x).map(([A,T])=>({type:A,outputs:T}))}function q(E,x){return jd({onStart:(A)=>{let T=x?.connectionId??"unknown";s?.onPhaseStart?.(T,E,A),x?.notify("progress",{method:E,phase:A,status:"started"})},onComplete:(A,T)=>{let j=x?.connectionId??"unknown";s?.onPhaseComplete?.(j,E,A,T),x?.notify("progress",{method:E,phase:A,status:"completed",durationMs:T})}})}function M(){if(!u)return!1;try{let E=u.dust;return E?.availableCoins?.length>0||E?.balance(new Date)>0n}catch{return!1}}async function O(E){return new Promise((x)=>{if(M()){x(!0);return}let A=o.state().pipe(It.filter(()=>M()),It.take(1),It.timeout(E)).subscribe({next:()=>{A.unsubscribe(),x(!0)},error:()=>{A.unsubscribe(),x(!1)}})})}async function ne(E){for(let x=1;x<=lr;x++)try{return await E()}catch(A){let T=String(A?.message??A??"");if(!(/no dust tokens/i.test(T)||/dust.*unavailable/i.test(T))||x===lr)throw A;if(process.stderr.write(g(` dust unavailable, waiting for recovery (${x}/${lr})... [${T.slice(0,60)}]`)+`
|
|
573
|
+
`),!await O(xs)&&x<lr)await new Promise((se)=>setTimeout(se,xs))}throw Error("unreachable")}let ue={connect:async(E)=>{let x=String(E.networkId??"");if(x.toLowerCase()!==r.networkId.toLowerCase())throw Ie("InvalidRequest",`Network mismatch: wallet is on ${r.networkId}, requested ${x}`);return{networkId:r.networkId}},getUnshieldedBalances:async()=>m().unshielded.balances,getShieldedBalances:async()=>m().shielded.balances,getDustBalance:async()=>{let x=m().dust.balance(new Date);return{cap:x,balance:x}},getUnshieldedAddress:async()=>{let E=m();return{unshieldedAddress:Y(E.unshielded.address)}},getShieldedAddresses:async()=>{let x=m().shielded.address;return{shieldedAddress:Y(x),shieldedCoinPublicKey:x.coinPublicKeyString(),shieldedEncryptionPublicKey:x.encryptionPublicKeyString()}},getDustAddress:async()=>{let E=m();return{dustAddress:Y(E.dust.address)}},getTxHistory:async(E)=>{let x=m(),A=Number(E.pageNumber??0),T=Number(E.pageSize??20);try{let j=x.unshielded.transactionHistory,L=[],se=0,H=A*T;for await(let oe of j.getAll()){if(se>=H+T)break;if(se>=H)L.push({txHash:oe.hash,txStatus:oe.status==="SUCCESS"?{status:"finalized"}:{status:"pending"}});se++}return L}catch{return[]}},getConfiguration:async()=>({indexerUri:r.indexer,indexerWsUri:r.indexerWS,proverServerUri:r.proofServer,substrateNodeUri:r.node,networkId:r.networkId}),getConnectionStatus:async()=>({status:"connected",networkId:d}),makeTransfer:async(E,x)=>{let A=E.desiredOutputs;if(!Array.isArray(A)||A.length===0)throw Ie("InvalidRequest","desiredOutputs must be a non-empty array");let T=q("makeTransfer",x),j=A.map((Be,ke)=>({label:`Output ${ke+1}`,value:`${Be.value} → ${String(Be.recipient).slice(0,20)}... (${Be.kind})`}));T.start("approve"),await P("makeTransfer",j,x),T.start("building");let L=J(A),se=E.options?.payFees??!0,H=await ne(()=>o.transferTransaction(L,y,{ttl:S(),payFees:se})),{hex:oe,finalized:Ae}=await v(H,T);return h(x.connectionId,oe,H),x.metadata.phases=T.getTimings(),{tx:oe}},submitTransaction:async(E,x)=>{let A=String(E.tx??"");if(!A)throw Ie("InvalidRequest","tx is required");let T=q("submitTransaction",x);T.start("approve");try{await P("submitTransaction",qn(A,"sealed"),x)}catch(L){let H=f.get(x.connectionId)?.get(A);if(H)try{await o.revert(H.recipe)}catch{}throw w(x.connectionId,A),L}let j=Oo(A);T.start("submitting");try{let L=await o.submitTransaction(j);return T.complete(),w(x.connectionId,A),x.metadata.phases=T.getTimings(),{txHash:L}}catch(L){T.complete();let H=f.get(x.connectionId)?.get(A);if(H)try{await o.revert(H.recipe)}catch{}w(x.connectionId,A);let oe=Sh(L),Ae=Error(`Transaction submission failed: ${oe}`);throw Ae.cause=L,Ae}},balanceUnsealedTransaction:async(E,x)=>{let A=String(E.tx??"");if(!A)throw Ie("InvalidRequest","tx is required");R(A);let T=q("balanceUnsealedTransaction",x);T.start("approve"),await P("balanceUnsealedTransaction",qn(A,"unsealed"),x),T.start("building");let j=Lr(A),L=await ne(()=>o.balanceUnboundTransaction(j,y,{ttl:S()})),{hex:se,finalized:H}=await v(L,T);return h(x.connectionId,se,L),x.metadata.phases=T.getTimings(),{tx:se}},balanceSealedTransaction:async(E,x)=>{let A=String(E.tx??"");if(!A)throw Ie("InvalidRequest","tx is required");let T=q("balanceSealedTransaction",x);T.start("approve"),await P("balanceSealedTransaction",qn(A,"sealed"),x),T.start("building");let j=Oo(A),L=await ne(()=>o.balanceFinalizedTransaction(j,y,{ttl:S()})),{hex:se,finalized:H}=await v(L,T);return h(x.connectionId,se,L),x.metadata.phases=T.getTimings(),{tx:se}},makeIntent:async(E,x)=>{let{desiredInputs:A,desiredOutputs:T,options:j}=E;if(!j)throw Ie("InvalidRequest","options is required for makeIntent");let L=q("makeIntent",x);L.start("approve"),await P("makeIntent",[],x),L.start("building");let se={};if(Array.isArray(A))for(let ke of A){let ps=ke.kind;if(!se[ps])se[ps]={};se[ps][ke.type]=BigInt(ke.value)}let H=J(T??[]),oe=await ne(()=>o.initSwap(se,H,y,{ttl:S(),payFees:j.payFees??!0})),{hex:Ae,finalized:Be}=await v(oe,L);return h(x.connectionId,Ae,oe),x.metadata.phases=L.getTimings(),{tx:Ae}},signData:async(E,x)=>{let A=String(E.data??""),T=E.options;if(!A||!T?.encoding)throw Ie("InvalidRequest","data and options.encoding are required");if(T.keyType&&T.keyType!=="unshielded")throw Ie("InvalidRequest",`Unsupported keyType: "${T.keyType}" — only "unshielded" is supported`);await P("signData",[{label:"Encoding",value:T.encoding},{label:"Data",value:A.length>64?A.slice(0,64)+"...":A}],x);let j;switch(T.encoding){case"hex":j=zn(A);break;case"base64":j=new Uint8Array(Buffer.from(A,"base64"));break;case"text":j=new Uint8Array(Buffer.from(A,"utf-8"));break;default:throw Ie("InvalidRequest",`Unknown encoding: ${T.encoding}`)}let L=i.signData(Vd(j)),se=i.getPublicKey();return{data:A,signature:String(L),verifyingKey:String(se)}},getProvingProvider:async()=>({provingProvider:"ready",proverServerUri:r.proofServer}),hintUsage:async(E)=>{let x=E.methodNames??[];process.stderr.write(g(` DApp hints usage: ${x.join(", ")}`)+`
|
|
574
|
+
`)}};function us(){p.unsubscribe();for(let[,E]of f)for(let[,x]of E)clearTimeout(x.timer);f.clear()}function Pt(){for(let[,E]of f)if(E.size>0)return!0;return!1}return{handlers:ue,revertPendingTxs:b,hasPendingTxs:Pt,dispose:us}}var yh;var tl=N(()=>{Bd();Po();Mo();Xd();Zd();Qd();yh={PreProd:Uo.NetworkId.PreProd,Preview:Uo.NetworkId.Preview,Undeployed:Uo.NetworkId.Undeployed}});import{Socket as bh}from"node:net";function vh(e,t){if(e===null||e===t.address)return;return`it serves the wallet at ${e}, and this command pays from ${t.name} (${t.address})`}function kh(e){return new Promise((t)=>{let r=new bh;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 Ch(e){let r=(await Bo(e,"getConnectionStatus"))?.networkId;return typeof r==="string"?r:null}async function Eh(e){let r=(await Bo(e,"getUnshieldedAddress"))?.unshieldedAddress;return typeof r==="string"?r:null}async function Lo(e){let r=(await Bo(e,"getDustBalance"))?.balance;try{return typeof r==="string"||typeof r==="number"?BigInt(r):null}catch{return null}}async function Bo(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 Yn(e){let t=e.port??ur,r=(e.network??"undeployed").toLowerCase(),n=e.onMessage??(()=>{});if(await kh(t)){let s=await Ch(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 Eh(t);if(i!==null){let a=ce(ae(e.wallet)).addresses[o],c=vh(i,{address:a,name:e.wallet??"the active wallet"});if(c)throw Error(`mn serve on port ${t} can't pay for this command: ${c}. Stop it first (\`pkill -f 'mn serve'\`) and retry, or run the command for the wallet it serves.`)}return n(`Reusing existing mn serve on port ${t}`),{port:t,async stop(){}}}return xh(e)}async function xh(e){let t=e.port??ur,r=e.onMessage??(()=>{}),n=ce(ae(e.wallet)),s=Buffer.from(n.seed,"hex"),{name:o,config:i}=Q({args:{command:"serve",subcommand:void 0,positionals:[],flags:e.network?{network:e.network}:{}}}),a=n.addresses[o],c=xe((h,w)=>{r(`SDK: ${w}`)}),d=De();r("Building wallet facade...");let l=st(o,i.indexerWS);if(l)r(Dn(o,l));let u=mt(a,o),p=await Ge(s,i,u);r("Syncing wallet..."),await ft(p,{onProgress:(h,w)=>{if(w>0){let b=Math.min(Math.round(h/w*100),100);r(`Syncing wallet... ${b}%`)}}}),r("Wallet synced"),r("Waiting for dust...");let m=await kn(p);r("Dust ready");try{await gt(a,o,p.facade)}catch{}let y=el({bundle:p,networkConfig:i,approvalOptions:{approveAll:!0,autoApproveReads:!0},initialState:m,isCurrent:(h)=>Tr(h),callbacks:{onPhaseStart:(h,w,b)=>{r(`${b}...`)},onPhaseComplete:(h,w,b,S)=>{r(`${b} ${Math.round(S)}ms`)}}}),f=Wd({port:t,handlers:y.handlers,onConnect:(h)=>{r(`connected ${h.id}`)},onDisconnect:(h)=>{r(`disconnected ${h.id}`),y.revertPendingTxs(h.id).catch(()=>{})},onRequest:(h,w)=>{r(`${h.id} → ${w.method}`)},onResponse:(h,w,b,S,v)=>{if(v)r(`${h.id} ← ${w.method} FAILED: ${v.message}`);else r(`${h.id} ← ${w.method} (${Math.round(b)}ms)`)}});return r(`Server ready on ws://localhost:${t}`),{port:t,async stop(){f.close(),y.dispose(),d(),c();try{await Oe(p)}catch{}}}}var Xn=N(()=>{$e();pe();Ye();_r();At();Nt();tl();Po()});import{existsSync as rl}from"node:fs";import{join as nl}from"node:path";function sl(e){for(let t of Zn){let r=nl(e,t);if(rl(r))return r}return null}function Th(e){for(let t of Ah){let r=nl(e,t);if(rl(r))return r}return null}function ol(e){let{projectRoot:t,witnessNames:r}=e,n=Th(t),s=[`Contract declares ${r.length} witness(es): ${r.join(", ")}`,"but no compiled witnesses module was found.","",`Searched (relative to ${t}):`,...Zn.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(`
|
|
575
|
+
`)}var Zn,Ah;var Wo=N(()=>{Zn=["dist/witnesses.js","src/witnesses.js","contract/dist/witnesses.js","contract/src/witnesses.js"],Ah=["src/witnesses.ts","contract/src/witnesses.ts"]});function Qn(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(Qn)}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]=Qn(e[r]);return t}return e}function il(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 Nh}from"node:child_process";import{writeFileSync as Rh,unlinkSync as al,existsSync as es,symlinkSync as cl}from"node:fs";import{join as Wr,dirname as dl}from"node:path";import{fileURLToPath as Dh}from"node:url";function Ih(){let e=dl(Dh(import.meta.url));for(let t=0;t<8;t++){let r=Wr(e,"node_modules");if(es(r))return r;let n=dl(e);if(n===e)break;e=n}return null}function Go(e){return ye(e.indexer),{[Ho]:e.indexer,[Ko]:e.indexerWS??e.indexer.replace("http","ws")}}async function rr(e){let t=Oh(e),r=await Jo(e.dappDir,t,e.onMessage,Go(e.networkConfig));try{return JSON.parse(r)}catch{throw Error(`State script returned unexpected output:
|
|
576
|
+
${r}`)}}async function ts(e){let t=Ph(e),r={...Go(e.networkConfig),...e.privateStateSecretKey?{MN_PRIVATE_STATE_SECRET:e.privateStateSecretKey}:{}},n=await Jo(e.dappDir,t,e.onMessage,r);try{return JSON.parse(n)}catch{throw Error(`Deploy script returned unexpected output:
|
|
577
|
+
${n}`)}}async function rs(e){let t=$h(e),r=await Jo(e.dappDir,t,e.onMessage,Go(e.networkConfig));try{return JSON.parse(r)}catch{throw Error(`Call script returned unexpected output:
|
|
578
|
+
${r}`)}}function ll(e){return`
|
|
574
579
|
import WebSocket from 'ws';
|
|
575
580
|
|
|
576
581
|
const RPC_URL = 'ws://127.0.0.1:${e}';
|
|
@@ -611,7 +616,7 @@ function rpcCall(method, params = {}) {
|
|
|
611
616
|
function rpcClose() {
|
|
612
617
|
if (rpcWs) rpcWs.close();
|
|
613
618
|
}
|
|
614
|
-
`}function
|
|
619
|
+
`}function ul(){return`
|
|
615
620
|
// Wallet provider backed by mn serve RPC
|
|
616
621
|
const walletProvider = {
|
|
617
622
|
getCoinPublicKey: () => {
|
|
@@ -641,7 +646,7 @@ const walletProvider = {
|
|
|
641
646
|
|
|
642
647
|
// Get wallet state for coin/encryption public keys
|
|
643
648
|
const walletState = await rpcCall('getShieldedAddresses', {});
|
|
644
|
-
`}function
|
|
649
|
+
`}function pl(e,t){return`
|
|
645
650
|
import { pathToFileURL } from 'node:url';
|
|
646
651
|
import { resolve } from 'node:path';
|
|
647
652
|
import { CompiledContract } from '@midnight-ntwrk/compact-js';
|
|
@@ -655,7 +660,7 @@ const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract',
|
|
|
655
660
|
// Both relative-to-cwd locations and contract/<...> locations are checked
|
|
656
661
|
// so mn dev (which chdirs into the contract sub-package) and mn contract
|
|
657
662
|
// deploy run from a workspace root both work.
|
|
658
|
-
const WITNESS_CANDIDATES = ${JSON.stringify(
|
|
663
|
+
const WITNESS_CANDIDATES = ${JSON.stringify(Zn)};
|
|
659
664
|
let witnesses;
|
|
660
665
|
let createPrivateState;
|
|
661
666
|
for (const p of WITNESS_CANDIDATES) {
|
|
@@ -686,7 +691,7 @@ if (!witnesses) {
|
|
|
686
691
|
// Uses a deterministic seed derived from the wallet so post/takeDown use the same key.
|
|
687
692
|
// The private state provider (leveldb) persists between calls, but initialPrivateState
|
|
688
693
|
// is the fallback when no stored state exists yet.
|
|
689
|
-
${
|
|
694
|
+
${_h}
|
|
690
695
|
function makeInitialPrivateState() {
|
|
691
696
|
if (createPrivateState) {
|
|
692
697
|
// Secret precedence (see resolvePrivateStateSecretKey, injected above via
|
|
@@ -712,7 +717,7 @@ const compiled = witnesses
|
|
|
712
717
|
CompiledContract.withVacantWitnesses,
|
|
713
718
|
(c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR),
|
|
714
719
|
);
|
|
715
|
-
`}function
|
|
720
|
+
`}function fl(e,t,r){return`
|
|
716
721
|
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
717
722
|
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
718
723
|
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
@@ -727,31 +732,31 @@ const providers = {
|
|
|
727
732
|
accountId: 'mn-contract-runner',
|
|
728
733
|
}),
|
|
729
734
|
publicDataProvider: indexerPublicDataProvider(
|
|
730
|
-
process.env.${
|
|
731
|
-
process.env.${
|
|
735
|
+
process.env.${Ho},
|
|
736
|
+
process.env.${Ko},
|
|
732
737
|
),
|
|
733
738
|
zkConfigProvider,
|
|
734
739
|
proofProvider: httpClientProofProvider(${JSON.stringify(t.proofServer)}, zkConfigProvider),
|
|
735
740
|
walletProvider,
|
|
736
741
|
midnightProvider: walletProvider,
|
|
737
742
|
};
|
|
738
|
-
`}function
|
|
743
|
+
`}function Ph(e){let t=e.privateStateKey??`${e.contractName}PrivateState`,r=JSON.stringify(e.args??[]);return`
|
|
739
744
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
740
745
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
741
746
|
|
|
742
|
-
${
|
|
743
|
-
${
|
|
747
|
+
${ll(e.servePort)}
|
|
748
|
+
${pl(e.contractName,e.managedDir)}
|
|
744
749
|
|
|
745
750
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
746
751
|
await rpcConnect();
|
|
747
752
|
process.stderr.write('Connected\\n');
|
|
748
753
|
|
|
749
|
-
${
|
|
750
|
-
${
|
|
754
|
+
${ul()}
|
|
755
|
+
${fl(e.managedDir,e.networkConfig,t)}
|
|
751
756
|
|
|
752
757
|
import { deployContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
753
758
|
|
|
754
|
-
${
|
|
759
|
+
${ml}
|
|
755
760
|
const constructorArgs = (${r}).map(coerceArg);
|
|
756
761
|
process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n');
|
|
757
762
|
const deployed = await deployContract(providers, {
|
|
@@ -767,19 +772,19 @@ process.stderr.write('Deploy complete: ' + address + '\\n');
|
|
|
767
772
|
console.log(JSON.stringify({ contractAddress: address }));
|
|
768
773
|
rpcClose();
|
|
769
774
|
process.exit(0);
|
|
770
|
-
`}function
|
|
775
|
+
`}function $h(e){let t=e.privateStateKey??`${e.contractName}PrivateState`;return`
|
|
771
776
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
772
777
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
773
778
|
|
|
774
|
-
${
|
|
775
|
-
${
|
|
779
|
+
${ll(e.servePort)}
|
|
780
|
+
${pl(e.contractName,e.managedDir)}
|
|
776
781
|
|
|
777
782
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
778
783
|
await rpcConnect();
|
|
779
784
|
process.stderr.write('Connected\\n');
|
|
780
785
|
|
|
781
|
-
${
|
|
782
|
-
${
|
|
786
|
+
${ul()}
|
|
787
|
+
${fl(e.managedDir,e.networkConfig,t)}
|
|
783
788
|
|
|
784
789
|
import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
785
790
|
|
|
@@ -792,14 +797,14 @@ const deployed = await findDeployedContract(providers, {
|
|
|
792
797
|
});
|
|
793
798
|
|
|
794
799
|
process.stderr.write('Calling ${e.circuit}...\\n');
|
|
795
|
-
${
|
|
800
|
+
${ml}
|
|
796
801
|
const args = (${JSON.stringify(e.args??[])}).map(coerceArg);
|
|
797
802
|
await deployed.callTx.${e.circuit}(...args);
|
|
798
803
|
|
|
799
804
|
console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(e.circuit)} }));
|
|
800
805
|
rpcClose();
|
|
801
806
|
process.exit(0);
|
|
802
|
-
`}function
|
|
807
|
+
`}function Oh(e){return`
|
|
803
808
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
804
809
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
805
810
|
|
|
@@ -819,8 +824,8 @@ if (typeof contractMod.ledger !== 'function') {
|
|
|
819
824
|
|
|
820
825
|
process.stderr.write('Querying contract state...\\n');
|
|
821
826
|
const provider = indexerPublicDataProvider(
|
|
822
|
-
process.env.${
|
|
823
|
-
process.env.${
|
|
827
|
+
process.env.${Ho},
|
|
828
|
+
process.env.${Ko},
|
|
824
829
|
);
|
|
825
830
|
|
|
826
831
|
const contractState = await provider.queryContractState(${JSON.stringify(e.contractAddress)});
|
|
@@ -862,20 +867,22 @@ for (const key of Object.keys(state)) {
|
|
|
862
867
|
|
|
863
868
|
console.log(JSON.stringify({ fields, maps }));
|
|
864
869
|
process.exit(0);
|
|
865
|
-
`}function
|
|
866
|
-
`,r?.(y)}),l.on("close",(m)=>{if(a(),m!==0){d(Error(p
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
const
|
|
870
|
-
`;
|
|
870
|
+
`}function Fh(e){if(!jo)return[];let t=[];if(!es(e)){try{cl(jo,e),t.push(e)}catch{}return t}for(let r of Mh){let n=Wr(jo,r),s=Wr(e,r);if(!es(n)||es(s))continue;try{cl(n,s),t.push(s)}catch{}}return t}async function Jo(e,t,r,n){let s=Wr(e,"node_modules"),o=Fh(s),i=Wr(e,`.mn-contract-${Date.now()}.mjs`);Rh(i,t);let a=()=>{try{al(i)}catch{}for(let c of o.slice().reverse())try{al(c)}catch{}};return new Promise((c,d)=>{let l=Nh("node",[i],{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1",...n}}),u="",p="";l.stdout?.on("data",(m)=>{u+=m.toString()}),l.stderr?.on("data",(m)=>{let y=m.toString().trim();if(y)p+=y+`
|
|
871
|
+
`,r?.(y)}),l.on("close",(m)=>{if(a(),m!==0){d(Error(Uh(p,m)));return}c(u.trim())}),l.on("error",(m)=>{a(),d(m)})})}function Uh(e,t){let r=e.split(`
|
|
872
|
+
`),n=-1;for(let o=r.length-1;o>=0;o--)if(/^\w*Error(?: \[\w+\])?: /.test(r[o].trim())){n=o;break}if(n===-1)return e.trim()||`Script exited with code ${t}`;let s=[r[n].trim().replace(/^Error: /,"")];for(let o of r.slice(n+1)){if(o.trim()===""||/^\s*at \S/.test(o)||/^Node\.js v/.test(o.trim()))break;s.push(o.trimEnd())}return s.join(`
|
|
873
|
+
`)}var jo,Ho="MN_INDEXER_URL",Ko="MN_INDEXER_WS_URL",_h,ml,Mh;var jr=N(()=>{_e();Wo();jo=Ih();_h=`
|
|
874
|
+
const resolvePrivateStateSecretKey = (${il.toString()});
|
|
875
|
+
`;ml=`
|
|
876
|
+
const coerceArg = (${Qn.toString()});
|
|
877
|
+
`;Mh=["@midnight-ntwrk","ws"]});import{indexerPublicDataProvider as Lh}from"@midnight-ntwrk/midnight-js-indexer-public-data-provider";function gl(e){return ye(e.indexer),Lh(e.indexer,e.indexerWS??e.indexer.replace("http","ws"))}var hl=N(()=>{_e()});var vl={};fe(vl,{default:()=>yl});import{resolve as ns}from"node:path";function Hr(){return{update(){},stop(){},fail(){},log(){},clear(){}}}function Bh(e){return wl.includes(e)}async function yl(e,t){let r=e.subcommand;if(!r||!Bh(r))throw new W(`Usage: midnight contract <${wl.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 Wh(e);case"deploy":return jh(e);case"call":return Kh(e);case"state":return Gh(e)}}function ss(e){let t=k(e,"managed"),r=k(e,"path");return ns(t??r??process.cwd())}async function Wh(e){let t=D(e,"json"),r=ss(e),n=k(e,"name"),{info:s}=at(r,n);if(t){I(Fd(s));return}if(process.stderr.write(`
|
|
885
|
+
`+U(`Contract: ${s.name}`)+`
|
|
879
886
|
|
|
880
887
|
`),process.stderr.write(C("Compiler",s.compilerVersion)+`
|
|
881
888
|
`),process.stderr.write(C("Language",s.languageVersion)+`
|
|
@@ -883,18 +890,18 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return yh(
|
|
|
883
890
|
`),process.stderr.write(`
|
|
884
891
|
`+_(" Circuits")+`
|
|
885
892
|
`),s.circuits.length===0)process.stderr.write(g(" (none)")+`
|
|
886
|
-
`);else for(let o of s.circuits){let i
|
|
893
|
+
`);else for(let o of s.circuits){let i=$d(o),a=Od(o),c=o.pure?G(a):ee(a);process.stderr.write(` ${i} ${g("—")} ${c}
|
|
887
894
|
`)}if(process.stderr.write(`
|
|
888
895
|
`+_(" Witnesses")+`
|
|
889
896
|
`),s.witnesses.length===0)process.stderr.write(g(" (none)")+`
|
|
890
|
-
`);else for(let o of s.witnesses)process.stderr.write(` ${
|
|
897
|
+
`);else for(let o of s.witnesses)process.stderr.write(` ${Md(o)}
|
|
891
898
|
`);if(s.siblings.length>0){process.stderr.write(`
|
|
892
899
|
`+_(" Other contracts in this project")+`
|
|
893
|
-
`);for(let o of s.siblings)process.stderr.write(` ${
|
|
900
|
+
`);for(let o of s.siblings)process.stderr.write(` ${G(o)}
|
|
894
901
|
`);process.stderr.write(`
|
|
895
902
|
`+g(" Inspect a sibling: mn contract inspect --name <name>")+`
|
|
896
903
|
`)}process.stderr.write(`
|
|
897
|
-
`)}async function
|
|
904
|
+
`)}async function Sl(e,t,r){await Promise.resolve().then(() => $e());await Promise.resolve().then(() => pe());await Promise.resolve().then(() => ht());await Promise.resolve();let{config:c}=Q({args:{command:"contract",subcommand:void 0,positionals:[],flags:{network:e}}}),d=ce(ae(r)),l=Buffer.from(d.seed,"hex"),u=d.addresses[e],p=t?Hr():z("Checking wallet..."),m=ve();try{let f=(await m.unshielded(u,c)).balances.get(cr)??0n;if(f===0n)throw p.fail("No NIGHT balance"),Error(`Wallet has 0 NIGHT on ${e}.
|
|
898
905
|
|
|
899
906
|
Fund your wallet before deploying:
|
|
900
907
|
Address: ${u}
|
|
@@ -905,63 +912,63 @@ Run "midnight help contract" for more info.`);switch(r){case"inspect":return yh(
|
|
|
905
912
|
Register for dust generation:
|
|
906
913
|
Run: midnight dust register --network ${e}
|
|
907
914
|
Then wait: midnight dust status --network ${e}
|
|
908
|
-
`);p.stop(`Wallet OK (${f} NIGHT, dust available)`)}catch(y){throw p.fail("Wallet check failed"),y}}async function
|
|
909
|
-
`+
|
|
915
|
+
`);p.stop(`Wallet OK (${f} NIGHT, dust available)`)}catch(y){throw p.fail("Wallet check failed"),y}}async function bl(e,t,r){await Promise.resolve().then(() => Xn());let s=t?Hr():z("Starting mn serve..."),o=await Yn({network:e,wallet:r,onMessage:(i)=>s.update(i)});return s.stop("mn serve ready (port "+o.port+")"),{port:o.port,stop:()=>o.stop()}}async function jh(e){let t=D(e,"json"),r=ns(k(e,"path")??process.cwd()),n=ss(e),s=k(e,"name");await Promise.resolve().then(() => jr());await Promise.resolve().then(() => pe());if(!t)process.stderr.write(`
|
|
916
|
+
`+U("Contract Deploy")+`
|
|
910
917
|
|
|
911
|
-
`);let{info:a}=
|
|
918
|
+
`);let{info:a}=at(n,s),c=a.witnesses.map((h)=>h.name);if(c.length>0){await Promise.resolve().then(() => Wo());if(!sl(r))throw Error(ol({projectRoot:r,witnessNames:c}))}let d=k(e,"network")??"undeployed",{config:l}=Q({args:{command:"contract",subcommand:"deploy",positionals:[],flags:{network:d}}}),u=k(e,"args"),p=[];if(u)try{let h=JSON.parse(u);p=Array.isArray(h)?h:Object.values(h)}catch(h){throw new W(`Invalid --args JSON: ${h.message}`)}let m=k(e,"secret-key");if(m!==void 0&&!/^[0-9a-fA-F]{64}$/.test(m))throw new W("--secret-key must be 32 bytes of hex (64 chars)");if(!t){if(process.stderr.write(C("Contract",a.name)+`
|
|
912
919
|
`),process.stderr.write(C("Network",d)+`
|
|
913
920
|
`),p.length>0)process.stderr.write(C("Constructor args",String(p.length))+`
|
|
914
921
|
`);process.stderr.write(`
|
|
915
|
-
`)}await
|
|
922
|
+
`)}await Sl(d,t,k(e,"wallet"));let y=await bl(d,t,k(e,"wallet")),f=t?Hr():z("Deploying contract...");try{let h=await ts({dappDir:r,networkConfig:l,managedDir:a.managedDir,contractName:a.name,servePort:y.port,args:p,privateStateSecretKey:m,onMessage:(w)=>f.update(w)});if(f.stop(B("✓")+" Contract deployed"),t)I({subcommand:"deploy",contractName:a.name,address:h.contractAddress,network:d});else process.stderr.write(`
|
|
916
923
|
`),process.stderr.write(C("Address",h.contractAddress)+`
|
|
917
924
|
`),process.stderr.write(`
|
|
918
|
-
`+
|
|
919
|
-
`),
|
|
920
|
-
`)}catch(h){throw f.fail("Deploy failed"),h}finally{await y.stop()}}function
|
|
925
|
+
`+B(" ✓ Deploy successful")+`
|
|
926
|
+
`),Hh(h.contractAddress,a.circuits,d),process.stdout.write(h.contractAddress+`
|
|
927
|
+
`)}catch(h){throw f.fail("Deploy failed"),h}finally{await y.stop()}}function Hh(e,t,r){let n=r==="undeployed"?"":` --network ${r}`;process.stderr.write(`
|
|
921
928
|
`+g(" Next:")+`
|
|
922
|
-
`),process.stderr.write(g(" mn contract state --address ")+
|
|
923
|
-
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(g(" mn contract call --address ")+
|
|
929
|
+
`),process.stderr.write(g(" mn contract state --address ")+G(e)+g(n)+`
|
|
930
|
+
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(g(" mn contract call --address ")+G(e)+g(" --circuit ")+G(s.name)+g(n)+`
|
|
924
931
|
`);process.stderr.write(`
|
|
925
|
-
`)}async function
|
|
926
|
-
`+
|
|
932
|
+
`)}async function Kh(e){let t=D(e,"json"),r=ns(k(e,"path")??process.cwd()),n=ss(e),s=k(e,"name"),o=Vr(e,"address","contract address"),i=Vr(e,"circuit","circuit name"),a=k(e,"args");await Promise.resolve().then(() => jr());await Promise.resolve().then(() => pe());if(!t)process.stderr.write(`
|
|
933
|
+
`+U("Contract Call")+`
|
|
927
934
|
|
|
928
|
-
`);let{info:l}=
|
|
935
|
+
`);let{info:l}=at(n,s),u=[];if(a)try{let h=JSON.parse(a);u=Array.isArray(h)?h:Object.values(h)}catch(h){throw new W(`Invalid --args JSON: ${h.message}`)}let p=k(e,"network")??"undeployed",{config:m}=Q({args:{command:"contract",subcommand:"call",positionals:[],flags:{network:p}}});if(!t)process.stderr.write(C("Contract",l.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 Sl(p,t,k(e,"wallet"));let y=await bl(p,t,k(e,"wallet")),f=t?Hr():z(`Calling ${i}...`);try{let h=await rs({dappDir:r,networkConfig:m,managedDir:l.managedDir,contractName:l.name,contractAddress:o,circuit:i,args:u,servePort:y.port,onMessage:(w)=>f.update(w)});if(f.stop(B("✓")+` ${i} called`),t)I({subcommand:"call",contractName:l.name,circuit:i,address:o,network:p,status:h.status});else process.stderr.write(`
|
|
940
|
+
`+B(" ✓ Circuit call successful")+`
|
|
934
941
|
|
|
935
|
-
`)}catch(h){throw f.fail("Call failed"),h}finally{await y.stop()}}async function
|
|
936
|
-
`+
|
|
942
|
+
`)}catch(h){throw f.fail("Call failed"),h}finally{await y.stop()}}async function Gh(e){let t=D(e,"json"),r=ns(k(e,"path")??process.cwd()),n=ss(e),s=k(e,"name"),o=Vr(e,"address","contract address");await Promise.resolve().then(() => pe());await Promise.resolve().then(() => jr());let c=k(e,"network")??"undeployed",{config:d}=Q({args:{command:"contract",subcommand:"state",positionals:[],flags:{network:c}}});if(!t)process.stderr.write(`
|
|
943
|
+
`+U("Contract State")+`
|
|
937
944
|
|
|
938
945
|
`),process.stderr.write(C("Address",o.slice(0,20)+"...")+`
|
|
939
946
|
`),process.stderr.write(C("Network",c)+`
|
|
940
947
|
|
|
941
|
-
`);let l=t?Hr():
|
|
942
|
-
`);for(let[f,h]of Object.entries(p.fields))process.stderr.write(` ${f}: ${
|
|
948
|
+
`);let l=t?Hr():z("Querying contract state...");try{let{info:u}=at(n,s),p=await rr({dappDir:r,networkConfig:d,managedDir:u.managedDir,contractName:u.name,contractAddress:o,onMessage:(m)=>l.update(m)});if(l.stop(B("✓")+" State retrieved"),t)I({subcommand:"state",address:o,network:c,...p});else{let m=Object.keys(p.fields).length>0,y=Object.keys(p.maps).length>0;if(m||y){process.stderr.write(_(" Ledger State")+`
|
|
949
|
+
`);for(let[f,h]of Object.entries(p.fields))process.stderr.write(` ${f}: ${G(h)}
|
|
943
950
|
`);for(let[f,h]of Object.entries(p.maps))process.stderr.write(` ${f}: ${g(`Map (${h.size} entries)`)}
|
|
944
951
|
`)}else process.stderr.write(g(" (no ledger fields found)")+`
|
|
945
952
|
`);process.stderr.write(`
|
|
946
|
-
`)}}catch(u){l.stop(ee("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() =>
|
|
953
|
+
`)}}catch(u){l.stop(ee("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() => hl());let y=await gl(d).queryContractState(o);if(!y)throw Error(`No contract found at address ${o} on ${c}`);let f=y.data??y;if(t)I({subcommand:"state",address:o,network:c,raw:f});else process.stderr.write(_(" Raw State")+`
|
|
947
954
|
`),process.stderr.write(g(" (run from dApp root for parsed ledger fields)")+`
|
|
948
955
|
`),process.stderr.write(` ${JSON.stringify(f).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 wl;var kl=N(()=>{Fe();he();qe();Jn();wl=["inspect","deploy","call","state"]});import{existsSync as nr,readFileSync as Kr,readdirSync as Jh}from"node:fs";import{join as _t,resolve as Vh}from"node:path";function os(e){let t=Vh(e??process.cwd()),r=_t(t,Vo);if(!nr(r))throw Error(`No ${Vo} found in ${t}
|
|
958
|
+
Run this command from the root of a dApp project, or create a ${Vo} file.`);let n;try{n=JSON.parse(Kr(r,"utf-8"))}catch(o){throw Error(`Failed to parse ${r}: ${o.message}`)}return{config:Yh(n,r),configPath:r,dappDir:t}}function zo(e){let t=_t(e,zh);if(!nr(t))return[];let r=Jh(t,{withFileTypes:!0}),n=[];for(let s of r){if(!s.isDirectory())continue;let o=_t(t,s.name),i=_t(o,"suite.json");if(!nr(i))continue;let a;try{a=JSON.parse(Kr(i,"utf-8"))}catch(c){throw Error(`Failed to parse ${i}: ${c.message}`)}n.push({suite:Xh(a,i),suiteDir:o})}return n}function Tl(e){let t=_t(e,"assertions.json");if(!nr(t))return null;let r;try{r=JSON.parse(Kr(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return Zh(r,t)}function Nl(e){let t=_t(e,"actions.json");if(!nr(t))return null;let r;try{r=JSON.parse(Kr(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return Qh(r,t)}function Rl(e){let t=_t(e,"prompt.md");if(!nr(t))return null;return Kr(t,"utf-8")}function Yh(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&&!Cl.includes(r.network))throw Error(`${t}: "network" must be one of: ${Cl.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"||!qh.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 Xh(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(!El.includes(r.strategy))throw Error(`${t}: "strategy" must be one of: ${El.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&&!xl.includes(r.browserMode))throw Error(`${t}: "browserMode" must be one of: ${xl.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 Zh(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 Qh(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"||!Al.includes(s.type))throw Error(`${t}: action "${s.id}" has invalid type "${s.type}". Valid: ${Al.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 Vo="dapp.test.json",zh="tests/suites",Cl,El,xl,qh,Al;var Dl=N(()=>{Cl=["undeployed","preprod","preview"],El=["browser","cli","hybrid"],xl=["dom","script","vision","auto"],qh=/^(cache-clear|localnet-up|balance:\d+|dust|dust-register|dust-wait|mn-serve|build-and-serve)$/;Al=["contract-deploy","contract-call","contract-state","wallet-cmd"]});function Il(){let e=[];return{cleanups:e,addCleanup(t){e.push(t)}}}import{setTimeout as ew}from"node:timers/promises";async function is(e,t,r){let n=Date.now()+r.timeoutMs,s=r.intervalMs??2000;for(;;){let o=await e();if(o>=t)return o;let i=n-Date.now();if(i<=0)return o;r.onBalance?.(o),await ew(Math.min(s,i))}}var qo=()=>{};async function _l(e,t){try{return await fetch(e,{signal:AbortSignal.timeout(t)}),!0}catch{return!1}}import{spawn as tw}from"node:child_process";import{createWriteStream as rw}from"node:fs";import{join as nw}from"node:path";import sw from"node:http";import ow from"node:net";async function $l(e){let{dappDir:t,buildCmd:r,buildDir:n=".",port:s,url:o,logFile:i,timeoutMs:a=240000,onMessage:c=()=>{}}=e;if(await iw(s)){if(await Pl(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 aw(s),await new Promise((f)=>setTimeout(f,2000))}let d=nw(t,n),l=rw(i,{flags:"a"}),u=tw("bash",["-lc",r],{cwd:d,stdio:["ignore","pipe","pipe"],detached:!1});u.stdout?.pipe(l),u.stderr?.pipe(l);let p=!1,m=null;u.on("exit",(f)=>{p=!0,m=f}),c(`Building (${r})...`);let y=Date.now()+a;while(Date.now()<y){if(p)throw Error(`Build process exited with code ${m} before the UI was ready.
|
|
959
|
+
Check the build log: ${i}`);if(await Pl(o))return c("UI ready"),{port:s,child:u,stop(){if(!p)u.kill("SIGTERM"),setTimeout(()=>{if(!p)u.kill("SIGKILL")},5000).unref();l.end()}};await new Promise((f)=>setTimeout(f,2000))}throw u.kill("SIGTERM"),l.end(),Error(`UI did not start within ${Math.round(a/1000)}s at ${o}
|
|
960
|
+
Check the build log: ${i}`)}function iw(e){return new Promise((t)=>{let r=new ow.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 aw(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 Pl(e){return new Promise((t)=>{let r=sw.get(e,{timeout:3000},(n)=>{t(n.statusCode===200),n.resume()});r.on("error",()=>t(!1)),r.on("timeout",()=>{r.destroy(),t(!1)})})}var Ol=()=>{};import*as Bl from"@midnight-ntwrk/ledger-v8";import{join as cw}from"node:path";import{setTimeout as dw}from"node:timers/promises";async function Wl(e,t,r,n){let s=[];for(let o of e.prep){let i=Date.now();n.onStepStart(o);try{await lw(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 lw(e,t,r,n,s){if(e==="cache-clear")return uw(t);if(e==="localnet-up")return mw(s);if(e.startsWith("balance:")){let o=parseInt(e.split(":")[1],10);return gw(o,t,s)}if(e==="dust"||e==="dust-register"||e==="dust-wait")return hw(t,s);if(e==="mn-serve")return ww(t,n,s);if(e==="build-and-serve")return yw(t,r,n,s);throw Error(`Unknown prep step: ${e}`)}async function uw(e){let t=e.network??"undeployed";Je(void 0,t)}async function Fl(e,t){let r=Date.now();while(Date.now()-r<e){if(await _l(fw,3000))return!0;t?.("Waiting for indexer..."),await dw(2000)}return!1}async function mw(e){Ln(),Bn();let t=["node","indexer","proof-server"],r=Rt();if(r.length>=3&&t.every((i)=>r.some((a)=>a.name===i&&a.state==="running"))&&r.every((i)=>!i.health||i.health==="healthy")){if(await Fl(1e4,(i)=>e.onMessage(i))){e.onMessage("Localnet OK (3 services healthy, indexer responding)");return}e.onMessage("Localnet containers running but indexer not responding. Restarting...")}let s=r.filter((i)=>i.state==="running").map((i)=>i.name),o=t.filter((i)=>!s.includes(i));if(o.length>0)e.onMessage(`Localnet missing: ${o.join(", ")}. Restarting clean...`);else e.onMessage("Localnet unhealthy. Restarting clean...");for(let i=1;i<=as;i++){e.onMessage(`Attempt ${i}/${as}: tearing down...`),it("down"),e.onMessage(`Attempt ${i}/${as}: starting...`),it("up -d");let a=Wn(pw);if(a&&await Fl(Ml,(p)=>e.onMessage(p))){e.onMessage("Localnet running (indexer verified)");return}if(a){e.onMessage(`Attempt ${i}: Docker healthy but indexer not responding after ${Ml/1000}s`);continue}let c=Rt(),d=t.filter((p)=>!c.some((m)=>m.name===p&&m.state==="running")),l=c.filter((p)=>p.state==="running"&&p.health&&p.health!=="healthy"),u=[];if(d.length>0)u.push(`not running: ${d.join(", ")}`);if(l.length>0)u.push(`unhealthy: ${l.map((p)=>p.name).join(", ")}`);e.onMessage(`Attempt ${i} failed: ${u.join("; ")||"timeout"}`)}throw Error(`Localnet failed to start after ${as} attempts`)}async function gw(e,t,r){let n=t.network??"undeployed",{config:s}=Q({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:n}}}),o=ce(ae()),i=Buffer.from(o.seed,"hex"),a=o.addresses[n];r.onMessage("Checking balance...");let c=xe((y,f)=>{r.onMessage(`SDK: ${f}`)}),d=De();st(n,s.indexerWS);let l=mt(a,n),u=await Ge(i,s,l);try{let y=await ft(u,{syncMode:"lite",onProgress:(w,b)=>{if(b>0){let S=Math.min(Math.round(w/b*100),100);r.onMessage(`Syncing wallet... ${S}%`)}},onSyncDetail:(w)=>{r.onMessage(`Syncing wallet... (${w})`)}}),f=Bl.unshieldedToken().raw,h=y.unshielded.balances[f]??0n;if(h>0n){r.onMessage(`Balance OK: ${h}`);try{await gt(a,n,u.facade)}catch{}return}}finally{d(),c();try{await Oe(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 p=Buffer.from(
|
|
962
|
+
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let p=Buffer.from(Qe,"hex"),m=Se(p,n);await Qt({seedBuffer:p,networkConfig:s,recipientAddress:a,amountNight:e,onSync(y,f){},onDust(y){r.onMessage(`Dust: ${y}`)},onProving(){r.onMessage("Generating ZK proof...")},onSubmitting(){r.onMessage("Submitting airdrop transaction...")},onSyncWarning(y,f){r.onMessage(`Syncing genesis... (${f})`)}}),r.onMessage(`Airdropped ${e} NIGHT`)}async function hw(e,t){let r=e.network??"undeployed",{config:n}=Q({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}}),s=ce(ae()),o=Buffer.from(s.seed,"hex"),i=s.addresses[r],a=xe(),c=De();st(r,n.indexerWS);let d=mt(i,r),l=await Ge(o,n,d);try{if(t.onMessage("Syncing wallet..."),await ft(l,{syncMode:"lite"}),t.onMessage("Ensuring dust..."),(await Ze(l,(y)=>t.onMessage(`Dust: ${y}`))).alreadyAvailable)t.onMessage("Dust already available");else{t.onMessage("Dust registered. Waiting for coins to become available...");let y=await kn(l,Ul);if(!(()=>{try{let h=y.dust;return h?.availableCoins?.length>0||h?.balance(new Date)>0n}catch{return!1}})()){if(r!=="undeployed")throw Error(`Dust not available on ${r}. Register dust and wait for it to generate:
|
|
956
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 ${Ul/1000}s. The chain may be slow — try again.`)}}let p=wt(Te),m=await is(()=>Ka(l),Te,{timeoutMs:Ll,onBalance:(y)=>t.onMessage(`Dust: ${wt(y)} of the ${p} DUST a transaction needs, accruing...`)});if(m<Te)throw Error(`Only ${wt(m)} DUST after ${Ll/1000}s, and a transaction needs ${p}. Dust accrues with time, faster the more NIGHT is registered: run the suite again in a while, or fund the wallet with more NIGHT.`);t.onMessage("Dust is available");try{await gt(i,r,l.facade)}catch{}}finally{c(),a();try{await Oe(l)}catch{}}}async function ww(e,t,r){r.onMessage("Starting mn serve...");let n=await Yn({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 yw(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=cw(t,"tests","results",`build_${Date.now()}.log`),a=await $l({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 pw=30000,as=2,Ml=30000,fw,Ul=90000,Ll=180000;var jl=N(()=>{_r();At();$e();pe();Ao();Ye();At();Nt();qo();je();Xn();Ol();fw=`http://localhost:8088${Mt}`});import{execSync as Hl,spawn as Sw}from"node:child_process";import{createWriteStream as bw,existsSync as vw,mkdirSync as kw,readFileSync as Cw}from"node:fs";import{dirname as Ew,join as xw}from"node:path";import{homedir as Aw}from"node:os";function Tw(){let e=xw(Aw(),".claude.json");if(!vw(e))return!1;try{let t=JSON.parse(Cw(e,"utf-8"));return Boolean(t.mcpServers?.["chrome-devtools"])}catch{return!1}}function Rw(e){let t;try{t=Hl(`ps -ax -o pid,command | grep "${Nw}" | 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{Hl(`kill ${n}`,{stdio:"pipe"})}catch{}}function Yo(e){let t=e.browserMode??"vision";if(t==="auto")return"vision";return t}async function Kl(e){let{suite:t,prompt:r,dappDir:n,logFile:s,onMessage:o=()=>{}}=e,i=(t.timeout??600)*1000,a=Yo(t);if(a==="dom"||a==="script"){if(!Tw())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).");Rw(o)}kw(Ew(s),{recursive:!0});let c=bw(s),d=[];if(a==="vision")d.push("--chrome");if(d.push("--dangerously-skip-permissions"),t.model)d.push("--model",t.model);if(t.effort)d.push("--effort",t.effort);let l=r;if(a==="dom")l=Dw+r;else if(a==="script")l=Iw+r;return d.push("-p",l),o(`Launching Claude (mode: ${a}, model: ${t.model??"default"}, timeout: ${t.timeout??600}s)`),new Promise((u)=>{let p=Sw("claude",d,{cwd:n,stdio:["inherit","pipe","inherit"]}),m=!1;p.stdout?.on("data",(f)=>{process.stdout.write(f),c.write(f)});let y=setTimeout(()=>{m=!0,o(`Timeout: test exceeded ${t.timeout??600}s`),p.kill("SIGTERM"),setTimeout(()=>{if(!p.killed)p.kill("SIGKILL")},1e4).unref()},i);p.on("close",(f)=>{clearTimeout(y),c.end(),u({exitCode:f??1,logFile:s,timedOut:m})}),p.on("error",(f)=>{clearTimeout(y),c.end(),o(_w(f)),u({exitCode:1,logFile:s,timedOut:!1})})})}function _w(e){if(e.code==="ENOENT")return'The browser strategy drives the dApp through the Claude Code CLI, and no "claude" command was found on PATH. Install Claude Code, or test from the command line instead: mn test create --strategy cli';return`Claude process error: ${e.message}`}var Nw="chrome-devtools-mcp/chrome-profile",Dw="## 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",Iw="## 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 Gl=()=>{};import{existsSync as Pw,readFileSync as $w}from"node:fs";import Ow from"node:net";async function Jl(e,t){let r=[];for(let n of e)try{let s=await Mw(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 Mw(e,t){switch(e.type){case"balance-changed":return Fw(e,t);case"process-exit-code":return Uw(e,t);case"port-listening":return Lw(e);case"agent-report-no-failure":return Ww(e,t);default:throw Error(`Unsupported assertion type: "${e.type}" (available in v2)`)}}function Fw(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 Uw(e,t){if(t.processExitCode===void 0)throw Error("Process exit code not available");let r=e.params.code;return t.processExitCode===r}function Lw(e){let t=e.params.port;return new Promise((r)=>{let n=new Ow.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 Ww(e,t){let r=e.params??{},n=r.logPath??t.agentLogPath;if(!n||!Pw(n))return!0;let s;try{s=$w(n,"utf-8")}catch{return!0}let o=Hw(s),i=r.markers??Bw;for(let a of i)if(jw(o,a))return!1;return!0}function jw(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 Hw(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"")}var Bw;var Vl=N(()=>{Bw=["FAILED","❌","did not pass","test failed","overall: fail","result: fail"]});import{existsSync as Kw,mkdirSync as Gw,writeFileSync as Jw,readFileSync as Vw,readdirSync as zw}from"node:fs";import{join as cs}from"node:path";function ql(e,t){let r=cs(t,zl);Gw(r,{recursive:!0});let n=`${e.suite}_${e.timestamp.replace(/[:.]/g,"-")}.json`,s=cs(r,n);return Jw(s,JSON.stringify(e,null,2)+`
|
|
971
|
+
`),s}function Yl(e,t){let r=Xo(e,t);return r.length>0?r[0]:null}function Xo(e,t){let r=cs(e,zl);if(!Kw(r))return[];let n=zw(r).filter((o)=>o.endsWith(".json")&&!o.startsWith(".")).filter((o)=>!t||o.startsWith(t+"_")),s=[];for(let o of n)try{let i=JSON.parse(Vw(cs(r,o),"utf-8"));if(qw(i))s.push(i)}catch{}return s.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),s}function qw(e){let t=e;return typeof t==="object"&&t!==null&&typeof t.suite==="string"&&typeof t.timestamp==="string"&&(t.status==="pass"||t.status==="fail")&&Array.isArray(t.prep)&&Array.isArray(t.assertions)}var zl="tests/results";var Xl=()=>{};import{execSync as Yw}from"node:child_process";async function Zo(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)Xw(e.buildHandle.port,t)}function Xw(e,t){try{Yw(`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 Zl=()=>{};function Ql(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(Ql);default:return null}}function Qo(e){let t={};for(let r of e.arguments)t[r.name]=Ql(r.type);return t}function ei(e,t){if((t.strategy??"cli")==="browser"){if(!t.browser)throw Error("Browser strategy requires browser options (port, buildCmd, buildDir?, url?)");return sy(t,t.browser)}return ny(e,t)}function ny(e,t){let r=t.suiteName??Zw,n=t.network??eu,s=t.servePort??tu;return{dappConfig:{name:t.contractName,network:n,prep:ru},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??ey},actions:{actions:iy(e)},assertions:{post:[nu(s)]},prompt:null,suiteName:r}}function sy(e,t){let r=e.suiteName??Qw,n=e.network??eu,s=e.servePort??tu,o=t.url??`http://localhost:${t.port}/`,i={name:e.contractName,network:n,port:t.port,buildCmd:t.buildCmd,url:o,prep:ry};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??ty,...t.browserMode?{browserMode:t.browserMode}:{}},actions:null,assertions:{post:[{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"},nu(s),{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}]},prompt:oy(e.contractName,o),suiteName:r}}function nu(e){return{id:"serve-port-listening",type:"port-listening",params:{port:e},expect:"pass"}}function oy(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 iy(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=Qo(n);t.push(s)}return t.push({id:"check-final",type:"contract-state"}),t}var eu="undeployed",Zw="cli-default",Qw="ui-default",ey=300,ty=600,tu=9932,ru,ry;var ti=N(()=>{ru=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],ry=[...ru,"build-and-serve"]});import{existsSync as ou,mkdirSync as ay,readFileSync as cy,writeFileSync as su}from"node:fs";import{join as sr}from"node:path";function iu(e,t){let{dappDir:r,force:n=!1}=t,s=sr(r,"tests","suites",e.suiteName),o=sr(r,"dapp.test.json"),i=[{path:sr(s,"suite.json"),kind:"json",body:e.suite},{path:sr(s,"assertions.json"),kind:"json",body:e.assertions}];if(e.actions)i.push({path:sr(s,"actions.json"),kind:"json",body:e.actions});if(e.prompt)i.push({path:sr(s,"prompt.md"),kind:"text",body:e.prompt});if(!n){let l=i.filter((u)=>ou(u.path)).map((u)=>u.path);if(l.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
1012
|
`+l.map((u)=>` - ${u}`).join(`
|
|
1006
|
-
`))}let a=
|
|
1013
|
+
`))}let a=uy(o,e,n);ay(s,{recursive:!0});let c=[],d=[];if(a.action==="write")su(o,JSON.stringify(a.config,null,2)+`
|
|
1007
1014
|
`),c.push(o);else d.push(o);for(let l of i){let u=l.kind==="json"?JSON.stringify(l.body,null,2)+`
|
|
1008
|
-
`:l.body;
|
|
1009
|
-
Fix or remove it (or pass --force to overwrite).`)}if(n.name!==t.dappConfig.name)throw Error(`${e} exists with name "${String(n.name)}" but this scaffold targets "${t.dappConfig.name}". Use --force to overwrite, or run from the right project directory.`);return{action:"preserve"}}var
|
|
1010
|
-
`+
|
|
1011
|
-
`);for(;;){let e=(await
|
|
1012
|
-
`))}}async function
|
|
1015
|
+
`:l.body;su(l.path,u),c.push(l.path)}return{written:c,preserved:d}}function ly(e,t){if(!t.prep.includes(ri))return null;let r={};for(let s of dy)if(t[s]!==void 0&&e[s]===void 0)Object.assign(r,{[s]:t[s]});let n=Array.isArray(e.prep)?e.prep:[];if(!n.includes(ri))r.prep=[...n,ri];return Object.keys(r).length>0?r:null}function uy(e,t,r){if(r||!ou(e))return{action:"write",config:t.dappConfig};let n;try{n=JSON.parse(cy(e,"utf-8"))}catch(o){let i=o instanceof Error?o.message:String(o);throw Error(`${e} exists but is not valid JSON: ${i}
|
|
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.`);let s=ly(n,t.dappConfig);return s===null?{action:"preserve"}:{action:"write",config:{...n,...s}}}var dy,ri="build-and-serve";var au=N(()=>{dy=["port","buildCmd","buildDir","url"]});import{existsSync as du,readdirSync as py,readFileSync as fy,statSync as my}from"node:fs";import{basename as gy,extname as hy,join as lu,relative as wy}from"node:path";function uu(e){let t=new Map;for(let r of yy){let n=lu(e,r);if(!du(n))continue;ni(n,e,t)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function pu(e,t=e){if(!du(e))return[];let r=new Map;return ni(e,t,r),[...r.values()].sort((n,s)=>n.name.localeCompare(s.name))}function ni(e,t,r){let n;try{n=py(e)}catch{return}for(let s of n){let o=lu(e,s),i;try{i=my(o)}catch{continue}if(i.isDirectory()){if(Sy.has(s.toLowerCase()))continue;ni(o,t,r);continue}if(hy(s)!==cu)continue;if(s.endsWith(".test.tsx")||s.endsWith(".spec.tsx"))continue;let a=gy(s,cu);if(!by(a,o))continue;let c=ky(a);if(r.has(c))continue;r.set(c,{name:c,component:a,path:o,relativePath:wy(t,o)})}}function by(e,t){if(!/^[A-Z][A-Za-z0-9]*$/.test(e))return!1;let r;try{r=fy(t,"utf-8")}catch{return!1}return vy.test(r)}function ky(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}var yy,cu=".tsx",Sy,vy;var si=N(()=>{yy=["src/components","src/pages","src/screens","src/views"];Sy=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 Cy,statSync as Ey}from"node:fs";import*as fu from"node:readline";function mu(){return process.stdin.isTTY===!0}function ze(e,t){let r=fu.createInterface({input:process.stdin,output:process.stderr}),n=t!==void 0?g(` [${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 gu(){process.stderr.write(`
|
|
1017
|
+
`+G("Test scaffold setup")+`
|
|
1018
|
+
`);for(;;){let e=(await ze("Strategy? cli or ui","cli")).toLowerCase();if(e==="cli")return"cli";if(e==="ui"||e==="browser")return"browser";process.stderr.write(g(` Unknown strategy "${e}". Pick "cli" or "ui".
|
|
1019
|
+
`))}}async function hu(e={}){process.stderr.write(`
|
|
1013
1020
|
`+g("Browser test scaffold needs your dApp UI details:")+`
|
|
1014
|
-
`);let t=e.port!==void 0?String(e.port):await
|
|
1015
|
-
`+
|
|
1021
|
+
`);let t=e.port!==void 0?String(e.port):await ze("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 ze("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 ze("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await ze("URL",`http://localhost:${r}/`),a=e.browserMode??await xy();return{port:r,buildCmd:n,buildDir:o,url:i,browserMode:a}}async function xy(){process.stderr.write(`
|
|
1022
|
+
`+G("Browser mode — how should Claude perceive the page?")+`
|
|
1016
1023
|
`),process.stderr.write(` ${g("1.")} dom ${g("— accessibility tree (text). Fast. HTML / React / Vue UIs.")}
|
|
1017
1024
|
`),process.stderr.write(` ${g("2.")} vision ${g("— screenshots. Slow. Canvas games (no DOM).")}
|
|
1018
1025
|
`),process.stderr.write(` ${g("3.")} script ${g("— direct JS. Fastest. Needs dApp-side hooks (advanced).")}
|
|
1019
1026
|
`),process.stderr.write(g(` dom and script need chrome-devtools-mcp installed.
|
|
1020
|
-
`));for(;;){let e=(await
|
|
1021
|
-
`))}}async function
|
|
1027
|
+
`));for(;;){let e=(await ze("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(ee(` Pick 1 (dom), 2 (vision), or 3 (script).
|
|
1028
|
+
`))}}async function wu(e){let t=e.filter((r)=>!r.pure);if(t.length===0){process.stderr.write(g(` No impure circuits in this contract — nothing to test as a write path.
|
|
1022
1029
|
`));return}process.stderr.write(`
|
|
1023
|
-
`+
|
|
1030
|
+
`+G("Pick the circuit this suite will exercise:")+`
|
|
1024
1031
|
`);for(let r=0;r<t.length;r++)process.stderr.write(` ${g(`${r+1}.`)} ${t[r].name}
|
|
1025
1032
|
`);process.stderr.write(g(` (or type "skip" to scaffold all circuits without AI)
|
|
1026
|
-
`));for(;;){let r=(await
|
|
1027
|
-
`))}}async function
|
|
1028
|
-
`+
|
|
1033
|
+
`));for(;;){let r=(await ze("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(g(` Pick a number 1–${t.length}, the circuit name, or "skip".
|
|
1034
|
+
`))}}async function oi(e){if(e.length===0)return Ay();process.stderr.write(`
|
|
1035
|
+
`+G("Pick the screen this suite will test:")+`
|
|
1029
1036
|
`);for(let t=0;t<e.length;t++)process.stderr.write(` ${g(`${t+1}.`)} ${e[t].name} ${g(`(${e[t].relativePath})`)}
|
|
1030
1037
|
`);process.stderr.write(g(` (or type "skip" to scaffold a generic prompt.md without AI)
|
|
1031
|
-
`));for(;;){let t=(await
|
|
1032
|
-
`))}}async function
|
|
1038
|
+
`));for(;;){let t=(await ze("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(g(` Pick a number 1–${e.length}, the screen name, or "skip".
|
|
1039
|
+
`))}}async function Ay(){process.stderr.write(g(`
|
|
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 ze('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!Cy(e)){process.stderr.write(g(` No such path: ${e}
|
|
1042
|
+
`));continue}let t;try{t=Ey(e)}catch{process.stderr.write(g(` Cannot stat: ${e}
|
|
1043
|
+
`));continue}if(t.isDirectory()){let r=pu(e);if(r.length===0){process.stderr.write(g(` No PascalCase .tsx components in ${e}
|
|
1044
|
+
`));continue}return oi(r)}if(!e.endsWith(".tsx")){process.stderr.write(g(` Not a .tsx file: ${e}
|
|
1045
|
+
`));continue}return Ny(e)}}async function yu(){let e=(await ze("What does success look like? (one line, optional)")).trim();return e===""?void 0:e}async function ii(e){for(;;){let t=(await ze("Suite name",e)).trim();if(Ty(t))return t;process.stderr.write(ee(` Suite names must be kebab-case (a–z, 0–9, dashes, underscores). Try again.
|
|
1046
|
+
`))}}function Ty(e){return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e)}function Ny(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 Su=N(()=>{si()});function ku(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
|
|
@@ -1141,9 +1148,9 @@ 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
|
+
${vu}
|
|
1145
1152
|
|
|
1146
|
-
Now produce the JSON.`}function
|
|
1153
|
+
Now produce the JSON.`}function Cu(e){let{contractName:t,contractSummary:r,screenComponent:n,screenSource:s,relatedSources:o,url:i,goal:a}=e,c=(o??[]).map((u)=>`
|
|
1147
1154
|
--- ${u.path} ---
|
|
1148
1155
|
${u.source}
|
|
1149
1156
|
--- end ${u.path} ---`).join(`
|
|
@@ -1220,28 +1227,28 @@ 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
|
+
${vu}
|
|
1224
1231
|
|
|
1225
|
-
Now produce the JSON.`}function
|
|
1226
|
-
`)}var
|
|
1232
|
+
Now produce the JSON.`}function ai(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 bu="```json",vu;var Eu=N(()=>{vu=`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.`});function rr(e,t){if(t.length===0)return{byCircuit:new Map};let r=ny(e),n=sy(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,l]of n){o.set(d,new Set),i.set(d,new Set);for(let u of iy(l.body,l.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,l]of i){let u=o.get(d);for(let p of l)for(let m of o.get(p)??[])if(!u.has(m))u.add(m),a=!0}}let c=new Map;for(let[d,l]of n){if(!l.isCircuit)continue;let u=o.get(d);if(u&&u.size>0)c.set(d,[...u].sort())}return{byCircuit:c}}function ny(e){return e.replace(ry,"").replace(ty,"")}function sy(e){let t=new Map,r=/\b(circuit|function)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gms,n;while((n=r.exec(e))!==null){let s=n[1],o=n[2],i=n[3],a=n.index+n[0].length,c=e.indexOf("{",a);if(c<0)continue;let d=1,l=c+1;for(;l<e.length&&d>0;l++){let m=e[l];if(m==="{")d++;else if(m==="}")d--}if(d!==0)continue;let u=e.slice(c+1,l-1),p=oy(i);t.set(o,{body:u,argNames:p,isCircuit:s==="circuit"})}return t}function oy(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 iy(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 ty,ry,ay;var is=N(()=>{ty=/\/\/[^\n]*/g,ry=/\/\*[\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 wu={};fe(wu,{claudeSubprocessRunner:()=>si,findContractSourcePath:()=>oi,generateCliScaffoldWithAI:()=>Sy,generateUiScaffoldWithAI:()=>by,isClaudeAvailable:()=>my});import{execFileSync as cy,spawn as dy}from"node:child_process";import{existsSync as ni,readdirSync as ly,readFileSync as lu}from"node:fs";import{dirname as nr,join as as}from"node:path";function my(){try{return cy("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function mu(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${nu} ... \`\`\` 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 gy(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=wy(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)"}`);hy(s,o)}return{actions:r}}function hy(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 wy(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 yy(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 Sy(e,t=si){let r=e.contractSourcePath&&ni(e.contractSourcePath)?lu(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((w)=>w.name),s=r?rr(r,n).byCircuit:new Map,o=e.targetCircuit?qo(e.targetCircuit):void 0,i=ou({contractName:e.contract.name,contractSummary:ri({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=mu(a),d=gy(c,e.contract),l=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${hu(e.goal)??"ai"}`),u=e.network??uu,p=e.servePort??pu,m={name:e.contract.name,network:u,prep:fu},y={name:l,description:c.description,strategy:"cli",timeout:uy},f=vy(c.assertions,p),h=[...s.entries()].filter(([w])=>w!==e.targetCircuit?.name).map(([w,b])=>({name:w,reason:`uses witness ${b.join(", ")} (private state — UI-only)`}));return{dappConfig:m,suite:y,actions:d,assertions:f,prompt:null,suiteName:l,excludedCircuits:h.length>0?h:void 0}}async function by(e,t=si){let r=e.screen?lu(e.screen.path,"utf-8"):void 0,n=iu({contractName:e.contract.name,contractSummary:ri({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=mu(s);yy(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${hu(e.goal)??"ai"}`),a=e.network??uu,c=e.servePort??pu,d=e.url,l={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:fy};if(e.buildDir)l.buildDir=e.buildDir;let u={name:i,description:o.description,strategy:"browser",timeout:py,...e.browserMode?{browserMode:e.browserMode}:{}},p=ky(o.assertions,c);return{dappConfig:l,suite:u,actions:null,assertions:p,prompt:o.prompt,suiteName:i}}function gu(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function vy(e,t){if(e.post.some((n)=>n.type==="port-listening"&&gu(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function ky(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"&&gu(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 hu(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 oi(e){let t=e.split("/").pop(),r=[nr(e),as(nr(e),"src"),nr(nr(e)),as(nr(nr(e)),"src")];for(let n of r){if(!ni(n))continue;if(t){let i=as(n,`${t}.compact`);if(ni(i))return i}let s;try{s=ly(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return as(n,o)}return}var uu="undeployed",pu=9932,uy=300,py=600,fu,fy,cu=300000,du=4194304,si=(e)=>new Promise((t,r)=>{let n=dy("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${cu/1000}s`))},cu);n.stdout?.on("data",(d)=>{if(i+=d.length,i>du){a=!0,n.kill("SIGTERM");return}s+=d.toString()}),n.stderr?.on("data",(d)=>{o+=d.toString()}),n.on("error",(d)=>{if(clearTimeout(c),d.code==="ENOENT"){r(Error("claude CLI not found on PATH. Install Claude Code (npm install -g @anthropic-ai/claude-code) or run mn test create without --goal / --screen for the deterministic scaffolder."));return}r(d)}),n.on("exit",(d,l)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${du/1024/1024}MB; aborted.`));return}if(l==="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 ii=N(()=>{au();Xo();is();fu=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],fy=[...fu,"build-and-serve"]});import{existsSync as yu,readFileSync as Su,writeFileSync as Cy,mkdirSync as Ey}from"node:fs";import{join as bu}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:l}=e,u=[],p=r.network??"undeployed",m;if(!a)m=Dy(n,s,p);let{info:y}=ot(n),f=Iy(y),h;for(let w of t){c?.(w);let b=Date.now();if(h&&(w.type==="contract-call"||w.type==="contract-state")){let S={id:w.id,type:w.type,status:"skip",duration:0,message:`cascaded skip — depends on ${h}`};u.push(S),d?.(w,S);continue}try{let S=await xy(w,{dappDir:n,networkConfig:o,managedDir:y.managedDir,contractName:y.name,servePort:i,contractAddress:m,witnessDeps:f,onMessage:l});if(S.contractAddress){if(m=S.contractAddress,_y(n,s,p,m),w.type==="contract-deploy")h=void 0}let v=Date.now()-b,R={...S,duration:v};if(u.push(R),d?.(w,R),S.status==="skip"&&w.type==="contract-call")h=`skipped action "${w.id}"`}catch(S){let v=Date.now()-b,R={id:w.id,type:w.type,status:"fail",duration:v,message:S.message};u.push(R),d?.(w,R);break}}return u}async function xy(e,t){switch(e.type){case"contract-deploy":return Ay(e,t);case"contract-call":return Ty(e,t);case"contract-state":return Ny(e,t);case"wallet-cmd":return Ry(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function Ay(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 Qn({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 Ty(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 Qt({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 es({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 Qt({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 Ny(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await Qt({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)ai(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);ai(s,a,o,n)}catch{ai(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 or(e,t){if(t.length===0)return{byCircuit:new Map};let r=Iy(e),n=_y(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,l]of n){o.set(d,new Set),i.set(d,new Set);for(let u of $y(l.body,l.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,l]of i){let u=o.get(d);for(let p of l)for(let m of o.get(p)??[])if(!u.has(m))u.add(m),a=!0}}let c=new Map;for(let[d,l]of n){if(!l.isCircuit)continue;let u=o.get(d);if(u&&u.size>0)c.set(d,[...u].sort())}return{byCircuit:c}}function Iy(e){return e.replace(Dy,"").replace(Ry,"")}function _y(e){let t=new Map,r=/\b(circuit|function)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gms,n;while((n=r.exec(e))!==null){let s=n[1],o=n[2],i=n[3],a=n.index+n[0].length,c=e.indexOf("{",a);if(c<0)continue;let d=1,l=c+1;for(;l<e.length&&d>0;l++){let m=e[l];if(m==="{")d++;else if(m==="}")d--}if(d!==0)continue;let u=e.slice(c+1,l-1),p=Py(i);t.set(o,{body:u,argNames:p,isCircuit:s==="circuit"})}return t}function Py(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 $y(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(Oy.has(o)||t.has(o))continue;r.add(o)}return r}var Ry,Dy,Oy;var ds=N(()=>{Ry=/\/\/[^\n]*/g,Dy=/\/\*[\s\S]*?\*\//g;Oy=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var $u={};fe($u,{claudeSubprocessRunner:()=>di,findContractSourcePath:()=>li,generateCliScaffoldWithAI:()=>Vy,generateUiScaffoldWithAI:()=>zy,isClaudeAvailable:()=>jy});import{execFileSync as My,spawn as Fy}from"node:child_process";import{existsSync as ci,readdirSync as Uy,readFileSync as Tu}from"node:fs";import{dirname as ir,join as ls}from"node:path";function jy(){try{return My("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function Iu(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${bu} ... \`\`\` 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 Hy(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=Gy(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)"}`);Ky(s,o)}return{actions:r}}function Ky(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 Gy(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 Jy(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 Vy(e,t=di){let r=e.contractSourcePath&&ci(e.contractSourcePath)?Tu(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((w)=>w.name),s=r?or(r,n).byCircuit:new Map,o=e.targetCircuit?Qo(e.targetCircuit):void 0,i=ku({contractName:e.contract.name,contractSummary:ai({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),contractSource:r,targetCircuit:e.targetCircuit,startingArgs:o,witnessDependentCircuits:s,goal:e.goal}),a=await t(i),c=Iu(a),d=Hy(c,e.contract),l=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${Pu(e.goal)??"ai"}`),u=e.network??Nu,p=e.servePort??Ru,m={name:e.contract.name,network:u,prep:Du},y={name:l,description:c.description,strategy:"cli",timeout:Ly},f=qy(c.assertions,p),h=[...s.entries()].filter(([w])=>w!==e.targetCircuit?.name).map(([w,b])=>({name:w,reason:`uses witness ${b.join(", ")} (private state — UI-only)`}));return{dappConfig:m,suite:y,actions:d,assertions:f,prompt:null,suiteName:l,excludedCircuits:h.length>0?h:void 0}}async function zy(e,t=di){let r=e.screen?Tu(e.screen.path,"utf-8"):void 0,n=Cu({contractName:e.contract.name,contractSummary:ai({name:e.contract.name,circuits:e.contract.circuits,witnesses:e.contract.witnesses}),screenComponent:e.screen?.component,screenSource:r,relatedSources:e.relatedSources,url:e.url,goal:e.goal}),s=await t(n),o=Iu(s);Jy(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${Pu(e.goal)??"ai"}`),a=e.network??Nu,c=e.servePort??Ru,d=e.url,l={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:Wy};if(e.buildDir)l.buildDir=e.buildDir;let u={name:i,description:o.description,strategy:"browser",timeout:By,...e.browserMode?{browserMode:e.browserMode}:{}},p=Yy(o.assertions,c);return{dappConfig:l,suite:u,actions:null,assertions:p,prompt:o.prompt,suiteName:i}}function _u(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function qy(e,t){if(e.post.some((n)=>n.type==="port-listening"&&_u(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function Yy(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"&&_u(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 Pu(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 li(e){let t=e.split("/").pop(),r=[ir(e),ls(ir(e),"src"),ir(ir(e)),ls(ir(ir(e)),"src")];for(let n of r){if(!ci(n))continue;if(t){let i=ls(n,`${t}.compact`);if(ci(i))return i}let s;try{s=Uy(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return ls(n,o)}return}var Nu="undeployed",Ru=9932,Ly=300,By=600,Du,Wy,xu=300000,Au=4194304,di=(e)=>new Promise((t,r)=>{let n=Fy("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${xu/1000}s`))},xu);n.stdout?.on("data",(d)=>{if(i+=d.length,i>Au){a=!0,n.kill("SIGTERM");return}s+=d.toString()}),n.stderr?.on("data",(d)=>{o+=d.toString()}),n.on("error",(d)=>{if(clearTimeout(c),d.code==="ENOENT"){r(Error("claude CLI not found on PATH. Install Claude Code (npm install -g @anthropic-ai/claude-code) or run mn test create without --goal / --screen for the deterministic scaffolder."));return}r(d)}),n.on("exit",(d,l)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${Au/1024/1024}MB; aborted.`));return}if(l==="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 ui=N(()=>{Eu();ti();ds();Du=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Wy=[...Du,"build-and-serve"]});async function Ou(e,t,r=1e4){try{let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:"query($address: HexEncoded!) { contractAction(address: $address) { address } }",variables:{address:t}}),signal:AbortSignal.timeout(r)});if(!n.ok)return;let s=await n.json();if(s.errors!==void 0||s.data===void 0||s.data===null)return;return s.data.contractAction!==null&&s.data.contractAction!==void 0}catch{return}}import{existsSync as Xy,mkdirSync as Zy,readFileSync as Qy,writeFileSync as eS}from"node:fs";import{join as Mu}from"node:path";function Fu(e,t){return Mu(e,"tests","results",`.contract-cache-${t}.json`)}function Uu(e,t,r){let n=Fu(e,t);if(!Xy(n))return;try{let s=JSON.parse(Qy(n,"utf-8"));if(s.network!==r)return;return s.address}catch{return}}function Lu(e,t,r,n){Zy(Mu(e,"tests","results"),{recursive:!0});let s={address:n,network:r,timestamp:new Date().toISOString()};eS(Fu(e,t),JSON.stringify(s,null,2)+`
|
|
1239
|
+
`)}var Bu=()=>{};function pi(e){return`${e/1000000000000000n}.${(e%1000000000000000n).toString().padStart(15,"0").slice(0,6)}`}async function fi(e,t={}){let r=t.timeoutMs??tS,n=pi(Te),s=await is(async()=>await e()??Te,Te,{timeoutMs:r,intervalMs:t.intervalMs,onBalance:(o)=>t.onMessage?.(`Waiting for Dust to regrow: ${pi(o)} of the ${n} DUST a transaction needs`)});if(s<Te)throw Error(`Only ${pi(s)} DUST after waiting ${Math.round(r/1000)}s, and a transaction needs ${n}. Dust regrows with time, faster the more NIGHT is registered: fund the wallet with more NIGHT, or run the suite again in a while.`)}var tS=180000;var Wu=N(()=>{qo()});import{existsSync as rS,readFileSync as nS}from"node:fs";async function ju(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:l}=e,u=[],p=r.network??"undeployed",m;if(!a){if(m=Uu(n,s,p),m&&await Ou(o.indexer,m)===!1)l?.(`The contract cached at ${m.slice(0,16)}... is not on this chain; deploying again`),m=void 0}let{info:y}=at(n),f=dS(y),h;for(let w of t){c?.(w);let b=Date.now();if(h&&(w.type==="contract-call"||w.type==="contract-state")){let S={id:w.id,type:w.type,status:"skip",duration:0,message:`cascaded skip — depends on ${h}`};u.push(S),d?.(w,S);continue}try{let S=await sS(w,{dappDir:n,networkConfig:o,managedDir:y.managedDir,contractName:y.name,servePort:i,contractAddress:m,witnessDeps:f,onMessage:l});if(S.contractAddress){if(m=S.contractAddress,Lu(n,s,p,m),w.type==="contract-deploy")h=void 0}let v=Date.now()-b,R={...S,duration:v};if(u.push(R),d?.(w,R),S.status==="skip"&&w.type==="contract-call")h=`skipped action "${w.id}"`}catch(S){let v=Date.now()-b,R={id:w.id,type:w.type,status:"fail",duration:v,message:S.message};u.push(R),d?.(w,R);break}}return u}async function sS(e,t){switch(e.type){case"contract-deploy":return oS(e,t);case"contract-call":return iS(e,t);case"contract-state":return aS(e,t);case"wallet-cmd":return cS(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function oS(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)}...`};await fi(()=>Lo(t.servePort),{onMessage:t.onMessage});let r=await ts({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 iS(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 rr({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 fi(()=>Lo(t.servePort),{onMessage:t.onMessage}),await rs({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 rr({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 aS(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await rr({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)mi(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);mi(s,a,o,n)}catch{mi(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1232
1240
|
${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 Eu=N(()=>{jr();Gn();is();ii()});var Ru={};fe(Ru,{default:()=>Tu});import{join as xu}from"node:path";import{mkdirSync as Py}from"node:fs";function $y(e){return Au.includes(e)}async function Tu(e,t){let r=e.subcommand;if(!r||!$y(r))throw new j(`Usage: midnight test <${Au.join("|")}>
|
|
1241
|
+
`)}`)}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 mi(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 cS(e,t){return{id:e.id,type:e.type,status:"pass",duration:0,message:`wallet-cmd: ${e.cmd??"no command"} (not yet implemented)`}}function dS(e){if(e.witnesses.length===0)return new Map;let t=li(e.managedDir);if(!t||!rS(t))return new Map;let r=nS(t,"utf-8"),n=e.witnesses.map((s)=>s.name);return or(r,n).byCircuit}function Hu(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}var Ku=N(()=>{jr();Jn();ds();ui();Bu();Wu();Xn()});var qu={};fe(qu,{default:()=>Vu});import{join as Gu}from"node:path";import{mkdirSync as lS}from"node:fs";function uS(e){return Ju.includes(e)}async function Vu(e,t){let r=e.subcommand;if(!r||!uS(r))throw new W(`Usage: midnight test <${Ju.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=D(e,"json");switch(r){case"create":return hS(e,n);case"run":return bS(e,n,t);case"list":return vS(n);case"results":return kS(e,n)}}function pS(e){let t=(e??"").toLowerCase();if(t==="")return;if(t==="cli"||t==="browser")return t;if(t==="ui")return"browser";throw new W(`Unknown strategy "${e}". Use "cli" or "ui".`)}function fS(e){return e==="preprod"||e==="preview"||e==="undeployed"?e:void 0}function mS(e){let t={},r=k(e,"port");if(r!==void 0){let a=parseInt(r,10);if(!Number.isFinite(a)||a<=0||a>65535)throw new W(`Invalid --port "${r}" — must be 1–65535.`);t.port=a}let n=k(e,"build-cmd");if(n!==void 0)t.buildCmd=n;let s=k(e,"build-dir");if(s!==void 0)t.buildDir=s;let o=k(e,"url");if(o!==void 0)t.url=o;let i=k(e,"browser-mode");if(i!==void 0){if(i!=="dom"&&i!=="vision"&&i!=="script"&&i!=="auto")throw new W(`Invalid --browser-mode "${i}" — must be dom, vision, or script.`);t.browserMode=i}return t}function gS(e){if(e.port===void 0||e.buildCmd===void 0)throw new W("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 hS(e,t){let{resolve:r}=await import("node:path");await Promise.resolve().then(() => Jn());await Promise.resolve().then(() => ti());await Promise.resolve().then(() => au());let i=await Promise.resolve().then(() => (Su(),{}));await Promise.resolve();let f=await Promise.resolve().then(() => (ui(),$u));await Promise.resolve().then(() => si());let w=r(k(e,"path")??process.cwd()),b=k(e,"name"),S=k(e,"suite"),v=fS(k(e,"network")),R=D(e,"force"),P=!t&&mu(),Y=k(e,"goal"),J=k(e,"screen"),q=D(e,"no-ai"),O=pS(k(e,"strategy"))??(P?await gu():"cli"),ne;if(O==="browser"){let T=mS(e);ne=P?await hu(T):gS(T)}let{info:ue}=at(w,b),us=!q&&f.isClaudeAvailable(),Pt=!q&&(Y!==void 0||J!==void 0||P&&us),E=Pt?await wS({strategy:O,info:ue,dappDir:w,browser:ne,network:v,suiteName:S,goalFlag:Y,screenFlag:J,interactive:P,jsonMode:t,ai:f,promptCircuit:wu,promptScreen:oi,promptGoal:yu,promptSuiteName:ii,discoverScreens:uu})??ei(ue.circuits,{contractName:ue.name,suiteName:S,strategy:O,browser:ne,network:v}):ei(ue.circuits,{contractName:ue.name,suiteName:S,strategy:O,browser:ne,network:v});if(P&&!S){let T=await ii(E.suiteName);if(T!==E.suiteName)E.suiteName=T,E.suite.name=T}let x=iu(E,{dappDir:w,force:R});if(t){I({subcommand:"create",contractName:ue.name,suiteName:E.suiteName,strategy:O,aiAssisted:Pt&&E.suiteName!=="cli-default"&&E.suiteName!=="ui-default",written:x.written,excludedCircuits:E.excludedCircuits});return}process.stderr.write(`
|
|
1249
|
+
`+U(`Test scaffold: ${ue.name}`)+`
|
|
1243
1250
|
|
|
1244
|
-
`);for(let T of x.written)process.stderr.write(` ${
|
|
1251
|
+
`);for(let T of x.written)process.stderr.write(` ${B("✓")} ${T}
|
|
1245
1252
|
`);let A=O==="browser"?{file:"prompt.md",hint:"verify the UI steps match your dApp — exact button labels, expected screens, success criteria. Claude follows these literally."}:{file:"actions.json",hint:'review args — placeholder values like 0 may violate contract assertions (e.g. "amount > 0").'};if(E.excludedCircuits&&E.excludedCircuits.length>0){process.stderr.write(`
|
|
1246
1253
|
`+g(" Skipped (not CLI-testable):")+`
|
|
1247
1254
|
`);for(let T of E.excludedCircuits)process.stderr.write(` ${ee("!")} ${T.name} ${g("— "+T.reason)}
|
|
@@ -1249,75 +1256,77 @@ Run from the root of a dApp project containing dapp.test.json.`);let n=I(e,"json
|
|
|
1249
1256
|
`)),process.stderr.write(g(` Cover them with a browser-strategy suite (mn test create --strategy ui).
|
|
1250
1257
|
`))}process.stderr.write(`
|
|
1251
1258
|
`+g(" Next:")+`
|
|
1252
|
-
`),process.stderr.write(g(" Edit ")+
|
|
1259
|
+
`),process.stderr.write(g(" Edit ")+G(`tests/suites/${E.suiteName}/${A.file}`)+`
|
|
1253
1260
|
`),process.stderr.write(g(" ")+g(A.hint)+`
|
|
1254
|
-
`),process.stderr.write(g(" Run ")+
|
|
1255
|
-
`),process.stderr.write(g(" List ")+
|
|
1261
|
+
`),process.stderr.write(g(" Run ")+G(`mn test run --suite ${E.suiteName}`)+`
|
|
1262
|
+
`),process.stderr.write(g(" List ")+G("mn test list")+g(" (see every suite in this project)")+`
|
|
1256
1263
|
|
|
1257
|
-
`)}async function
|
|
1264
|
+
`)}async function wS(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 yS(e,t);return await SS(e,t)}catch(t){return process.stderr.write(`
|
|
1258
1265
|
${g("AI scaffold failed, falling back to deterministic:")} ${t.message}
|
|
1259
|
-
`),null}}async function
|
|
1266
|
+
`),null}}async function zu(e,t,r){if(!r)return t();let n=z(e);try{let s=await t();return n.stop(),s}catch(s){throw n.fail("AI scaffold failed"),s}}async function yS(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(() => ds());let i=s(n,"utf-8"),a=e.info.witnesses.map((l)=>l.name),d=or(i,a).byCircuit.get(r.name);if(d&&d.length>0)process.stderr.write(`
|
|
1260
1267
|
`+ee("!")+` ${r.name} calls ${d.join(", ")} — a witness that reads private state.
|
|
1261
1268
|
`),process.stderr.write(g(` The CLI suite will deploy + run, but expect a "Cannot read properties of undefined" failure
|
|
1262
1269
|
`)+g(` unless the dApp UI populates that state first. Consider --strategy ui instead.
|
|
1263
|
-
`))}return
|
|
1264
|
-
`+
|
|
1270
|
+
`))}return zu("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 SS(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 zu("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 bS(e,t,r){let{config:n,dappDir:s}=os(),o=zo(s),i=k(e,"suite"),a;if(i){if(a=o.find((m)=>m.suite.name===i),!a){let m=o.map((y)=>y.suite.name).join(", ")||"none found";throw new W(`Suite "${i}" not found. Available: ${m}`)}}else if(o.length>0)a=o[0];lS(Gu(s,"tests","results"),{recursive:!0});let c=Date.now(),d=new Date().toISOString();if(!t){if(process.stderr.write(`
|
|
1271
|
+
`+U(`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 m=
|
|
1277
|
+
`),a.suite.strategy==="browser"){let m=Yo(a.suite);process.stderr.write(C("Browser Mode",m)+`
|
|
1271
1278
|
`)}}process.stderr.write(`
|
|
1272
|
-
`)}let l=
|
|
1273
|
-
`)};r?.addEventListener("abort",()=>
|
|
1274
|
-
`));let m=
|
|
1275
|
-
`);let f=0,h="";if(a){let M=a.suite;if(M.strategy==="browser"){let O=
|
|
1279
|
+
`)}let l=Il(),u=[],p=(m)=>{if(!t)process.stderr.write(g(` [teardown] ${m}`)+`
|
|
1280
|
+
`)};r?.addEventListener("abort",()=>Zo(l,p),{once:!0});try{if(!t)process.stderr.write(_(` Prep
|
|
1281
|
+
`));let m=null,y=await Wl(n,s,l,{onStepStart(M){m=z(`[prep] ${M}...`)},onStepComplete(M,O,ne,ue){if(O==="pass")m?.stop(`${M} (${CS(ne)})`);else m?.fail(`${M}: ${ue??"failed"}`);m=null},onMessage(M){m?.update(M)}});if(u.push(...y),!t)process.stderr.write(`
|
|
1282
|
+
`);let f=0,h="";if(a){let M=a.suite;if(M.strategy==="browser"){let O=Rl(a.suiteDir);if(!O)throw Error(`No prompt.md found in ${a.suiteDir} — required for browser strategy`);if(h=Gu(s,"tests","results",`${M.name}_${d.replace(/[:.]/g,"-")}_claude.log`),!t)process.stderr.write(_(` Browser Test
|
|
1276
1283
|
`)),process.stderr.write(g(` Claude will take over the terminal. Output is also logged.
|
|
1277
1284
|
|
|
1278
|
-
`));let
|
|
1279
|
-
`)}});if(f=
|
|
1280
|
-
`),
|
|
1281
|
-
`);else process.stderr.write(` ${f===0?
|
|
1282
|
-
`)}else if(M.strategy==="cli"){let O=
|
|
1285
|
+
`));let ne=await Kl({suite:M,prompt:O,dappDir:s,logFile:h,onMessage:(ue)=>{if(!t)process.stderr.write(g(` ${ue}`)+`
|
|
1286
|
+
`)}});if(f=ne.exitCode,!t)if(process.stderr.write(`
|
|
1287
|
+
`),ne.timedOut)process.stderr.write(` ${le("✗")} Browser test timed out
|
|
1288
|
+
`);else process.stderr.write(` ${f===0?B("✓"):le("✗")} Claude exited with code ${f}
|
|
1289
|
+
`)}else if(M.strategy==="cli"){let O=Nl(a.suiteDir);if(!O)throw Error(`No actions.json found in ${a.suiteDir} — required for CLI strategy`);if(!t)process.stderr.write(_(` CLI Test
|
|
1283
1290
|
`)),process.stderr.write(g(` Executing ${O.actions.length} action(s)
|
|
1284
1291
|
|
|
1285
|
-
`));await Promise.resolve().then(() =>
|
|
1286
|
-
`)}
|
|
1287
|
-
`)
|
|
1288
|
-
`)}
|
|
1289
|
-
`)
|
|
1292
|
+
`));await Promise.resolve().then(() => Ku());await Promise.resolve().then(() => pe());let Pt=n.network??"undeployed",{config:E}=Q({args:{command:"test",subcommand:"run",positionals:[],flags:{network:Pt}}});await Promise.resolve();let A=l.serveHandle?.port??ur,T=D(e,"redeploy"),j,L=await ju({actions:O.actions,config:n,dappDir:s,suiteName:M.name,networkConfig:E,servePort:A,redeploy:T,onActionStart:(H)=>{if(j=H,!t){let oe=z(`[${H.id}] ${H.type}${H.circuit?` ${H.circuit}`:""}...`);H._spinner=oe}},onActionComplete:(H,oe)=>{if(!t){let Ae=H._spinner;if(Ae)if(oe.status==="pass")Ae.stop(`${H.id}: ${oe.message??"pass"}`);else if(oe.status==="skip")Ae.clear(),process.stderr.write(`${ee("⊘")} ${H.id}: ${oe.message??"skipped"}
|
|
1293
|
+
`);else Ae.fail(`${H.id}: ${oe.message??"fail"}`);if(oe.stateBefore&&oe.stateAfter){let Be=Hu(oe.stateBefore,oe.stateAfter);if(Be.length>0)for(let ke of Be)process.stderr.write(g(` ${ke.field}: ${ke.before} → `)+G(ke.after)+`
|
|
1294
|
+
`)}}},onMessage:(H)=>{if(!t&&j)j._spinner?.update(`[${j.id}] ${H.split(`
|
|
1295
|
+
`)[0]}`)}});if(f=L.some((H)=>H.status==="fail")?1:0,!t){process.stderr.write(`
|
|
1296
|
+
`);let H=L.filter((ke)=>ke.status==="pass").length,oe=L.filter((ke)=>ke.status==="skip").length,Ae=L.filter((ke)=>ke.status==="fail").length,Be=B(String(H)+" passed");if(oe>0)Be+=`, ${ee(String(oe)+" skipped")}`;if(Ae>0)Be+=`, ${le(String(Ae)+" failed")}`;process.stderr.write(` Actions: ${Be}
|
|
1297
|
+
`)}l._actionResults=L}}else if(!t)process.stderr.write(g(` No test suites found — only prep was run
|
|
1298
|
+
`));let w={processExitCode:f,agentLogPath:h},b=[];if(a){let M=Tl(a.suiteDir);if(M&&M.post.length>0){if(!t)process.stderr.write(`
|
|
1290
1299
|
`+_(` Assertions
|
|
1291
|
-
`));if(b=await
|
|
1292
|
-
`)}}}let S=Math.round((Date.now()-c)/1000),v=u.every((M)=>M.status==="pass"),R=b.every((M)=>M.status==="pass"),P=v&&R&&f===0?"pass":"fail",
|
|
1300
|
+
`));if(b=await Jl(M.post,w),!t)for(let O of b){let ne=O.status==="pass"?B("✓"):le("✗"),ue=O.message?g(` — ${O.message}`):"";process.stderr.write(` ${ne} ${O.id}${ue}
|
|
1301
|
+
`)}}}let S=Math.round((Date.now()-c)/1000),v=u.every((M)=>M.status==="pass"),R=b.every((M)=>M.status==="pass"),P=v&&R&&f===0?"pass":"fail",Y=l._actionResults,J={id:`${n.name}_${d}`,dapp:n.name,suite:a?.suite.name??"prep-only",timestamp:d,duration:S,network:n.network??"undeployed",strategy:a?.suite.strategy??"none",model:a?.suite.model,status:P,prep:u,actions:Y?.map((M)=>({id:M.id,type:M.type,status:M.status,duration:M.duration,message:M.message,contractAddress:M.contractAddress})),assertions:b,testOutput:h?{exitCode:f,logFile:h}:void 0},q=ql(J,s);if(t)I(J);else process.stderr.write(`
|
|
1293
1302
|
`+V()+`
|
|
1294
|
-
`),process.stderr.write(` ${P==="pass"?
|
|
1295
|
-
`),process.stderr.write(g(` Results: ${
|
|
1303
|
+
`),process.stderr.write(` ${P==="pass"?B(_("PASS")):le(_("FAIL"))} — ${n.name} (${S}s)
|
|
1304
|
+
`),process.stderr.write(g(` Results: ${q}`)+`
|
|
1296
1305
|
|
|
1297
|
-
`);if(P==="fail")process.exitCode=1}finally{await
|
|
1298
|
-
`+
|
|
1306
|
+
`);if(P==="fail")process.exitCode=1}finally{await Zo(l,p)}}function vS(e){let{config:t,dappDir:r}=os(),n=zo(r);if(e){I({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(`
|
|
1307
|
+
`+U(`Tests: ${t.name}`)+`
|
|
1299
1308
|
|
|
1300
1309
|
`),n.length===0)process.stderr.write(g(` No test suites found.
|
|
1301
1310
|
`)),process.stderr.write(g(` Create tests/suites/<name>/suite.json to add one.
|
|
1302
|
-
`));else for(let{suite:s}of n)process.stderr.write(` ${_(
|
|
1311
|
+
`));else for(let{suite:s}of n)process.stderr.write(` ${_(G(s.name))}
|
|
1303
1312
|
`),process.stderr.write(` ${g(s.description)}
|
|
1304
1313
|
`),process.stderr.write(g(` strategy: ${s.strategy}`)+(s.timeout?g(`, timeout: ${s.timeout}s`):"")+`
|
|
1305
1314
|
|
|
1306
1315
|
`);process.stderr.write(`
|
|
1307
|
-
`)}function
|
|
1308
|
-
`+
|
|
1316
|
+
`)}function kS(e,t){let{config:r,dappDir:n}=os(),s=D(e,"all"),o=k(e,"suite"),i=s?Xo(n,o):(()=>{let a=Yl(n,o);return a?[a]:[]})();if(t){I(s?{dapp:r.name,results:i}:i[0]??{});return}if(process.stderr.write(`
|
|
1317
|
+
`+U(`Results: ${r.name}`)+`
|
|
1309
1318
|
|
|
1310
1319
|
`),i.length===0)process.stderr.write(g(` No test results found.
|
|
1311
1320
|
`)),process.stderr.write(g(` Run "midnight test run" to generate results.
|
|
1312
|
-
`));else for(let a of i){let c=a.status==="pass"?
|
|
1321
|
+
`));else for(let a of i){let c=a.status==="pass"?B("✓"):le("✗"),d=a.status==="pass"?B(_("PASS")):le(_("FAIL"));process.stderr.write(` ${c} ${_(a.suite)} — ${d} (${a.duration}s)
|
|
1313
1322
|
`),process.stderr.write(g(` ${a.timestamp} | ${a.network} | ${a.strategy}`)+`
|
|
1314
|
-
`);let l=a.prep.filter((p)=>p.status==="fail");if(l.length>0)process.stderr.write(
|
|
1315
|
-
`);let u=a.assertions.filter((p)=>p.status==="fail");if(u.length>0)process.stderr.write(
|
|
1323
|
+
`);let l=a.prep.filter((p)=>p.status==="fail");if(l.length>0)process.stderr.write(le(` prep: ${l.length} failed`)+`
|
|
1324
|
+
`);let u=a.assertions.filter((p)=>p.status==="fail");if(u.length>0)process.stderr.write(le(` assertions: ${u.length} failed`)+`
|
|
1316
1325
|
`);process.stderr.write(`
|
|
1317
1326
|
`)}process.stderr.write(`
|
|
1318
|
-
`)}function
|
|
1327
|
+
`)}function CS(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var Ju;var Yu=N(()=>{Fe();he();qe();Dl();jl();Gl();Vl();Xl();Zl();Ju=["run","list","results","create"]});import{readFileSync as Xu}from"node:fs";import{fileURLToPath as ep}from"node:url";import{Server as ES}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as xS}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as AS,CallToolRequestSchema as TS,ListResourcesRequestSchema as NS,ReadResourceRequestSchema as RS}from"@modelcontextprotocol/sdk/types.js";async function X(e,t,r){let n=[];ms((s)=>n.push(s));try{if(t.flags.json=!0,!(Jr in t.flags))t.flags[Jr]=!0;await e(t,r);let s=n.join("").trim();if(!s)return{};return JSON.parse(s)}finally{ms(null)}}Fe();var Si=1,bi=2,cp=3,gs=4,vi=5,Ot=6,dp=7,de={INVALID_ARGS:"INVALID_ARGS",WALLET_NOT_FOUND:"WALLET_NOT_FOUND",NETWORK_ERROR:"NETWORK_ERROR",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",TX_REJECTED:"TX_REJECTED",STALE_UTXO:"STALE_UTXO",STALE_CACHE:"STALE_CACHE",PROOF_TIMEOUT:"PROOF_TIMEOUT",PROOF_FAILURE:"PROOF_FAILURE",INVALID_DUST_PROOF:"INVALID_DUST_PROOF",DUST_REQUIRED:"DUST_REQUIRED",SYNC_TIMEOUT:"SYNC_TIMEOUT",CANCELLED:"CANCELLED",UNSUPPORTED_NODE:"UNSUPPORTED_NODE",BLOCKFROST_PROJECT_ID_REQUIRED:"BLOCKFROST_PROJECT_ID_REQUIRED",BLOCKFROST_PROJECT_ID_REJECTED:"BLOCKFROST_PROJECT_ID_REJECTED",BLOCKFROST_LIMIT_REACHED:"BLOCKFROST_LIMIT_REACHED",ENDPOINT_SHUT_DOWN:"ENDPOINT_SHUT_DOWN",UNKNOWN:"UNKNOWN"},lp=new Set([de.BLOCKFROST_PROJECT_ID_REQUIRED,de.BLOCKFROST_PROJECT_ID_REJECTED,de.BLOCKFROST_LIMIT_REACHED,de.ENDPOINT_SHUT_DOWN]);function ki(e){if(yi(e))return{exitCode:bi,errorCode:de.INVALID_ARGS};let t=e.code;if(t===de.UNSUPPORTED_NODE)return{exitCode:Si,errorCode:de.UNSUPPORTED_NODE};if(typeof t==="string"&&lp.has(t))return{exitCode:gs,errorCode:t};let r=(e.message??"").toLowerCase();if(r.includes("operation cancelled")||r.includes("operation aborted")||r==="cancelled"||r==="aborted")return{exitCode:dp,errorCode:de.CANCELLED};if(r.includes("wallet file not found")||r.includes("wallet")&&r.includes("not found"))return{exitCode:cp,errorCode:de.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:bi,errorCode:de.INVALID_ARGS};if(r.includes("proof")&&r.includes("timeout"))return{exitCode:Ot,errorCode:de.PROOF_TIMEOUT};if(r.includes("stale utxo")||r.includes("error code 115")||r.includes("errorcode: 115"))return{exitCode:Ot,errorCode:de.STALE_UTXO};if(r.includes("error 170")||r.includes("errorcode: 170")||r.includes("invaliddustspendproof"))return{exitCode:Ot,errorCode:de.INVALID_DUST_PROOF};if(r.includes("stale cache")||r.includes("chain reset")||r.includes("chainid mismatch")||r.includes("applied > highest")||r.includes("inserted non-linearly"))return{exitCode:Ot,errorCode:de.STALE_CACHE};if(r.includes("failed to prove"))return{exitCode:Ot,errorCode:de.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:gs,errorCode:de.SYNC_TIMEOUT};if(r.includes("no dust")||r.includes("dust")&&(r.includes("required")||r.includes("available")||r.includes("insufficient")))return{exitCode:vi,errorCode:de.DUST_REQUIRED};if(r.includes("insufficient")||r.includes("not enough"))return{exitCode:vi,errorCode:de.INSUFFICIENT_BALANCE};if(r.includes("rejected")||r.includes("transaction failed"))return{exitCode:Ot,errorCode:de.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:gs,errorCode:de.NETWORK_ERROR};return{exitCode:Si,errorCode:de.UNKNOWN}}function Ci(e){let t=e.split(`
|
|
1319
1328
|
|
|
1320
1329
|
`)[0].trim(),r=t.split(`
|
|
1321
1330
|
`),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(`
|
|
1322
|
-
`).trim()||t}var zr={name:"midnight-wallet-cli",version:"0.5.7",type:"module",description:"Git-style CLI wallet for the Midnight blockchain",license:"Apache-2.0",author:"Norman Lopez (https://github.com/nel349)",homepage:"https://github.com/nel349/midnight-wallet-cli#readme",repository:{type:"git",url:"git+https://github.com/nel349/midnight-wallet-cli.git"},bugs:{url:"https://github.com/nel349/midnight-wallet-cli/issues"},keywords:["midnight","blockchain","wallet","cli","zk","zero-knowledge","compact","mcp","ai-agent"],workspaces:["packages/connector"],bin:{midnight:"dist/wallet.js",mn:"dist/wallet.js","midnight-wallet-cli":"dist/wallet.js","midnight-wallet-mcp":"dist/mcp-server.js"},files:["dist","docs/SKILL.md","NOTICE"],engines:{node:">=22",bun:">=1.3.0"},scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",link:"bun link",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/compact-runtime":"0.16.0","@midnight-ntwrk/dapp-connector-api":"4.0.1","@midnight-ntwrk/ledger-v8":"8.1.0","@midnight-ntwrk/midnight-js-contracts":"4.1.1","@midnight-ntwrk/midnight-js-http-client-proof-provider":"4.1.1","@midnight-ntwrk/midnight-js-indexer-public-data-provider":"4.1.1","@midnight-ntwrk/midnight-js-level-private-state-provider":"4.1.1","@midnight-ntwrk/midnight-js-network-id":"4.1.1","@midnight-ntwrk/midnight-js-node-zk-config-provider":"4.1.1","@midnight-ntwrk/midnight-js-types":"4.1.1","@midnight-ntwrk/midnight-js-utils":"4.1.1","@midnight-ntwrk/onchain-runtime-v3":"3.0.0","@midnight-ntwrk/wallet-sdk-abstractions":"2.1.0","@midnight-ntwrk/wallet-sdk-address-format":"3.1.1","@midnight-ntwrk/wallet-sdk-capabilities":"3.3.0","@midnight-ntwrk/wallet-sdk-dust-wallet":"4.0.0","@midnight-ntwrk/wallet-sdk-facade":"4.0.0","@midnight-ntwrk/wallet-sdk-hd":"3.0.1","@midnight-ntwrk/wallet-sdk-shielded":"3.0.0","@midnight-ntwrk/wallet-sdk-unshielded-wallet":"3.0.0","@midnight-ntwrk/wallet-sdk-utilities":"1.1.1","@modelcontextprotocol/sdk":"^1.27.1","@scure/base":"2.0.0","@scure/bip39":"^2.0.1",rxjs:"7.8.2",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"},optionalDependencies:{"@nel349/dust-sync-darwin-arm64":"0.5.7","@nel349/dust-sync-darwin-x64":"0.5.7","@nel349/dust-sync-linux-x64":"0.5.7","@nel349/dust-sync-linux-arm64":"0.5.7","@nel349/dust-sync-win32-x64":"0.5.7"}};var SS=zr.name,ms=zr.version,bS=zr.description;import{randomUUID as Ju}from"node:crypto";var Vu=300000;function hi(e={}){let t=e.ttlMs??Vu,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=Ju(),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}}}import zu from"node:v8";import qu from"node:os";import{spawn as Yu}from"node:child_process";var Es="MN_HEAP_BUMPED",Xu="MN_MAX_OLD_SPACE_MB",Pi=1048576;function Zu(e){let t=e.desiredMb??Ei,r=e.ramFraction??xi,n=e.minGainMb??Ai;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 $i(){if(process.env[Es]){ep();return}let e=process.env[Xu],t=e!==void 0?Number(e):void 0,r=Zu({totalMb:Math.floor(qu.totalmem()/Pi),currentLimitMb:Math.floor(zu.getHeapStatistics().heap_size_limit/Pi),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=Yu(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[Es]:"1"}});Qu(s),s.on("error",()=>{process.env[Es]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function Qu(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 ep(){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()}class xs extends Error{code="UNSUPPORTED_NODE";constructor(e){super(`midnight-wallet-cli needs Node.js 22 or newer; this is Node.js ${e}. The Midnight wallet SDK uses features older versions lack. Install a current Node.js (https://nodejs.org) and run the command again.`);this.name="UnsupportedNodeError",Object.setPrototypeOf(this,xs.prototype)}}function Oi(e=process.versions){if(e.bun!==void 0)return;let t=Number(e.node.split(".")[0]);if(!Number.isInteger(t)||t<22)throw new xs(e.node)}De();function np(e){if(typeof e==="string")return Ds(e)?on(e):e;let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8");if(!Ds(t))return e;let r=on(t);return r===t?e:Buffer.from(r,"utf8")}function Bi(e){return function(t,...r){return e.call(this,np(t),...r)}}var Wi=!1;function ji(){if(Wi)return;Wi=!0,process.stdout.write=Bi(process.stdout.write),process.stderr.write=Bi(process.stderr.write)}var Ou="midnight-wallet://skill/core",Mu="midnight-wallet://skill/full",Qy="midnight-wallet://skill",eS=$u(new URL("../docs/SKILL-CORE.md",import.meta.url)),tS=$u(new URL("../docs/SKILL.md",import.meta.url));function we(e,t,r){let n={json:!0},s=[];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;let a=o==="full"?or:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}var rS={generate:()=>Promise.resolve().then(() => (da(),ca)),info:()=>Promise.resolve().then(() => (pa(),ua)),balance:()=>Promise.resolve().then(() => (lc(),dc)),address:()=>Promise.resolve().then(() => (fc(),pc)),"genesis-address":()=>Promise.resolve().then(() => (hc(),gc)),"inspect-cost":()=>Promise.resolve().then(() => (bc(),Sc)),airdrop:()=>Promise.resolve().then(() => (xc(),Ec)),transfer:()=>Promise.resolve().then(() => (Ic(),Rc)),dust:()=>Promise.resolve().then(() => (Oc(),$c)),cache:()=>Promise.resolve().then(() => (Uc(),Fc)),config:()=>Promise.resolve().then(() => (Wc(),Bc)),localnet:()=>Promise.resolve().then(() => (rd(),td)),wallet:()=>Promise.resolve().then(() => (ad(),id)),status:()=>Promise.resolve().then(() => (gd(),md)),contract:()=>Promise.resolve().then(() => (al(),il)),test:()=>Promise.resolve().then(() => (Iu(),Ru))};async function Z(e){let t=rS[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}var Fu=[{name:"midnight_wallet_generate",description:"Create wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"64-char hex"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=we("wallet",e,"generate");if(r.positionals=[t],delete r.flags.name,e.force==="true"||e.force===!0)r.flags.force=!0;let n=await Z("wallet");return X(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[or]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await Z("wallet");return X(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 Z("wallet");return X(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[or]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await Z("wallet");return X(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 Z("wallet");return X(n,r)}},{name:"midnight_info",description:"Wallet metadata.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=we("info",e),r=await Z("info");return X(r,t)}},{name:"midnight_balance",description:"NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string"},full:{type:"boolean",description:"Include the queried address + shieldedAddress in the response (matches `mn balance --json`). Default false (slim)."}}},async handler(e){let t=e.address,r=we("balance",e,t);delete r.flags.address;let n=await Z("balance");return X(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64-char hex"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=we("address",e),r=await Z("address");return X(r,t)}},{name:"midnight_genesis_address",description:"Genesis address.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]}}},async handler(e){let t=we("genesis-address",e),r=await Z("genesis-address");return X(r,t)}},{name:"midnight_inspect_cost",description:"Block limits.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e=we("inspect-cost",{}),t=await Z("inspect-cost");return X(t,e)}},{name:"midnight_airdrop",description:'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.',annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{amount:{type:"string",description:"NIGHT"},wallet:{type:"string",description:"Destination: wallet name, JSON path, or bech32m address"},shielded:{type:"string",description:'Set to "true" for shielded airdrop'}},required:["amount"]},async handler(e){let t=e.amount,r=we("airdrop",e,t);delete r.flags.amount;let n=await Z("airdrop");return X(n,r)}},{name:"midnight_transfer",description:"Send NIGHT (returns pending token; see skill).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{to:{type:"string",description:"bech32m"},amount:{type:"string",description:"NIGHT"},wallet:{type:"string"}},required:["to","amount"]},async handler(e){let{to:t,amount:r}=e,n=we("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await Z("transfer");return X(s,n)}},{name:"midnight_dust_register",description:"Register for dust.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=we("dust",e,"register"),r=await Z("dust");return X(r,t)}},{name:"midnight_dust_status",description:"Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},"proof-server":{type:"string"},node:{type:"string"},"indexer-ws":{type:"string"},"no-cache":{type:"string"},full:{type:"boolean",description:"Include sync internals (eventsApplied, ownedUtxos, cached) in the response (matches `mn dust status --json`). Default false (slim)."}}},async handler(e){let t=we("dust",e,"status"),r=await Z("dust");return X(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 Z("config");return X(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 Z("config");return X(s,n)}},{name:"midnight_cache_clear",description:"Clear sync cache.",annotations:{destructiveHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]},wallet:{type:"string"}}},async handler(e){let t=we("cache",e,"clear"),r=await Z("cache");return X(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 Z("config");return X(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 Z("localnet");return X(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 Z("localnet");return X(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 Z("localnet");return X(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 Z("localnet");return X(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 Z("localnet");return X(t,e)}},{name:"midnight_contract_inspect",description:"Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed/<name>/compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path)"},name:{type:"string",description:"Specific contract name to inspect when the project has multiple (see siblings field)"}}},async handler(e){let t=we("contract",e,"inspect"),r=await Z("contract");return X(r,t)}},{name:"midnight_contract_state",description:"Read the current ledger state of a deployed contract. Returns the ledger fields as a JSON object.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},path:{type:"string",description:"dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address"]},async handler(e){let t=we("contract",e,"state"),r=await Z("contract");return X(r,t)}},{name:"midnight_contract_deploy",description:"Deploy a compiled Compact contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of constructor arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}}},async handler(e){let t=we("contract",e,"deploy"),r=await Z("contract");return X(r,t)}},{name:"midnight_contract_call",description:"Call a circuit on a deployed contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},circuit:{type:"string",description:"Circuit name to invoke"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of circuit arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address","circuit"]},async handler(e){let t=we("contract",e,"call"),r=await Z("contract");return X(r,t)}},{name:"midnight_test_create",description:"Generate a test scaffold for the contract. Two paths: (1) AI-assisted — pass `goal` (and optionally `screen` for UI strategy) and the scaffold is generated by Claude reading the contract + screen source, producing a focused suite with realistic args / on-screen labels. (2) Deterministic — pass `no-ai: true` (or omit goal/screen in non-interactive mode) for boilerplate scaffolds that the user reviews. CLI strategy emits dapp.test.json + tests/suites/<name>/{suite,actions,assertions}.json. Browser strategy emits prompt.md instead of actions.json plus the browser fields in dapp.test.json — required: port, build-cmd. Use force:true to overwrite.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"dApp directory (defaults to cwd)"},name:{type:"string",description:"Specific contract name when the project has multiple"},suite:{type:"string",description:"Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)"},strategy:{type:"string",enum:["cli","browser"],description:"cli (default): drive contracts via actions.json. browser: drive a real UI via Claude + Chrome via prompt.md."},network:{type:"string",enum:["preprod","preview","undeployed"]},goal:{type:"string",description:'AI mode: one-line success criterion this suite should verify (e.g. "round goes from 0 to 1 after increment"). Triggers AI scaffolding.'},screen:{type:"string",description:'AI mode + browser strategy: name of the screen component to focus on (e.g. "loan-request-form" or "LoanRequestForm"). Auto-discovered from src/components, src/pages, src/screens.'},"no-ai":{type:"boolean",description:"Force deterministic scaffolder even when claude CLI is available."},port:{type:"string",description:'Browser strategy only — dev server port (e.g. "4173").'},"build-cmd":{type:"string",description:'Browser strategy only — shell command that builds + serves the UI (e.g. "npm run dev").'},"build-dir":{type:"string",description:"Browser strategy only — subdir the build runs in (monorepo case)."},url:{type:"string",description:"Browser strategy only — full URL Claude opens (default http://localhost:<port>/)."},"browser-mode":{type:"string",enum:["dom","vision","script"],description:"Browser strategy only — how Claude perceives the page. dom (HTML/React UIs, fast, needs chrome-devtools-mcp), vision (canvas games, slow), script (advanced, needs hooks). Default: dom for AI scaffolds."},force:{type:"boolean",description:"Overwrite existing files instead of aborting on collision"}}},async handler(e){let t=we("test",e,"create"),r=await Z("test");return X(r,t)}},{name:"midnight_localnet_logs",description:"Snapshot of recent localnet logs (last N lines per service, no streaming). Returns { tail, lines: string[] }.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{tail:{type:"string",description:"Number of lines to retrieve (default 200)"}}},async handler(e){let t=we("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await Z("localnet");return X(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")}}],nS=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),_u=hi();function sS(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)}`}}var Gr=new Vy({name:"midnight-wallet-cli",version:ms},{capabilities:{tools:{},resources:{}}});Gr.setRequestHandler(Xy,async()=>({resources:[{uri:Ou,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:Mu,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"}]}));Gr.setRequestHandler(Zy,async(e)=>{let t=e.params.uri;if(t===Ou){let r=Du(eS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===Mu||t===Qy){let r=Du(tS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Gr.setRequestHandler(qy,async()=>({tools:Fu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Gr.setRequestHandler(Yy,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=_u.redeem(s);if(!o)return ci(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return Pu(o.tool,o.args)}if(nS.has(t)){let s=_u.create({tool:t,args:n,description:sS(t,n)});return{content:[{type:"text",text:JSON.stringify(di({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 Pu(t,n)});function di(e){return{...e,_serverVersion:ms}}async function Pu(e,t){let r=Fu.find((n)=>n.name===e);if(!r)return ci(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(di(n),null,2)}]}}catch(n){return ci(n instanceof Error?n:Error(String(n)))}}function ci(e){let{errorCode:t}=mi(e);return{content:[{type:"text",text:JSON.stringify(di({error:!0,code:t,message:gi(e.message)}))}],isError:!0}}async function oS(){Oi(),ji(),await $i();let e=new zy;await Gr.connect(e)}oS().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1331
|
+
`).trim()||t}var zr={name:"midnight-wallet-cli",version:"0.5.8",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:">=22",bun:">=1.3.0"},scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",link:"bun link",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/compact-runtime":"0.16.0","@midnight-ntwrk/dapp-connector-api":"4.0.1","@midnight-ntwrk/ledger-v8":"8.1.0","@midnight-ntwrk/midnight-js-contracts":"4.1.1","@midnight-ntwrk/midnight-js-http-client-proof-provider":"4.1.1","@midnight-ntwrk/midnight-js-indexer-public-data-provider":"4.1.1","@midnight-ntwrk/midnight-js-level-private-state-provider":"4.1.1","@midnight-ntwrk/midnight-js-network-id":"4.1.1","@midnight-ntwrk/midnight-js-node-zk-config-provider":"4.1.1","@midnight-ntwrk/midnight-js-types":"4.1.1","@midnight-ntwrk/midnight-js-utils":"4.1.1","@midnight-ntwrk/onchain-runtime-v3":"3.0.0","@midnight-ntwrk/wallet-sdk-abstractions":"2.1.0","@midnight-ntwrk/wallet-sdk-address-format":"3.1.1","@midnight-ntwrk/wallet-sdk-capabilities":"3.3.0","@midnight-ntwrk/wallet-sdk-dust-wallet":"4.0.0","@midnight-ntwrk/wallet-sdk-facade":"4.0.0","@midnight-ntwrk/wallet-sdk-hd":"3.0.1","@midnight-ntwrk/wallet-sdk-shielded":"3.0.0","@midnight-ntwrk/wallet-sdk-unshielded-wallet":"3.0.0","@midnight-ntwrk/wallet-sdk-utilities":"1.1.1","@modelcontextprotocol/sdk":"^1.27.1","@scure/base":"2.0.0","@scure/bip39":"^2.0.1",rxjs:"7.8.2",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"},optionalDependencies:{"@nel349/dust-sync-darwin-arm64":"0.5.8","@nel349/dust-sync-darwin-x64":"0.5.8","@nel349/dust-sync-linux-x64":"0.5.8","@nel349/dust-sync-linux-arm64":"0.5.8","@nel349/dust-sync-win32-x64":"0.5.8"}};var YS=zr.name,hs=zr.version,XS=zr.description;import{randomUUID as pp}from"node:crypto";var fp=300000;function Ei(e={}){let t=e.ttlMs??fp,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=pp(),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}}}import mp from"node:v8";import gp from"node:os";import{spawn as hp}from"node:child_process";var As="MN_HEAP_BUMPED",wp="MN_MAX_OLD_SPACE_MB",Wi=1048576;function yp(e){let t=e.desiredMb??_i,r=e.ramFraction??Pi,n=e.minGainMb??$i;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 ji(){if(process.env[As]){bp();return}let e=process.env[wp],t=e!==void 0?Number(e):void 0,r=yp({totalMb:Math.floor(gp.totalmem()/Wi),currentLimitMb:Math.floor(mp.getHeapStatistics().heap_size_limit/Wi),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=hp(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[As]:"1"}});Sp(s),s.on("error",()=>{process.env[As]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function Sp(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 bp(){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()}class Ts extends Error{code="UNSUPPORTED_NODE";constructor(e){super(`midnight-wallet-cli needs Node.js 22 or newer; this is Node.js ${e}. The Midnight wallet SDK uses features older versions lack. Install a current Node.js (https://nodejs.org) and run the command again.`);this.name="UnsupportedNodeError",Object.setPrototypeOf(this,Ts.prototype)}}function Hi(e=process.versions){if(e.bun!==void 0)return;let t=Number(e.node.split(".")[0]);if(!Number.isInteger(t)||t<22)throw new Ts(e.node)}_e();function Cp(e){if(typeof e==="string")return Ps(e)?on(e):e;let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8");if(!Ps(t))return e;let r=on(t);return r===t?e:Buffer.from(r,"utf8")}function zi(e){return function(t,...r){return e.call(this,Cp(t),...r)}}var qi=!1;function Yi(){if(qi)return;qi=!0,process.stdout.write=zi(process.stdout.write),process.stderr.write=zi(process.stderr.write)}var tp="midnight-wallet://skill/core",rp="midnight-wallet://skill/full",DS="midnight-wallet://skill",IS=ep(new URL("../docs/SKILL-CORE.md",import.meta.url)),_S=ep(new URL("../docs/SKILL.md",import.meta.url));function we(e,t,r){let n={json:!0},s=[];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;let a=o==="full"?ar:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}var PS={generate:()=>Promise.resolve().then(() => (wa(),ha)),info:()=>Promise.resolve().then(() => (ba(),Sa)),balance:()=>Promise.resolve().then(() => (xc(),Ec)),address:()=>Promise.resolve().then(() => (Nc(),Tc)),"genesis-address":()=>Promise.resolve().then(() => (Ic(),Dc)),"inspect-cost":()=>Promise.resolve().then(() => (Oc(),$c)),airdrop:()=>Promise.resolve().then(() => (Bc(),Lc)),transfer:()=>Promise.resolve().then(() => (Gc(),Kc)),dust:()=>Promise.resolve().then(() => (Yc(),qc)),cache:()=>Promise.resolve().then(() => (Qc(),Zc)),config:()=>Promise.resolve().then(() => (rd(),td)),localnet:()=>Promise.resolve().then(() => (yd(),wd)),wallet:()=>Promise.resolve().then(() => (Cd(),kd)),status:()=>Promise.resolve().then(() => (Id(),Dd)),contract:()=>Promise.resolve().then(() => (kl(),vl)),test:()=>Promise.resolve().then(() => (Yu(),qu))};async function Z(e){let t=PS[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}var np=[{name:"midnight_wallet_generate",description:"Create wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"64-char hex"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=we("wallet",e,"generate");if(r.positionals=[t],delete r.flags.name,e.force==="true"||e.force===!0)r.flags.force=!0;let n=await Z("wallet");return X(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[ar]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await Z("wallet");return X(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 Z("wallet");return X(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[ar]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await Z("wallet");return X(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 Z("wallet");return X(n,r)}},{name:"midnight_info",description:"Wallet metadata.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=we("info",e),r=await Z("info");return X(r,t)}},{name:"midnight_balance",description:"NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string"},full:{type:"boolean",description:"Include the queried address + shieldedAddress in the response (matches `mn balance --json`). Default false (slim)."}}},async handler(e){let t=e.address,r=we("balance",e,t);delete r.flags.address;let n=await Z("balance");return X(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64-char hex"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=we("address",e),r=await Z("address");return X(r,t)}},{name:"midnight_genesis_address",description:"Genesis address.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]}}},async handler(e){let t=we("genesis-address",e),r=await Z("genesis-address");return X(r,t)}},{name:"midnight_inspect_cost",description:"Block limits.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e=we("inspect-cost",{}),t=await Z("inspect-cost");return X(t,e)}},{name:"midnight_airdrop",description:'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.',annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{amount:{type:"string",description:"NIGHT"},wallet:{type:"string",description:"Destination: wallet name, JSON path, or bech32m address"},shielded:{type:"string",description:'Set to "true" for shielded airdrop'}},required:["amount"]},async handler(e){let t=e.amount,r=we("airdrop",e,t);delete r.flags.amount;let n=await Z("airdrop");return X(n,r)}},{name:"midnight_transfer",description:"Send NIGHT (returns pending token; see skill).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{to:{type:"string",description:"bech32m"},amount:{type:"string",description:"NIGHT"},wallet:{type:"string"}},required:["to","amount"]},async handler(e){let{to:t,amount:r}=e,n=we("transfer",e,t);n.positionals=[r],delete n.flags.to,delete n.flags.amount;let s=await Z("transfer");return X(s,n)}},{name:"midnight_dust_register",description:"Register for dust.",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"}}},async handler(e){let t=we("dust",e,"register"),r=await Z("dust");return X(r,t)}},{name:"midnight_dust_status",description:"Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},"proof-server":{type:"string"},node:{type:"string"},"indexer-ws":{type:"string"},"no-cache":{type:"string"},full:{type:"boolean",description:"Include sync internals (eventsApplied, ownedUtxos, cached) in the response (matches `mn dust status --json`). Default false (slim)."}}},async handler(e){let t=we("dust",e,"status"),r=await Z("dust");return X(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 Z("config");return X(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 Z("config");return X(s,n)}},{name:"midnight_cache_clear",description:"Clear sync cache.",annotations:{destructiveHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{network:{type:"string",enum:["preprod","preview","undeployed"]},wallet:{type:"string"}}},async handler(e){let t=we("cache",e,"clear"),r=await Z("cache");return X(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 Z("config");return X(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 Z("localnet");return X(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 Z("localnet");return X(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 Z("localnet");return X(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 Z("localnet");return X(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 Z("localnet");return X(t,e)}},{name:"midnight_contract_inspect",description:"Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed/<name>/compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path)"},name:{type:"string",description:"Specific contract name to inspect when the project has multiple (see siblings field)"}}},async handler(e){let t=we("contract",e,"inspect"),r=await Z("contract");return X(r,t)}},{name:"midnight_contract_state",description:"Read the current ledger state of a deployed contract. Returns the ledger fields as a JSON object.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},path:{type:"string",description:"dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address"]},async handler(e){let t=we("contract",e,"state"),r=await Z("contract");return X(r,t)}},{name:"midnight_contract_deploy",description:"Deploy a compiled Compact contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of constructor arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}}},async handler(e){let t=we("contract",e,"deploy"),r=await Z("contract");return X(r,t)}},{name:"midnight_contract_call",description:"Call a circuit on a deployed contract (returns pending token; agent must show the description and redeem via midnight_confirm_operation).",annotations:{destructiveHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{address:{type:"string",description:"Contract address (hex)"},circuit:{type:"string",description:"Circuit name to invoke"},wallet:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},args:{type:"string",description:"JSON-encoded array or object of circuit arguments"},path:{type:"string",description:"dApp directory (defaults to cwd)"},managed:{type:"string",description:"Direct path to a managed/<name>/ directory (overrides path-based contract scan)"},name:{type:"string",description:"Specific contract name when the project has multiple"}},required:["address","circuit"]},async handler(e){let t=we("contract",e,"call"),r=await Z("contract");return X(r,t)}},{name:"midnight_test_create",description:"Generate a test scaffold for the contract. Two paths: (1) AI-assisted — pass `goal` (and optionally `screen` for UI strategy) and the scaffold is generated by Claude reading the contract + screen source, producing a focused suite with realistic args / on-screen labels. (2) Deterministic — pass `no-ai: true` (or omit goal/screen in non-interactive mode) for boilerplate scaffolds that the user reviews. CLI strategy emits dapp.test.json + tests/suites/<name>/{suite,actions,assertions}.json. Browser strategy emits prompt.md instead of actions.json plus the browser fields in dapp.test.json — required: port, build-cmd. Use force:true to overwrite.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{path:{type:"string",description:"dApp directory (defaults to cwd)"},name:{type:"string",description:"Specific contract name when the project has multiple"},suite:{type:"string",description:"Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)"},strategy:{type:"string",enum:["cli","browser"],description:"cli (default): drive contracts via actions.json. browser: drive a real UI via Claude + Chrome via prompt.md."},network:{type:"string",enum:["preprod","preview","undeployed"]},goal:{type:"string",description:'AI mode: one-line success criterion this suite should verify (e.g. "round goes from 0 to 1 after increment"). Triggers AI scaffolding.'},screen:{type:"string",description:'AI mode + browser strategy: name of the screen component to focus on (e.g. "loan-request-form" or "LoanRequestForm"). Auto-discovered from src/components, src/pages, src/screens.'},"no-ai":{type:"boolean",description:"Force deterministic scaffolder even when claude CLI is available."},port:{type:"string",description:'Browser strategy only — dev server port (e.g. "4173").'},"build-cmd":{type:"string",description:'Browser strategy only — shell command that builds + serves the UI (e.g. "npm run dev").'},"build-dir":{type:"string",description:"Browser strategy only — subdir the build runs in (monorepo case)."},url:{type:"string",description:"Browser strategy only — full URL Claude opens (default http://localhost:<port>/)."},"browser-mode":{type:"string",enum:["dom","vision","script"],description:"Browser strategy only — how Claude perceives the page. dom (HTML/React UIs, fast, needs chrome-devtools-mcp), vision (canvas games, slow), script (advanced, needs hooks). Default: dom for AI scaffolds."},force:{type:"boolean",description:"Overwrite existing files instead of aborting on collision"}}},async handler(e){let t=we("test",e,"create"),r=await Z("test");return X(r,t)}},{name:"midnight_localnet_logs",description:"Snapshot of recent localnet logs (last N lines per service, no streaming). Returns { tail, lines: string[] }.",annotations:{readOnlyHint:!0,openWorldHint:!0},inputSchema:{type:"object",properties:{tail:{type:"string",description:"Number of lines to retrieve (default 200)"}}},async handler(e){let t=we("localnet",e,"logs");if(!t.flags.tail)t.flags.tail="200";let r=await Z("localnet");return X(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")}}],$S=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),Zu=Ei();function OS(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)}`}}var Gr=new ES({name:"midnight-wallet-cli",version:hs},{capabilities:{tools:{},resources:{}}});Gr.setRequestHandler(NS,async()=>({resources:[{uri:tp,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:rp,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"}]}));Gr.setRequestHandler(RS,async(e)=>{let t=e.params.uri;if(t===tp){let r=Xu(IS,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===rp||t===DS){let r=Xu(_S,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Gr.setRequestHandler(AS,async()=>({tools:np.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Gr.setRequestHandler(TS,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=Zu.redeem(s);if(!o)return gi(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return Qu(o.tool,o.args)}if($S.has(t)){let s=Zu.create({tool:t,args:n,description:OS(t,n)});return{content:[{type:"text",text:JSON.stringify(hi({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 Qu(t,n)});function hi(e){return{...e,_serverVersion:hs}}async function Qu(e,t){let r=np.find((n)=>n.name===e);if(!r)return gi(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(hi(n),null,2)}]}}catch(n){return gi(n instanceof Error?n:Error(String(n)))}}function gi(e){let{errorCode:t}=ki(e);return{content:[{type:"text",text:JSON.stringify(hi({error:!0,code:t,message:Ci(e.message)}))}],isError:!0}}async function MS(){Hi(),Yi(),await ji();let e=new xS;await Gr.connect(e)}MS().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1323
1332
|
`),process.exit(1)});
|