midnight-wallet-cli 0.5.2 → 0.6.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -24
- package/dist/mcp-server.js +497 -493
- package/dist/wallet.js +566 -531
- package/docs/SKILL-CORE.md +45 -0
- package/docs/SKILL.md +21 -11
- package/package.json +16 -26
package/dist/mcp-server.js
CHANGED
|
@@ -1,71 +1,73 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as vu}from"node:module";var yu=Object.defineProperty;var Su=(e)=>e;function bu(e,t){this[e]=Su.bind(null,t)}var me=(e,t)=>{for(var r in t)yu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:bu.bind(t,r)})};var T=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var jo=vu(import.meta.url);function C(e,t){let r=e.flags[t];if(r===void 0||r===!0)return;return r}function R(e,t){return t in e.flags}function We(e){return R(e,"verbose")}function lt(e){return R(e,Qr)&&!R(e,fr)}function Lt(e){if(R(e,"no-cache"))throw Error(`--no-cache is not supported on write commands (transfer, airdrop, dust register, serve).
|
|
3
3
|
`+`Writes always use the cache — the SDK's fresh-sync is too slow on hosted networks.
|
|
4
|
-
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function
|
|
5
|
-
`;if(
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
Valid
|
|
9
|
-
|
|
10
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(ur.has(n)){if(!iu(t))throw Error(`Invalid URL for "${e}": "${t}"
|
|
4
|
+
`+"To reset: midnight cache clear --wallet <name> --network <name>")}function en(e,t,r){let n=C(e,t);if(n===void 0)throw Error(`Missing required flag: --${t} <${r}>`);return n}var Qr="_minimal",fr="_full";function os(e){ss=e}function I(e){let t=JSON.stringify(e)+`
|
|
5
|
+
`;if(ss)ss(t);else process.stdout.write(t)}var ss=null;function kt(e){if(!e||e!==e.trim())return!1;if(/[\/\\]/.test(e))return!1;if(e.endsWith(".json"))return!1;if(e==="."||e==="..")return!1;if(/[\x00-\x1f]/.test(e))return!1;return!0}var rt="0000000000000000000000000000000000000000000000000000000000000001",mr="0000000000000000000000000000000000000000000000000000000000000000",gr="/api/v4/graphql",Ut="/api/v4/graphql/ws",as=6,cs=1e6,Vo=300000000000000n,Jo=5,hr=800000000000000n,qo=5000000000n,zo=8267n,Xo=10800n,Yo=300000,ds=30000,Zo=1e4,ls=120000,rn=300000,us=60000,Qo=16384,ei=0.7,ti=512,nn=10,ri=3,ni=600000,ps=15000,si=115,oe=".midnight",sn="wallet.json",oi="config.json",Ee=448,xe=384,ii="localnet",fs=2,$e="cache",on="wallets",ms="default",wr=10,gs=3000,ai=120000,yr=9932,an="https://midnight-comp-tracker.vercel.app";import*as nt from"fs";import*as ws from"path";import{homedir as _u}from"os";function ys(e){return $u[e]??e}function Ou(e){return/^(https?|wss?):\/\/\S+/.test(e)}function li(e){return e??ws.join(_u(),oe)}function ui(e){return ws.join(li(e),oi)}function Mu(e){let t=li(e);if(!nt.existsSync(t))nt.mkdirSync(t,{recursive:!0,mode:Ee})}function Re(e){let t=ui(e);if(!nt.existsSync(t))return{...Sr};let r;try{r=nt.readFileSync(t,"utf-8")}catch{return{...Sr}}let n;try{n=JSON.parse(r)}catch{return{...Sr}}let s={network:n.network&&Ne(n.network)?n.network:Sr.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 d of br){let u=a[d];if(u&&typeof u==="string")c[d]=u}if(Object.keys(c).length>0)o[i]=c}if(Object.keys(o).length>0)s.networks=o}return s}function vr(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 dn(e,t){Mu(t);let r=ui(t);nt.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
6
|
+
`,{mode:xe})}function pi(e,t){let r=ys(e),n=Re(t);if(r==="network")return n.network;if(r==="wallet")return n.wallet??"(not set)";if(br.has(r)){let o=vr(n,n.network)[r];return typeof o==="string"?o:"(not set)"}throw Error(`Unknown config key: "${e}"
|
|
7
|
+
Valid keys: ${cn.join(", ")}`)}function Fu(e,t){let r={...e.networks?.[t]??{}},n=!1;for(let s of br){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 fi(e,t,r){let n=ys(e),s=Re(r);if(n==="network"){if(!Ne(t))throw Error(`Invalid network: "${t}"
|
|
8
|
+
Valid networks: preprod, preview, undeployed`);Fu(s,s.network),s.network=t}else if(n==="wallet"){if(!kt(t))throw Error(`Invalid wallet name: "${t}"
|
|
9
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);s.wallet=t}else if(br.has(n)){if(!Ou(t))throw Error(`Invalid URL for "${e}": "${t}"
|
|
11
10
|
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}"
|
|
12
|
-
Valid keys: ${
|
|
13
|
-
Valid keys: ${
|
|
14
|
-
`)){if(!
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
11
|
+
Valid keys: ${cn.join(", ")}`);dn(s,r)}function mi(e,t){let r=ys(e),n=Re(t);if(r==="network")n.network=Sr.network;else if(r==="wallet")delete n.wallet;else if(br.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}"
|
|
12
|
+
Valid keys: ${cn.join(", ")}`);dn(n,t)}function Ss(){return cn}var Sr,cn,$u,br;var Wt=T(()=>{ge();Sr={network:"undeployed"},cn=["network","proof-server","node","indexer-ws","wallet"],$u={"network-id":"network"};br=new Set(["proof-server","node","indexer-ws"])});import{execSync as Lu}from"child_process";import{ProtocolVersion as Uu}from"@midnightntwrk/wallet-sdk";function Ne(e){return gi.includes(e)}function kr(e){return{...Wu[e]}}function Cr(){return gi}function Bu(e){let t={node:new Set,indexer:new Set,proofServer:new Set};for(let n of e.split(`
|
|
13
|
+
`)){if(!n)continue;let[s="",o=""]=n.split("|"),i=(a)=>[...o.matchAll(new RegExp(`:(\\d+)->${a}/tcp`,"g"))].map((c)=>parseInt(c[1],10));if(s.includes("indexer"))i(8088).forEach((a)=>t.indexer.add(a));if(s.includes("midnight-node"))i(9944).forEach((a)=>t.node.add(a));if(s.includes("proof-server"))i(6300).forEach((a)=>t.proofServer.add(a))}let r=(n)=>[...n].sort((s,o)=>s-o);return{node:r(t.node),indexer:r(t.indexer),proofServer:r(t.proofServer)}}function Hu(e,t=ju){if(t.node&&e.node.length>1||t.indexer&&e.indexer.length>1||t.proofServer&&e.proofServer.length>1)throw new hi(e);return{nodePort:t.node?e.node[0]:void 0,indexerPort:t.indexer?e.indexer[0]:void 0,proofServerPort:t.proofServer?e.proofServer[0]:void 0}}function Gu(){if(process.env.MN_NO_LOCAL_DETECT==="1")return{node:[],indexer:[],proofServer:[]};try{return Bu(Lu('docker ps --format "{{.Image}}|{{.Ports}}"',{encoding:"utf-8",timeout:5000}))}catch{return{node:[],indexer:[],proofServer:[]}}}function wi(e,t={}){let r=kr(e),n=t.given??{},s={node:n.node===void 0,indexer:n.indexerWS===void 0,proofServer:n.proofServer===void 0};if(e==="undeployed"&&(s.node||s.indexer||s.proofServer)){let o=Hu((t.detect??Gu)(),s);if(o.indexerPort)r.indexer=`http://localhost:${o.indexerPort}${gr}`,r.indexerWS=`ws://localhost:${o.indexerPort}${Ut}`;if(o.nodePort)r.node=`ws://localhost:${o.nodePort}`;if(o.proofServerPort)r.proofServer=`http://localhost:${o.proofServerPort}`}if(n.node!==void 0)r.node=n.node;if(n.proofServer!==void 0)r.proofServer=n.proofServer;if(n.indexerWS!==void 0)r.indexerWS=n.indexerWS,r.indexer=yi(n.indexerWS);return r}function yi(e){return e.replace(/^wss:/,"https:").replace(/^ws:/,"http:").replace(/\/ws$/,"")}function ln(e){let t={};if(e.node!==void 0)t.node=e.node;if(e.indexerWS!==void 0)t["indexer-ws"]=e.indexerWS;if(e.proofServer!==void 0)t["proof-server"]=e.proofServer;return t}function Ie(e,t,r,n){let s=Re(n),o=vr(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=yi(e.indexerWS);return e}var st,Wu,gi,hi,ju;var ge=T(()=>{Wt();st=Uu.V9NativeForkSchedule,Wu={preprod:{indexer:`https://indexer.preprod.midnight.network${gr}`,indexerWS:`wss://indexer.preprod.midnight.network${Ut}`,node:"wss://rpc.preprod.midnight.network",proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:`https://indexer.preview.midnight.network${gr}`,indexerWS:`wss://indexer.preview.midnight.network${Ut}`,node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:`http://localhost:8088${gr}`,indexerWS:`ws://localhost:8088${Ut}`,node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},gi=["preprod","preview","undeployed"];hi=class hi extends Error{code="AMBIGUOUS_LOCAL_STACKS";constructor(e){super(`Several local Midnight stacks are running (node ${e.node.join(", ")}; indexer ${e.indexer.join(", ")}; proof-server ${e.proofServer.join(", ")}), and mn won't guess which one to use.
|
|
14
|
+
Pick one per command: --node ws://localhost:<port> --indexer-ws ws://localhost:<port>${Ut} --proof-server http://localhost:<port>
|
|
15
|
+
or once: midnight config set network undeployed, then midnight config set node / indexer-ws / proof-server <url>
|
|
16
|
+
Commands without endpoint flags (cache, test, dev) use the saved config. MN_NO_LOCAL_DETECT=1 turns detection off.`);this.name="AmbiguousLocalStacksError"}};ju={node:!0,indexer:!0,proofServer:!0}});import{HDWallet as Ku,Roles as bs}from"@midnightntwrk/wallet-sdk/hd";function vs(e,t){let r=Ku.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 Ct(e){return vs(e,bs.Zswap)}function Si(e){return vs(e,bs.NightExternal)}function ut(e){return vs(e,bs.Dust)}var Et=()=>{};import{NetworkId as Bt}from"@midnightntwrk/wallet-sdk";function Oe(e){let t=Vu[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}function ks(e){return Ju[e]}var Vu,Ju;var pt=T(()=>{Vu={PreProd:Bt.NetworkId.PreProd,Preview:Bt.NetworkId.Preview,Undeployed:Bt.NetworkId.Undeployed},Ju={preprod:Bt.NetworkId.PreProd,preview:Bt.NetworkId.Preview,undeployed:Bt.NetworkId.Undeployed}});import{HDWallet as qu,Roles as zu}from"@midnightntwrk/wallet-sdk/hd";import{createKeystore as Xu,PublicKey as Yu}from"@midnightntwrk/wallet-sdk/unshielded";import{MidnightBech32m as Zu,ShieldedAddress as Qu,ShieldedCoinPublicKey as ep,ShieldedEncryptionPublicKey as tp}from"@midnightntwrk/wallet-sdk/address-format";import*as bi from"@midnightntwrk/ledger-v9";function Se(e,t,r=0){let n=ks(t),s=qu.fromSeed(e);if(s.type!=="seedOk")throw Error("Invalid seed for HD wallet");let o=s.hdWallet.selectAccount(0).selectRole(zu.NightExternal).deriveKeyAt(r);if(o.type==="keyOutOfBounds")throw Error(`Key index ${r} out of bounds`);let i=Xu({kind:"schnorr",secret:o.key},n);return Yu.fromKeyStore(i).address}function xt(e,t=0){let r={};for(let n of Cr())r[n]=Se(e,n,t);return r}function Er(e){let t=xr(e),r={};for(let n of Cr()){let s=ks(n);r[n]=Zu.encode(s,t).asString()}return r}function xr(e){let t=Ct(e),r=bi.ZswapSecretKeys.fromSeed(t);return new Qu(new ep(Buffer.from(r.coinPublicKey,"hex")),new tp(Buffer.from(r.encryptionPublicKey,"hex")))}var Be=T(()=>{ge();Et();pt()});function he(e){let t=C(e.args,"network");if(t!==void 0){if(!Ne(t))throw Error(`Invalid network: "${t}"
|
|
17
|
+
Valid networks: ${Cr().join(", ")}`);return t}let r=Re(e.configDir);if(r.network&&Ne(r.network))return r.network;return"undeployed"}function ce(e){let t=he(e),r=vr(Re(e.configDir),t),n={node:C(e.args,"node")??r.node,indexerWS:C(e.args,"indexer-ws")??r["indexer-ws"],proofServer:C(e.args,"proof-server")??r["proof-server"]},s=wi(t,{given:n});return{name:t,config:s}}var Ae=T(()=>{ge();Wt()});import*as Z from"fs";import*as be from"path";import{homedir as rp}from"os";function jt(e,t,r){let n=be.resolve(e);if(!Z.existsSync(n))return;try{let s=JSON.parse(Z.readFileSync(n,"utf-8")),o=s.shieldedAddresses&&typeof s.shieldedAddresses==="object"?s.shieldedAddresses:{};if(o[t]=r,s.shieldedAddresses=o,s.shieldedAddress&&s.shieldedAddress===r)delete s.shieldedAddress;Z.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
18
|
+
`,{mode:xe})}catch{}}function Cs(){return be.join(rp(),oe)}function Ar(){return be.join(Cs(),on)}function ki(){return be.join(Cs(),sn)}function np(){let e=Cs();if(!Z.existsSync(e))Z.mkdirSync(e,{recursive:!0,mode:Ee})}function sp(e){return e.includes("/")||e.includes("\\")||e.endsWith(".json")}function re(e){if(e!==void 0){if(sp(e))return be.resolve(e);return be.join(Ar(),`${e}.json`)}let r=Re().wallet??ms;return be.join(Ar(),`${r}.json`)}function Ht(){return Re().wallet??ms}function Es(e){if(!kt(e))throw Error(`Invalid wallet name: "${e}"
|
|
19
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=be.join(Ar(),`${e}.json`);if(!Z.existsSync(t))throw Error(`Wallet "${e}" not found.
|
|
20
|
+
Run "midnight wallet list" to see available wallets.`);let r=Re();r.wallet=e,dn(r)}function xs(){let e=Ar();if(!Z.existsSync(e))return[];let t=Ht();return Z.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(Z.readFileSync(o,"utf-8")),a;if(i.addresses)a=i.addresses;else if(i.address&&i.seed)try{let d=Buffer.from(i.seed,"hex");a=xt(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=Er(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 op(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 Ci(e){return op(xs(),e)}function Ei(e){if(!kt(e))throw Error(`Invalid wallet name: "${e}"
|
|
21
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let t=Ar(),r=be.join(t,`${e}.json`);if(!Z.existsSync(r))throw Error(`Wallet "${e}" not found.
|
|
22
|
+
Run "midnight wallet list" to see available wallets.`);let n=Ht();if(e===n)throw Error(`Cannot remove the active wallet "${e}".
|
|
23
|
+
Switch to another wallet first: midnight wallet use <other-wallet>`);if(Z.readdirSync(t).filter((o)=>o.endsWith(".json")).length<=1)throw Error(`Cannot remove "${e}" — it is the only wallet.
|
|
24
|
+
`+"Create another wallet first: midnight wallet generate <name>");Z.unlinkSync(r)}function ie(e){let t=e?be.resolve(e):ki();if(!Z.existsSync(t))throw Error(`Wallet file not found: ${t}
|
|
25
|
+
Generate a wallet first: midnight wallet generate <name> --network <name>`);let r;try{r=Z.readFileSync(t,"utf-8")}catch(c){throw Error(`Failed to read wallet file: ${t}
|
|
26
|
+
${c.message}`)}let n;try{n=JSON.parse(r)}catch{throw Error(`Invalid JSON in wallet file: ${t}`)}if(!n.seed||!n.createdAt){let c=["seed","createdAt"];if(!n.addresses)c.push("address");let d=c.filter((u)=>!n[u]);if(d.length>0)throw Error(`Wallet file is missing required fields (${d.join(", ")}): ${t}`)}if(!/^[0-9a-fA-F]+$/.test(n.seed))throw Error(`Invalid seed format in wallet file (expected hex string): ${t}`);if(!n.addresses){if(!n.address)throw Error(`Wallet file is missing required fields (address): ${t}`);let c=Buffer.from(n.seed,"hex"),d=xt(c),u={seed:n.seed,addresses:d,createdAt:n.createdAt};if(n.mnemonic)u.mnemonic=n.mnemonic;let l=vi(n,c);if(l)u.shieldedAddresses=l;let f={...n,addresses:d};if(l)f.shieldedAddresses=l,delete f.shieldedAddress;return Z.writeFileSync(t,JSON.stringify(f,null,2)+`
|
|
27
|
+
`,{mode:xe}),u}if(typeof n.addresses!=="object")throw Error(`Wallet file has invalid addresses field: ${t}`);let s={seed:n.seed,addresses:n.addresses,createdAt:n.createdAt};if(n.mnemonic)s.mnemonic=n.mnemonic;let o=Buffer.from(n.seed,"hex"),i=vi(n,o);if(i)s.shieldedAddresses=i;if(i&&(!n.shieldedAddresses||typeof n.shieldedAddresses!=="object"||Object.keys(n.shieldedAddresses).length<Object.keys(i).length))try{let c={...n,shieldedAddresses:i};delete c.shieldedAddress,Z.writeFileSync(t,JSON.stringify(c,null,2)+`
|
|
28
|
+
`,{mode:xe})}catch{}return s}function vi(e,t){let r;try{r=Er(t)}catch{}let n=e.shieldedAddresses,s=n&&typeof n==="object"?n:null,o=s?Object.fromEntries(Object.entries(s).filter(([,i])=>typeof i==="string"&&i.length>0)):{};if(!r)return Object.keys(o).length>0?o:void 0;return{...r,...o}}function un(e,t){let r=t?be.resolve(t):ki();if(!t)np();else{let n=be.dirname(r);if(!Z.existsSync(n))Z.mkdirSync(n,{recursive:!0,mode:Ee})}return Z.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
29
|
+
`,{mode:xe}),r}var Me=T(()=>{Wt();Be()});var q;var ze=T(()=>{q=class q extends Error{constructor(e){super(e);this.name="UsageError",Object.setPrototypeOf(this,q.prototype)}}});function Tr(e,t){let r=e.trim().replace(/^0x/,"");if(r.length!==64&&r.length!==128||!/^[0-9a-fA-F]+$/.test(r))throw new q(`${t} must be 64 or 128 hex characters (a 32-byte seed, or a 64-byte BIP-39 seed)`);return Buffer.from(r,"hex")}function As(e,t={}){let r=C(e,"seed"),n=r??process.env.MN_SEED;if(n)return{seed:Tr(n,r?"--seed":"MN_SEED"),walletPath:null,config:null};let s=C(e,"wallet");if(s===void 0&&t.requireExplicit)throw new q(`${t.label??"This command"} needs a seed source. Provide one of:
|
|
30
|
+
--seed <hex> seed as 64 hex chars (32-byte) or 128 (64-byte BIP-39)
|
|
31
|
+
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
32
|
+
--wallet <name> derive from a saved wallet`);let o=re(s),i=ie(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function pn(e,t){return As(e,t).seed}var Gt=T(()=>{ze();Me()});function Nr(){return!("NO_COLOR"in process.env)}function Rr(e,t){if(!Nr())return e;return`\x1B[38;5;${t}m${e}\x1B[0m`}function P(e){if(!Nr())return e;return`\x1B[1m${e}\x1B[0m`}function g(e){if(!Nr())return e;return`\x1B[2m${e}\x1B[0m`}function H(e){return Rr(e,38)}function ae(e){return Rr(e,196)}function U(e){return Rr(e,40)}function Y(e){return Rr(e,226)}function Ir(e){return Rr(e,245)}function W(e,t=Ai){let r=` ${e} `,n=t-r.length;if(n<=0)return P(r);let s=Math.floor(n/2),o=n-s;return P("═".repeat(s)+r+"═".repeat(o))}function K(e=Ai){return g("─".repeat(e))}function E(e,t,r=16){let n=(e+":").padEnd(r);return` ${Ir(n)}${t}`}function At(e){let t=e<0n,r=t?-e:e,n=BigInt(10**as),s=r/n,i=(r%n).toString().padStart(as,"0");return`${t?"-":""}${s}.${i}`}function fn(e){return`${At(e)} NIGHT`}function Ue(e){let t=e<0n,r=t?-e:e,n=10n**BigInt(xi),s=r/n,a=(r%n).toString().padStart(xi,"0").replace(/0+$/,"").padEnd(6,"0");return`${t?"-":""}${s}.${a}`}function Dr(e){return`${Ue(e)} DUST`}function Q(e,t=!1){let r=t&&e.length>20?e.slice(0,10)+"…"+e.slice(-8):e;return H(r)}function ip(e,t){let r=[],n="",s=0,o=!1,i=0;while(i<e.length){let a=/^\x1b\[[0-9;]*m/.exec(e.slice(i));if(a){n+=a[0],o=!0,i+=a[0].length;continue}if(s===t)r.push(o?n+"\x1B[0m":n),n="",s=0,o=!1;n+=e[i],s+=1,i+=1}if(n.length>0)r.push(o?n+"\x1B[0m":n);return r}function ap(e,t){if(Kt(e).length<=t)return[e];let n=e.split(/(\s+)/).flatMap((a)=>Kt(a).length>t?ip(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 Ti(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 l of e){let f=l.split(`
|
|
33
|
+
`);for(let p of f)o.push(...ap(p,s))}let i=Math.max(...o.map((l)=>Kt(l).length)),a=Math.max(i+2,20),c=n.tl+n.h.repeat(a)+n.tr,d=n.bl+n.h.repeat(a)+n.br,u=o.map((l)=>{let f=Kt(l).length,p=a-f-2;return`${n.v} ${l}${" ".repeat(Math.max(0,p))} ${n.v}`});return[c,...u,d].join(`
|
|
34
|
+
`)}function ft(e,t){let n=[`${U("✓")} ${e}`];if(t)n.push(E("Transaction",H(t)));return n.join(`
|
|
35
|
+
`)}var Ai=60,xi=15,Kt=(e)=>e.replace(/\x1b\[[0-9;]*m/g,"");var ue=()=>{};var Pi={};me(Pi,{default:()=>Di});import*as Ii from"fs";import*as mn from"path";import{homedir as cp}from"os";import{generateMnemonic as dp,mnemonicToSeedSync as Ni,validateMnemonic as lp}from"@scure/bip39";import{wordlist as Ri}from"@scure/bip39/wordlists/english.js";async function Di(e){let t=he({args:e}),r=C(e,"output"),n=C(e,"seed"),s=process.env.MN_SEED?.trim(),o=n??(s?s:void 0),i=C(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?mn.resolve(r):mn.join(cp(),oe,sn);if(Ii.existsSync(a)&&!R(e,"force"))throw Error(`Wallet file already exists: ${a}
|
|
36
|
+
Use --force to overwrite, or --output <file> to save to a different path.`);let c,d;if(o!==void 0)c=Tr(o,n!==void 0?"--seed":"MN_SEED");else if(i!==void 0){if(!lp(i,Ri))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");d=i,c=Buffer.from(Ni(d))}else d=dp(Ri,256),c=Buffer.from(Ni(d));let u=xt(c),l=u[t],f={seed:c.toString("hex"),addresses:u,createdAt:new Date().toISOString()};if(d)f.mnemonic=d;let p=un(f,r);if(R(e,"json")){let m={addresses:u,activeAddress:l,activeNetwork:t,seed:c.toString("hex"),file:p,createdAt:f.createdAt};if(d)m.mnemonic=d;I(m);return}if(process.stdout.write(l+`
|
|
32
37
|
`),process.stderr.write(`
|
|
33
|
-
`+
|
|
38
|
+
`+W("Wallet Generated")+`
|
|
34
39
|
|
|
35
|
-
`),process.stderr.write(
|
|
36
|
-
`),process.stderr.write(
|
|
37
|
-
`),process.stderr.write(
|
|
40
|
+
`),process.stderr.write(E("Network",t)+`
|
|
41
|
+
`),process.stderr.write(E("Address",Q(l))+`
|
|
42
|
+
`),process.stderr.write(E("File",p)+`
|
|
38
43
|
`),process.stderr.write(`
|
|
39
|
-
`),d)process.stderr.write(
|
|
44
|
+
`),d)process.stderr.write(Y(P(" MNEMONIC (save securely!):"))+`
|
|
40
45
|
`),process.stderr.write(` ${d}
|
|
41
46
|
|
|
42
|
-
`);process.stderr.write(
|
|
47
|
+
`);process.stderr.write(Y(P(" SEED (hex):"))+`
|
|
43
48
|
`),process.stderr.write(` ${c.toString("hex")}
|
|
44
49
|
|
|
45
|
-
`),process.stderr.write(
|
|
50
|
+
`),process.stderr.write(K()+`
|
|
46
51
|
`),process.stderr.write(g(" Next: midnight info | midnight balance")+`
|
|
47
52
|
|
|
48
|
-
`),process.stderr.write(
|
|
49
|
-
`)}var
|
|
53
|
+
`),process.stderr.write(U("✓")+` Wallet saved
|
|
54
|
+
`)}var _i=T(()=>{Be();Ae();Me();Gt();ue()});var Oi={};me(Oi,{default:()=>$i});async function $i(e){let t=re(C(e,"wallet")),r=ie(t),n=he({args:e}),s=r.addresses[n];if(R(e,"json")){let i={addresses:r.addresses,activeNetwork:n,activeAddress:s,createdAt:r.createdAt,file:t};if(r.shieldedAddresses)i.shieldedAddresses=r.shieldedAddresses;I(i);return}process.stdout.write(s+`
|
|
50
55
|
`),process.stderr.write(`
|
|
51
|
-
`+
|
|
56
|
+
`+W("Wallet Info")+`
|
|
52
57
|
|
|
53
|
-
`);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],
|
|
54
|
-
`),process.stderr.write(` ${g("unshielded")} ${
|
|
55
|
-
`),
|
|
58
|
+
`);let o=Object.keys(r.addresses);for(let i=0;i<o.length;i++){let a=o[i],c=a===n,d=r.addresses[a],u=r.shieldedAddresses?.[a],l=c?P(H(a))+g(" (active)"):a;if(process.stderr.write(` ${l}
|
|
59
|
+
`),process.stderr.write(` ${g("unshielded")} ${Q(d)}
|
|
60
|
+
`),u)process.stderr.write(` ${g("shielded ")} ${Q(u)}
|
|
56
61
|
`);else process.stderr.write(` ${g("shielded ")} ${g("(unavailable)")}
|
|
57
62
|
`);if(i<o.length-1)process.stderr.write(`
|
|
58
63
|
`)}process.stderr.write(`
|
|
59
|
-
`+
|
|
64
|
+
`+K()+`
|
|
60
65
|
|
|
61
66
|
`),process.stderr.write(` ${g("created")} ${r.createdAt}
|
|
62
67
|
`),process.stderr.write(` ${g("file ")} ${t}
|
|
63
68
|
|
|
64
|
-
`)}var
|
|
65
|
-
`)}var
|
|
66
|
-
--seed <hex> 32-byte seed as 64 hex characters
|
|
67
|
-
MN_SEED=<hex> same seed via env (kept off the process list)
|
|
68
|
-
--wallet <name> derive from a saved wallet`);let o=ie(s),i=ce(o);return{seed:Buffer.from(i.seed,"hex"),walletPath:o,config:i}}function cn(e,t){return Os(e,t).seed}var dn=R(()=>{Ze();De()});function Du(e){return!Iu.includes(e)}function ln(e,t=!1){return Du(e)||t}function un(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var Iu;var Ms=R(()=>{Iu=["preview","preprod"]});import{NetworkId as Fs}from"@midnight-ntwrk/wallet-sdk-abstractions";function vt(e){let t=Pu[e];if(t===void 0)throw Error(`Unknown networkId: ${e}`);return t}var Pu;var pn=R(()=>{Pu={PreProd:Fs.NetworkId.PreProd,Preview:Fs.NetworkId.Preview,Undeployed:Fs.NetworkId.Undeployed}});import _u from"ws";function Kt(e,t,r){return new Promise((n,s)=>{let o=new _u(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,l=!1,u=!1,p,m=()=>{let w=new Map,y=0,S=0,b=0;for(let v of i.values())if(!v.spent){y++;let x=w.get(v.tokenType)??0n;if(w.set(v.tokenType,x+v.value),v.tokenType===jr)if(v.registeredForDustGeneration)S++;else b++}return{balances:w,utxoCount:y,txCount:a,highestTxId:c,registeredUtxos:S,unregisteredUtxos:b}},h=()=>{clearTimeout(p)},f=()=>{if(!u&&l&&(c===0||d>=c))u=!0,h(),o.send(JSON.stringify({id:"1",type:"complete"})),o.close(),n(m())};o.on("open",()=>{o.send(JSON.stringify({type:"connection_init"}))}),o.on("message",(w)=>{let y=JSON.parse(w.toString());switch(y.type){case"connection_ack":o.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:$u,variables:{address:e}}}));break;case"next":{if(y.payload?.errors){let b=y.payload.errors[0]?.message||"Unknown GraphQL error";if(!u)u=!0,h(),o.close(),s(Error(`GraphQL error: ${b}`));return}let S=y.payload?.data?.unshieldedTransactions;if(!S)return;if(S.__typename==="UnshieldedTransaction"){a++;let b=S;d=Math.max(d,b.transaction.id);for(let v of b.createdUtxos){let x=`${v.intentHash}:${v.outputIndex}`;i.set(x,{value:BigInt(v.value),tokenType:v.tokenType,spent:!1,registeredForDustGeneration:v.registeredForDustGeneration===!0})}for(let v of b.spentUtxos){let x=`${v.intentHash}:${v.outputIndex}`,_=i.get(x);if(_)_.spent=!0}if(r)r(d,c);f()}else if(S.__typename==="UnshieldedTransactionsProgress")c=S.highestTransactionId,l=!0,f();break}case"error":if(!u)u=!0,h(),o.close(),s(Error(`GraphQL subscription error: ${JSON.stringify(y.payload)}`));break;case"complete":break}}),o.on("error",(w)=>{if(!u){u=!0,h();let y=w.message?.trim()?w.message:`unable to reach ${t} (connection refused, DNS, or TLS error). Is the indexer running?`;s(Error(`WebSocket connection failed: ${y}`))}}),o.on("close",()=>{if(!u)u=!0,h(),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 ${Vr/1000}s. Indexer: ${t}`))},Vr)})}function wr(e){return e===jr}var $u=`
|
|
69
|
+
`)}var Mi=T(()=>{Me();Ae();ue();ue()});function je(){Fi=!0}function F(e,t){if(!Fi)return;let r=new Date().toISOString().slice(11,23);process.stderr.write(g(` [${r}] ${e}: ${t}`)+`
|
|
70
|
+
`)}var Fi=!1;var mt=()=>{};function pp(e){return!up.includes(e)}function gn(e,t=!1){return pp(e)||t}function hn(e){return`Shielded is unavailable on ${e} (no faucet). Use --force-shielded to sync anyway, or --network undeployed.`}var up;var Ts=T(()=>{up=["preview","preprod"]});import fp from"ws";function Vt(e,t,r){return new Promise((n,s)=>{let o=new fp(t,["graphql-transport-ws"]),i=new Map,a=0,c=0,d=0,u=!1,l=!1,f,p=()=>{let w=new Map,y=0,S=0,v=0;for(let A of i.values())if(!A.spent){y++;let N=w.get(A.tokenType)??0n;if(w.set(A.tokenType,N+A.value),A.tokenType===mr)if(A.registeredForDustGeneration)S++;else v++}return{balances:w,utxoCount:y,txCount:a,highestTxId:c,registeredUtxos:S,unregisteredUtxos:v}},m=()=>{clearTimeout(f)},h=()=>{if(!l&&u&&(c===0||d>=c))l=!0,m(),o.send(JSON.stringify({id:"1",type:"complete"})),o.close(),n(p())};o.on("open",()=>{o.send(JSON.stringify({type:"connection_init"}))}),o.on("message",(w)=>{let y=JSON.parse(w.toString());switch(y.type){case"connection_ack":o.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:mp,variables:{address:e}}}));break;case"next":{if(y.payload?.errors){let v=y.payload.errors[0]?.message||"Unknown GraphQL error";if(!l)l=!0,m(),o.close(),s(Error(`GraphQL error: ${v}`));return}let S=y.payload?.data?.unshieldedTransactions;if(!S)return;if(S.__typename==="UnshieldedTransaction"){a++;let v=S;d=Math.max(d,v.transaction.id);for(let A of v.createdUtxos){let N=`${A.intentHash}:${A.outputIndex}`;i.set(N,{value:BigInt(A.value),tokenType:A.tokenType,spent:!1,registeredForDustGeneration:A.registeredForDustGeneration===!0})}for(let A of v.spentUtxos){let N=`${A.intentHash}:${A.outputIndex}`,L=i.get(N);if(L)L.spent=!0}if(r)r(d,c);h()}else if(S.__typename==="UnshieldedTransactionsProgress")c=S.highestTransactionId,u=!0,h();break}case"error":if(!l)l=!0,m(),o.close(),s(Error(`GraphQL subscription error: ${JSON.stringify(y.payload)}`));break;case"complete":break}}),o.on("error",(w)=>{if(!l){l=!0,m();let y=w.message?.trim()?w.message:`unable to reach ${t} (connection refused, DNS, or TLS error). Is the indexer running?`;s(Error(`WebSocket connection failed: ${y}`))}}),o.on("close",()=>{if(!l)l=!0,m(),s(Error(`Indexer closed the connection before balance sync completed. Indexer: ${t}`))}),f=setTimeout(()=>{if(!l)l=!0,o.close(),s(Error(`Balance check timed out after ${us/1000}s. Indexer: ${t}`))},us)})}function Pr(e){return e===mr}var mp=`
|
|
69
71
|
subscription UnshieldedTransactions($address: UnshieldedAddress!) {
|
|
70
72
|
unshieldedTransactions(address: $address) {
|
|
71
73
|
__typename
|
|
@@ -79,10 +81,14 @@ Use --force to overwrite, or --output <file> to save to a different path.`);let
|
|
|
79
81
|
}
|
|
80
82
|
}
|
|
81
83
|
}
|
|
82
|
-
`;var
|
|
83
|
-
`),
|
|
84
|
+
`;var _r=()=>{};import{existsSync as $r,mkdirSync as gp,writeFileSync as hp,readFileSync as Li,unlinkSync as wn,readdirSync as Ns,renameSync as wp}from"node:fs";import{join as Tt,dirname as yp}from"node:path";import{homedir as Ui}from"node:os";import{randomBytes as Sp}from"node:crypto";import*as yn from"@midnightntwrk/ledger-v9";function Rs(e){return e.toString(16).padStart(64,"0")}function Xe(e){let t=ut(e),r=yn.DustSecretKey.fromSeed(t);return Rs(r.publicKey)}function Is(e,t){let r=t??Tt(Ui(),oe,$e);return Tt(r,e)}function Ds(e,t,r){let n=t.slice(0,20);return Tt(Is(e,r),`dust-${n}.json`)}function Or(e,t,r){let n=Ds(e,t,r);if(!$r(n))return null;try{let s=JSON.parse(Li(n,"utf-8"));if(s.version!==Wi)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:yn.DustLocalState.deserialize(o),lastAppliedEventId:s.lastAppliedEventId,retention:{ownedGenerationIndices:s.ownedGenerationIndices,generationFrontier:s.generationFrontier}}}catch{return null}}function Ps(e,t,r,n,s,o,i=bp){let a={version:Wi,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=Ds(e,t,s),d=yp(c);if(!$r(d))gp(d,{recursive:!0,mode:Ee});let u=c+`.tmp.${Sp(4).toString("hex")}`;try{hp(u,JSON.stringify(a),{mode:xe}),wp(u,c)}catch(l){try{wn(u)}catch{}throw l}}function Bi(e,t,r){if(!t)return[];let n=Is(e,r);if(!$r(n))return[];let s=[],o;try{o=Ns(n)}catch{return[]}for(let i of o){if(!i.startsWith("dust-")||!i.endsWith(".json"))continue;let a=Tt(n,i);try{let c=JSON.parse(Li(a,"utf-8"));if(!c.chainId)continue;if(c.chainId!==t)wn(a),s.push(a)}catch{}}return s}function gt(e,t,r){let n=r??Tt(Ui(),oe,$e);if(e&&t){let o=Ds(e,t,r);try{wn(o)}catch{}return}let s=(o)=>{if(!$r(o))return;try{for(let i of Ns(o))if(i.startsWith("dust-")&&i.endsWith(".json"))try{wn(Tt(o,i))}catch{}}catch{}};if(e){s(Is(e,r));return}if(!$r(n))return;try{for(let o of Ns(n))s(Tt(n,o))}catch{}}var Wi=3,bp;var Nt=T(()=>{Et();bp={ownedGenerationIndices:[],generationFrontier:0}});import{ShieldedWallet as ji}from"@midnightntwrk/wallet-sdk/shielded";import{UnshieldedWallet as Hi,createKeystore as vp,PublicKey as kp}from"@midnightntwrk/wallet-sdk/unshielded";import{DustWallet as Gi}from"@midnightntwrk/wallet-sdk/dust";import{WalletFacade as Ki,WalletEntrySchema as Cp,mergeWalletEntries as Ep}from"@midnightntwrk/wallet-sdk/facade";import*as Vi from"@midnightntwrk/ledger-v9";import{InMemoryTransactionHistoryStorage as xp}from"@midnightntwrk/wallet-sdk";import*as De from"rxjs";async function Ye(e,t,r){let n=Oe(t.networkId);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={shielded:Ct(e),unshielded:Si(e),dust:ut(e)},o=vp({kind:"schnorr",secret:s.unshielded},n),i={networkId:n,forks:st,indexerClientConnection:{indexerHttpUrl:t.indexer,indexerWsUrl:t.indexerWS},costParameters:{additionalFeeOverhead:Vo,feeBlocksMargin:Jo},txHistoryStorage:new xp(Cp,Ep),provingServerUrl:new URL(t.proofServer),relayURL:new URL(t.node)},a,c,d=()=>Ki.init({configuration:i,shielded:async(m)=>a=await ji(m).startWithSeed(s.shielded),unshielded:(m)=>Hi(m).startWithPublicKey(kp.fromKeyStore(o)),dust:async(m)=>c=await Gi(m).startWithSeed(s.dust)}),u=Vi.DustSecretKey.fromSeed(s.dust).publicKey,l=r?Tp(r,t,u):null,f=!1,p;if(l){F("facade","Restoring from cache...");try{p=await Ki.init({configuration:i,shielded:(m)=>a=ji(m).restore(l.shielded),unshielded:(m)=>Hi(m).restore(l.unshielded),dust:(m)=>c=Gi(m).restore(l.dust)}),f=!0,F("facade","Cache restore successful")}catch(m){F("facade",`Cache restore failed: ${m.message}`),process.stderr.write(` Cache restore failed, building from scratch: ${m.message}
|
|
85
|
+
`),p=await d()}}else F("facade","No cache, building fresh"),p=await d();if(!a||!c)throw Error("Wallet facade was built without its shielded or dust wallet");return{facade:p,keystore:o,seeds:s,seedStartable:{shielded:a,dust:c},restoredFromCache:f}}async function Ap(e){let{facade:t,seeds:r,seedStartable:n}=e;if(!e.restoredFromCache){await t.start(r);return}await Promise.all([n.shielded.startWithSeed(r.shielded),t.unshielded.start(),n.dust.startWithSeed(r.dust),t.pendingTransactionsService.start()])}function $s(e,t){let r=JSON.parse(e);if(BigInt(r.protocolVersion)<st.v9)throw Error(`Can't put a ledger-9 dust state into a snapshot at protocol version ${r.protocolVersion}: the wallet would read it as ledger 8 (fork at ${st.v9}).`);return r.state=Buffer.from(t.state.serialize()).toString("hex"),r.offset=t.lastAppliedEventId.toString(),JSON.stringify(r)}function Tp(e,t,r){try{let n=t.networkId.toLowerCase(),s=Rs(r),o=Or(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:$s(e.dust,o)}}catch(n){return F("facade",`Dust-direct bridge skipped: ${n.message}`),e}}function Ji(e,t){if(e.isStrictlyComplete())return!0;if(e.highestRelevantWalletIndex>0n&&e.appliedIndex>=e.highestRelevantWalletIndex)return!0;return qi(e)&&t}function qi(e){return e.highestRelevantWalletIndex===0n&&e.appliedIndex===0n}function _s(e,t="full"){let r=e.unshielded.progress.isStrictlyComplete(),n=t==="no-dust"||Ji(e.dust.progress,r);if(t==="lite")return r&&n;let s=e.shielded.progress;return(s.isStrictlyComplete()||r&&qi(s))&&r&&n}function Np(e){return!Ji(e.dust.progress,e.unshielded.progress.isStrictlyComplete())}async function ht(e,t={}){let{onProgress:r,onSyncDetail:n,timeoutMs:s,syncMode:o="full",requireStrictSync:i=!1}=t,{facade:a}=e;F("sync","Starting facade (connecting to node and indexer)..."),await Ap(e),F("sync","Facade started, subscribing to state...");let c=s??Yo;F("sync",`Sync timeout: ${c/1000}s, mode: ${o}`);let d=!i&&e.restoredFromCache,u=Date.now();return new Promise((l,f)=>{let p=!1,m=0,h="",w=null,y=setTimeout(()=>{if(!p){if(F("sync",`Sync timed out after ${c/1000}s (${m} emissions)`),w)try{let S=w.unshielded.progress;F("sync",` unshielded: applied=${S.appliedId} highest=${S.highestTransactionId} complete=${S.isStrictlyComplete()}`);let v=w.dust.progress;if(F("sync",` dust: applied=${v.appliedIndex} highest=${v.highestRelevantWalletIndex} complete=${v.isStrictlyComplete()} connected=${v.isConnected}`),o==="full"){let A=w.shielded.progress;F("sync",` shielded: complete=${A.isStrictlyComplete()}`)}}catch{}f(Error("Wallet sync timed out"))}},c);e.keepAlive=a.state().subscribe({next:(S)=>{if(p)return;if(m++,w=S,e.restoredFromCache){let A=Ip(S);if(A){p=!0,clearTimeout(y),F("sync",`Stale cache detected: ${A}`),f(new Sn(A));return}}if(r){let A=S.unshielded.progress;if(A){let N=Number(A.appliedId),L=Number(A.highestTransactionId);r(Math.min(N,L),L)}}let v=[];try{if((o==="full"||o==="no-dust")&&!S.shielded.progress.isStrictlyComplete())v.push("shielded");if(o!=="no-dust"&&Np(S))v.push("dust");if(!S.unshielded.progress.isStrictlyComplete())v.push("unshielded")}catch{}if(v.length>0){n?.(v.join(", "));let A=v.join(",");if(m===1||A!==h||m%100===0)F("sync",`Waiting on: ${v.join(", ")} (emission #${m})`),h=A}if(_s(S,o)){p=!0,clearTimeout(y),F("sync",`Sync complete after ${m} emissions`),l(S);return}if(d){let A=Date.now()-u;if(A>=Rp&&_s(S,"no-dust"))p=!0,clearTimeout(y),F("sync",`Sync resolved via cached-restore grace (${A}ms, ${m} emissions)`),l(S)}},error:(S)=>{if(!p)F("sync",`Sync error: ${S.message}`),clearTimeout(y),f(S)}})})}function Ip(e){let{appliedId:t,highestTransactionId:r}=e.unshielded.progress;if(r>0n&&t>r)return`unshielded cache applied=${t} but chain highest=${r}.`;return}async function zi(e){let t=(r)=>{let n=r.unshielded.progress.isStrictlyComplete(),s=r.dust.progress.isStrictlyComplete();return n&&s};try{return await De.firstValueFrom(e.facade.state().pipe(De.filter(t),De.timeout(15000)))}catch{return await De.firstValueFrom(e.facade.state())}}function Rt(e){return e.dust.availableCoins.length>0||e.dust.balance(new Date)>0n}async function bn(e,t=60000){try{return await De.firstValueFrom(e.facade.state().pipe(De.filter(Rt),De.timeout(t)))}catch{return await De.firstValueFrom(e.facade.state())}}async function Os(e,t="full"){return De.firstValueFrom(e.facade.state().pipe(De.filter((r)=>_s(r,t)),De.timeout(Zo)))}async function Fe(e){e.keepAlive?.unsubscribe(),await Promise.race([e.facade.stop(),new Promise((t)=>setTimeout(t,5000))])}function Te(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 Rp=1e4,Sn;var He=T(()=>{ge();pt();Et();Nt();mt();Sn=class Sn extends Error{code="STALE_CACHE";constructor(e){super(`Cached wallet state is stale (from a previous chain). ${e}
|
|
84
86
|
Run: midnight cache clear --wallet <name> --network <name>
|
|
85
|
-
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function
|
|
87
|
+
Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});function Dp(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 Xi(e){let t=new Set,r=[e];while(r.length>0){let n=r.pop();if(!n||typeof n!=="object"||t.has(n))continue;t.add(n);let s=n;if(s._tag==="Wallet.InsufficientFunds"&&s.tokenType==="dust")return!0;if(typeof s.message==="string"&&/no dust tokens|dust.*unavailable/i.test(s.message))return!0;r.push(s.cause,s[Pp],s.error,s.defect,s.left,s.right)}return!1}function vn(e){let t=e?.message?.toLowerCase()??"";return t.includes("not enough dust")||t.includes("dust generated")||t.includes("insufficient generated dust")||t.includes("insufficient funds")||t.includes("no dust tokens")||Dp(e)}function Mr(e){let t=e?.message?.toLowerCase()??"";if(e?._tag==="Wallet.InsufficientFunds")return!0;return t==="insufficient funds"||t.startsWith("insufficient funds")}var Pp;var Fr=T(()=>{Pp=Symbol.for("effect/Runtime/FiberFailure/Cause")});import{existsSync as Ur,mkdirSync as _p,writeFileSync as $p,readFileSync as Yi,unlinkSync as Lr,readdirSync as kn,renameSync as Op}from"node:fs";import{join as Ze,dirname as Mp}from"node:path";import{homedir as Ms}from"node:os";import{randomBytes as Fp}from"node:crypto";function Fs(e,t,r){let n=r??Ze(Ms(),oe,$e),s=e.slice(0,20);return Ze(n,t,`${s}.json`)}function wt(e,t,r){let n=Fs(e,t,r);if(!Ur(n))return null;try{let s=Yi(n,"utf-8"),o=JSON.parse(s);if(o.version!==fs)return null;if(o.network!==t)return null;if(o.address!==e)return null;if(!o.wallets||typeof o.wallets.shielded!=="string"||typeof o.wallets.unshielded!=="string"||typeof o.wallets.dust!=="string")return null;return o.wallets}catch{return null}}async function ot(e,t,r,n,s){let[o,i,a]=await Promise.all([r.shielded.serializeState(),r.unshielded.serializeState(),r.dust.serializeState()]),c={version:fs,network:t,address:e,timestamp:new Date().toISOString(),wallets:{shielded:o,unshielded:i,dust:a},...s?{chainId:s}:{}},d=Fs(e,t,n),u=Mp(d);if(!Ur(u))_p(u,{recursive:!0,mode:Ee});let l=d+`.tmp.${Fp(4).toString("hex")}`;try{$p(l,JSON.stringify(c),{mode:xe}),Op(l,d)}catch(f){try{Lr(l)}catch{}throw f}}function Zi(e,t,r){if(!t)return[];let n=r??Ze(Ms(),oe,$e),s=Ze(n,e);if(!Ur(s))return[];let o=[],i;try{i=kn(s)}catch{return[]}for(let a of i){if(!a.endsWith(".json"))continue;let c=Ze(s,a);try{let d=JSON.parse(Yi(c,"utf-8"));if(!d.chainId)continue;if(d.chainId!==t)Lr(c),o.push(c)}catch{}}return o}function Ge(e,t,r){let n=r??Ze(Ms(),oe,$e);if(e&&t){let s=Fs(e,t,r);try{Lr(s)}catch{}return}if(t){let s=Ze(n,t);if(!Ur(s))return;try{for(let o of kn(s))if(o.endsWith(".json"))Lr(Ze(s,o))}catch{}return}if(!Ur(n))return;try{for(let s of kn(n)){let o=Ze(n,s);try{for(let i of kn(o))if(i.endsWith(".json"))Lr(Ze(o,i))}catch{}}}catch{}}var It=()=>{};import Lp from"ws";async function Jt(e,t,r=[]){let n=e.timeoutMs??Up;return new Promise((s,o)=>{let i=new Lp(e.url),a=!1,c=(u)=>{if(!a)a=!0,u()},d=setTimeout(()=>{c(()=>{try{i.close()}catch{}o(Error(`RPC ${t} timed out after ${n}ms`))})},n);i.on("open",()=>{try{i.send(JSON.stringify({jsonrpc:"2.0",id:1,method:t,params:r}))}catch(u){clearTimeout(d),c(()=>o(u instanceof Error?u:Error(String(u))))}}),i.on("message",(u)=>{clearTimeout(d),c(()=>{try{let l=JSON.parse(u.toString());try{i.close()}catch{}if(l.error)o(Error(`RPC ${t}: ${l.error.message}`));else s(l.result)}catch(l){o(l instanceof Error?l:Error(String(l)))}})}),i.on("error",(u)=>{clearTimeout(d),c(()=>o(u instanceof Error?u:Error(String(u))))})})}var Up=5000;var Cn=()=>{};async function qt(e){let t=Qi.get(e);if(t&&Date.now()-t.fetchedAt<Wp)return t.hash;try{let r=await Jt({url:e,timeoutMs:5000},"chain_getBlockHash",[0]);if(typeof r!=="string"||!r.startsWith("0x"))return null;return Qi.set(e,{hash:r,fetchedAt:Date.now()}),r}catch{return null}}var Qi,Wp=60000;var En=T(()=>{Cn();Qi=new Map});async function xn(e,t,r,n){let s;try{s=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r?{query:t,variables:r}:{query:t}),signal:AbortSignal.timeout(n)})}catch(i){throw new Dt(i.message)}if(!s.ok)throw new Dt(`HTTP ${s.status} ${s.statusText}`.trim());let o;try{o=await s.json()}catch(i){throw new Dt(`the answer is not JSON: ${i.message}`)}if(o.errors?.length)throw new Dt(o.errors.map((i)=>i.message).join("; "));if(o.data==null)throw new Dt("the answer has no data");return o.data}var Dt;var Ls=T(()=>{Dt=class Dt extends Error{constructor(e){super(e);this.name="IndexerQueryError",Object.setPrototypeOf(this,Dt.prototype)}}});function ta(e,t){if(t!==null&&t<st.v9)throw new ea(e,t)}async function An(e){try{let r=(await xn(e,"{ block { protocolVersion } }",void 0,Bp)).block?.protocolVersion;return typeof r==="number"?BigInt(r):null}catch{return null}}async function Qe(e,t,r=An){ta(e,await r(t.indexer))}async function ra(e,t,r={}){let n=await(r.fetchVersion??An)(t.indexer);if(n===null)throw new Us("indexer",t.indexer);if(ta(e,n),await(r.fetchGenesis??qt)(t.node)===null)throw new Us("node",t.node)}function na(e){return["shielded","unshielded","dust"].filter((t)=>e[t]<st.v9)}var ea,Bp=5000,Us;var zt=T(()=>{ge();En();Ls();ea=class ea extends Error{code="UNSUPPORTED_LEDGER";constructor(e,t){super(`${e} is on ledger 8 (protocol version ${t}), and this build of mn supports ledger 9 only.
|
|
88
|
+
Use midnight-wallet-cli 0.5.x for ledger-8 networks.`);this.name="UnsupportedLedgerError"}};Us=class Us extends Error{code="LOCAL_STACK_UNREACHABLE";constructor(e,t){super(`No ledger-9 stack is reachable: the ${e} at ${t} did not answer.
|
|
89
|
+
This build of mn can't start a localnet (no published indexer image runs ledger 9 yet).
|
|
90
|
+
Start a ledger-9 stack (node 2.1.0-rc.2, proof-server 9.0.0-rc.8, a 4.4 indexer) and point mn at it:
|
|
91
|
+
midnight config set network undeployed, then midnight config set node / indexer-ws / proof-server <url>`);this.name="LocalStackUnreachableError"}}});function jp(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=jp(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 Hp from"ws";function Nn(e,t){let{query:r,variables:n,onNext:s,buildResult:o,timeoutMs:i,idleMs:a,idleBeforeFirstEvent:c,initialSilenceMs:d,signal:u}=t;return new Promise((l,f)=>{let p=new Hp(e,["graphql-transport-ws"]),m=!1,h=!1,w,y,S,v=()=>{if(clearTimeout(w),y)clearTimeout(y);if(S)clearTimeout(S);try{p.close()}catch{}u?.removeEventListener("abort",L)},A=(X,V)=>{if(h)return;h=!0,v();try{l(o(V))}catch(O){f(O instanceof Error?O:Error(String(O)))}},N=(X)=>{if(h)return;h=!0,v(),f(X)},L=()=>N(Error("Operation cancelled"));u?.addEventListener("abort",L,{once:!0});let ee=()=>{if(y)clearTimeout(y);y=setTimeout(()=>{if(!h&&(m||c))A("idle",!1)},a)};p.on("open",()=>{p.send(JSON.stringify({type:"connection_init"}))}),p.on("message",(X)=>{let V;try{V=JSON.parse(X.toString())}catch{return}if(V.type==="connection_ack"){if(p.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:r,variables:n}})),c)ee();if(d&&d>0)S=setTimeout(()=>{if(!m&&!h)A("initial-silence",!1)},d);return}if(V.type==="error"){N(Error(`GraphQL subscription error: ${JSON.stringify(V.payload)?.slice(0,300)}`));return}if(V.type!=="next")return;if(V.payload?.errors){N(Error(`GraphQL error: ${V.payload.errors[0]?.message||"unknown"}`));return}if(m=!0,S)clearTimeout(S),S=void 0;let O;try{O=s(V.payload?.data)}catch(_){N(_ instanceof Error?_:Error(String(_)));return}if(ee(),O)A("caught-up",!1)}),p.on("error",(X)=>N(Error(`WebSocket error: ${X.message}`))),p.on("close",()=>{if(h)return;A(m?"closed-early":"graceful-close",m)}),w=setTimeout(()=>A("timeout",!0),i)})}var Ws=()=>{};import*as Xt from"@midnightntwrk/ledger-v9";function Kp(){let e=new Xt.DustParameters(qo,zo,Xo);return new Xt.DustLocalState(e)}function sa(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:u=0,initialRetention:l,collapse:f}=r,p=f!==!1&&process.env[Bs]!=="1",m=500,h=d??Kp(),w=[],y=e.publicKey,S=new Set((l?.ownedGenerationIndices??[]).map(BigInt)),v=BigInt(l?.generationFrontier??0),A=(O)=>{let _=O.content;if(_?.tag!=="dustInitialUtxo"||_.generationIndex===void 0)return;let ne=_.generationIndex;if(ne+1n>v)v=ne+1n;if(_.generation?.owner===y)S.add(ne)},N=()=>({ownedGenerationIndices:[...S].map(Number),generationFrontier:Number(v)}),L=0,ee=u-1,X=-1,V=()=>{if(w.length===0)return;if(h=h.replayEvents(e,w),L+=w.length,w.length=0,p)h=Tn(h,S,v).state;if(s&&ee>=0)try{s(h,ee,N())}catch{}};return Nn(t,{query:Gp,variables:{id:u},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(O)=>{let _=O?.dustLedgerEvents;if(!_)return!1;let ne;try{ne=Xt.Event.deserialize(Buffer.from(_.raw,"hex"))}catch(de){throw Error(`Failed to deserialize dust event ${_.id}: ${de.message}`)}if(A(ne),w.push(ne),ee=_.id,_.maxId>X)X=_.maxId;if(w.length>=500)try{V()}catch(de){throw Error(`Failed applying dust events: ${de.message}`)}return n?.(L+w.length,X),ee>=X},buildResult:(O)=>{try{V();let _=new Date;return h=h.processTtls(_),{balance:h.walletBalance(_),availableCoins:h.utxos.length,eventCount:L,ownedUtxoCount:h.utxos.length,syncTime:h.syncTime,state:h,retention:N(),lastAppliedEventId:ee,partial:O}}catch(_){throw Error(`Failed to build dust state: ${_.message}`)}}})}var Bs="MN_DISABLE_DUST_COLLAPSE",Gp=`
|
|
86
92
|
subscription DustLedgerEvents($id: Int) {
|
|
87
93
|
dustLedgerEvents(id: $id) {
|
|
88
94
|
type: __typename
|
|
@@ -91,9 +97,9 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
91
97
|
maxId
|
|
92
98
|
}
|
|
93
99
|
}
|
|
94
|
-
`;var
|
|
95
|
-
`),
|
|
96
|
-
`).filter(Boolean).pop(),S=y?JSON.parse(y):JSON.parse(
|
|
100
|
+
`;var js=T(()=>{Ws()});import{spawn as Vp}from"node:child_process";import{existsSync as Pt,mkdirSync as Jp,readFileSync as ca,readdirSync as oa,unlinkSync as ia,writeFileSync as qp}from"node:fs";import{homedir as da}from"node:os";import{dirname as aa,join as it}from"node:path";import{fileURLToPath as zp}from"node:url";import*as la from"@midnightntwrk/ledger-v9";function ua(){let e=process.env.MN_DUST_SYNC_BIN;if(e&&Pt(e))return e;let t=process.platform==="win32"?"dust-sync.exe":"dust-sync",r=aa(zp(import.meta.url));for(let n of[["..",".."],[".."]]){let s=it(r,...n,"sidecar","dust-sync","target","release",t);if(Pt(s))return s}try{let n=`@nel349/dust-sync-${process.platform}-${process.arch}`,s=Xp(import.meta.url),o=it(aa(s.resolve(`${n}/package.json`)),t);if(Pt(o))return o}catch{}return null}function Xp(e){return globalThis.require??jo("node:module").createRequire(e)}function pa(){if(Yp!==Zp)return!1;if(process.env.MN_DISABLE_NATIVE_DUST==="1")return!1;return ua()!==null}function Qp(e,t,r){if(e+1>=t)return"existing";if(r)return"seed";return"fresh"}function ef(e){if(!Pt(e))return-2;try{let t=JSON.parse(ca(e,"utf-8"));return typeof t.last_applied_event_id==="number"?t.last_applied_event_id:-2}catch{return-2}}function tf(e,t){let r=it(da(),oe,$e,e);if(!Pt(r))Jp(r,{recursive:!0,mode:Ee});return it(r,`dust-native-${t.slice(0,20)}.json`)}function Rn(e,t){let r=it(da(),oe,$e);if(e&&t){try{ia(it(r,e,`dust-native-${t.slice(0,20)}.json`))}catch{}return}let n=(s)=>{if(!Pt(s))return;try{for(let o of oa(s))if(o.startsWith("dust-native-")&&o.endsWith(".json"))try{ia(it(s,o))}catch{}}catch{}};if(e){n(it(r,e));return}if(!Pt(r))return;try{for(let s of oa(r))n(it(r,s))}catch{}}function fa(e,t,r){return new Promise((n,s)=>{let o=ua();if(!o){s(Error("dust-sync sidecar not found"));return}let i=t.networkId.toLowerCase(),a=Xe(e),c=tf(i,a),d=["--indexer-ws",t.indexerWS,"--out",c],u=Qp(ef(c),r.startFromId,!!r.initialState);if(u==="seed"){let w={dust_state:Buffer.from(r.initialState.serialize()).toString("hex"),last_applied_event_id:r.startFromId-1,owned_generation_indices:r.initialRetention?.ownedGenerationIndices??[],generation_frontier:r.initialRetention?.generationFrontier??0,balance:"0",available_coins:0,events_applied:0,partial:!0};qp(c,JSON.stringify(w),{mode:xe})}if(u!=="fresh")d.push("--resume",c);let l=Vp(o,d,{stdio:["pipe","pipe","pipe"]}),f=()=>{try{l.kill("SIGINT")}catch{}};r.signal?.addEventListener("abort",f,{once:!0}),l.stdin.on("error",()=>{});let p=Buffer.from(ut(e)).toString("hex");l.stdin.write(p+`
|
|
101
|
+
`),l.stdin.end();let m="",h="";l.stdout.on("data",(w)=>{m+=w.toString()}),l.stderr.on("data",(w)=>{let y=w.toString();h=(h+y).slice(-2000);for(let S of y.matchAll(/applied (\d+) \/ (\d+)/g))r.onProgress?.(Number(S[1]),Number(S[2]))}),l.on("error",(w)=>{r.signal?.removeEventListener("abort",f),s(w)}),l.on("close",(w)=>{if(r.signal?.removeEventListener("abort",f),w!==0){s(Error(`dust-sync exited ${w}: ${h.trim().slice(-300)}`));return}try{let y=m.trim().split(`
|
|
102
|
+
`).filter(Boolean).pop(),S=y?JSON.parse(y):JSON.parse(ca(c,"utf-8"));n(rf(S))}catch(y){s(Error(`dust-sync output parse failed: ${y.message}`))}})})}function rf(e){let t=new Date,r=la.DustLocalState.deserialize(new Uint8Array(Buffer.from(e.dust_state,"hex")));if(process.env[Bs]!=="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 Yp=8,Zp=9;var Hs=T(()=>{Et();js();Nt()});import*as ga from"@midnightntwrk/ledger-v9";class ha{now;fetchTip;fetchUnshielded;fetchDust;fetchChainId;fetchProtocolVersion;cacheDir;dustMemo=new Map;unshieldedMemo=new Map;tipMemo=new Map;constructor(e={}){this.now=e.now??Date.now,this.fetchTip=e.fetchTip??df,this.fetchUnshielded=e.fetchUnshielded??lf,this.fetchDust=e.fetchDust??pf,this.fetchChainId=e.fetchChainId??qt,this.fetchProtocolVersion=e.fetchProtocolVersion??An,this.cacheDir=e.cacheDir}async dust(e,t,r={}){let n=In(t);await Qe(n,t,this.fetchProtocolVersion);let s=Xe(e),o=`${n}:${s}`;if(!r.forceFresh){let m=await this.tryMemo(o,t,this.dustMemo,r.signal);if(m)return{...m,fromCache:!0,eventsApplied:0}}let i=await this.fetchChainId(t.node).catch(()=>null);Bi(n,i,this.cacheDir);let a=i??void 0,c=r.forceFresh?null:Or(n,s,this.cacheDir),d=c!==null,u=0,l=c?.lastAppliedEventId??-1,f=null;for(let m=0;m<sf;m++){if(r.signal?.aborted)throw Error("Operation cancelled");let h=c?c.lastAppliedEventId+1:0;if(r.onStatus?.(m>0?`Resuming dust from event ${h} (continuation ${m+1})…`:c?`Resuming dust from event ${h}…`:"Reading dust events…"),f=await this.fetchDust(e,t,{startFromId:h,initialState:c?.state,initialRetention:c?.retention,signal:r.signal,onProgress:(w,y)=>{let S=Math.max(1,y+1-h);r.onStatus?.(`Reading dust events… ${w}/${S}`),r.onProgress?.(w,y)},onCheckpoint:(w,y,S)=>{try{Ps(n,s,w,y,this.cacheDir,a,S)}catch{}}}),l=f.lastAppliedEventId>=0?f.lastAppliedEventId:c?.lastAppliedEventId??-1,f.lastAppliedEventId>=0||!c)try{Ps(n,s,f.state,l,this.cacheDir,a,f.retention)}catch{}if(u+=f.eventCount,!f.partial)break;c=Or(n,s,this.cacheDir)}if(!f)throw Error("Dust sync exhausted retries without producing a result");let p={state:f.state,balance:f.balance,availableCoins:f.availableCoins,ownedUtxoCount:f.ownedUtxoCount,syncTime:f.syncTime,fromCache:d,eventsApplied:u,lastAppliedEventId:l,partial:f.partial,fetchedAt:this.now()};return await this.memoize(this.dustMemo,o,p,t,r.signal),p}async unshielded(e,t,r={}){let n=In(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=In(t),c=Se(e,a),d=t.networkId!=="Undeployed",u=n.syncTimeoutMs??(d?af:of);await Qe(a,t,this.fetchProtocolVersion);let l=await this.fetchChainId(t.node).catch(()=>null);Zi(a,l,this.cacheDir);let f=l??void 0;if(i&&!n.noPrime&&!n.forceFresh)try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch(y){n.onSyncWarning?.("PrePrime",y.message)}let p,m,h=!1,w=async()=>{if(h||!p)return;h=!0;try{await Fe(p)}catch{}};try{for(let v=1;v<=Wr;v++){if(n.signal?.aborted)throw Error("Operation cancelled");let A=n.forceFresh?null:wt(c,a,this.cacheDir);p=await Ye(e,t,A);try{m=await ht(p,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:u,syncMode:s,requireStrictSync:o});break}catch(N){if(n.signal?.aborted)throw Error("Operation cancelled");if(N instanceof Sn&&v<Wr&&i){n.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${v+1}/${Wr})...`),await Fe(p).catch(()=>{}),p=void 0,Ge(c,a,this.cacheDir),gt(a,Xe(e),this.cacheDir);try{await this.dust(e,t,{signal:n.signal,onStatus:n.onStatus})}catch{}continue}if(v<Wr&&String(N?.message??"").includes("timed out")){try{await ot(c,a,p.facade,this.cacheDir,f)}catch{}n.onStatus?.(`Sync timed out, retrying (attempt ${v+1}/${Wr})...`),await Fe(p).catch(()=>{}),p=void 0;continue}throw N}}if(!p||!m)throw Error("Sync failed: no facade state after retries");let y,S=0;while(!0){if(S++,n.signal?.aborted)throw Error("Operation cancelled");try{y=await r({bundle:p,state:m});break}catch(v){if(!(i&&S<ma&&Mr(v)))throw v;if(n.onStatus?.(`Refreshing wallet state (attempt ${S+1}/${ma})...`),await Fe(p).catch(()=>{}),p=void 0,await new Promise((L)=>setTimeout(L,cf)),n.signal?.aborted)throw Error("Operation cancelled");let N=wt(c,a,this.cacheDir);p=await Ye(e,t,N),m=await ht(p,{onProgress:n.onSyncProgress,onSyncDetail:n.onSyncDetail,timeoutMs:u,syncMode:s,requireStrictSync:o})}}if(!n.skipAutoSave)try{await ot(c,a,p.facade,this.cacheDir,f)}catch{}if(!n.readOnly)this.invalidate({network:t,seed:e});return y}finally{await w()}}invalidate(e){let t=In(e.network),r=e.kinds??["dust","unshielded","facade"];if(r.includes("dust"))if(e.seed){let n=Xe(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{Ge(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<nf)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 df(e){return Jt({url:e.node,timeoutMs:3000},"chain_getBlockHash",[])}function lf(e,t,r){return Vt(e,t.indexerWS,r)}function uf(e,t,r){let n=ut(e),s=ga.DustSecretKey.fromSeed(n);return sa(s,t.indexerWS,r)}async function pf(e,t,r){if(pa())try{return await fa(e,t,r)}catch(n){F("dust",`native sidecar failed, using WASM: ${n.message}`)}return uf(e,t,r)}function In(e){let t=e.networkId.toLowerCase();if(Ne(t))return t;throw Error(`Unsupported network: ${e.networkId}`)}function ve(){if(!Gs)Gs=new ha;return Gs}var nf=5000,sf=6,of=30000,af=120000,Wr=3,ma=5,cf=5000,Gs=null;var yt=T(()=>{ge();He();Fr();Nt();It();En();zt();_r();js();Hs();mt();Cn();Et();Be()});import*as Yt from"@midnightntwrk/ledger-v9";function mf(e){let t=Yt.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 wa(e,t,r={}){let{onProgress:n,onCheckpoint:s,timeoutMs:o=600000,idleMs:i=5000,initialSilenceMs:a=3000,signal:c,initialState:d,startFromId:u=0}=r,l=500,f=d??new Yt.ZswapLocalState,p=[],m=0,h=u-1,w=-1,y=()=>{if(p.length===0)return;if(f=f.replayEventsWithChanges(e,p).state,m+=p.length,p.length=0,s&&h>=0)try{s(f,h)}catch{}};return Nn(t,{query:ff,variables:{id:u},idleMs:i,timeoutMs:o,initialSilenceMs:d?a:0,signal:c,onNext:(S)=>{let v=S?.zswapLedgerEvents;if(!v)return!1;let A;try{A=Yt.Event.deserialize(new Uint8Array(Buffer.from(v.raw,"hex")))}catch(N){throw Error(`Failed to deserialize zswap event ${v.id}: ${N.message}`)}if(p.push(A),h=v.id,v.maxId>w)w=v.maxId;if(p.length>=500)try{y()}catch(N){throw Error(`Failed applying zswap events: ${N.message}`)}return n?.(m+p.length,w),h>=w},buildResult:(S)=>{try{y();let{balance:v,count:A}=mf(f);return{balance:v,availableCoins:A,eventCount:m,state:f,lastAppliedEventId:h,partial:S}}catch(v){throw Error(`Failed to build shielded state: ${v.message}`)}}})}var ff=`
|
|
97
103
|
subscription ZswapLedgerEvents($id: Int) {
|
|
98
104
|
zswapLedgerEvents(id: $id) {
|
|
99
105
|
id
|
|
@@ -101,112 +107,110 @@ Or: midnight cache clear (wipe all caches)`);this.name="StaleCacheError"}}});f
|
|
|
101
107
|
maxId
|
|
102
108
|
}
|
|
103
109
|
}
|
|
104
|
-
`;var
|
|
105
|
-
Expected a bech32m address for network "${t.networkId}"`)}}function
|
|
106
|
-
Available: ${
|
|
110
|
+
`;var ya=T(()=>{Ws()});import{existsSync as Dn,mkdirSync as gf,writeFileSync as hf,readFileSync as wf,unlinkSync as Vs,readdirSync as Sa,renameSync as yf}from"node:fs";import{join as Zt,dirname as Sf}from"node:path";import{homedir as ba}from"node:os";import{randomBytes as bf}from"node:crypto";import*as Br from"@midnightntwrk/ledger-v9";function ka(e){return Br.ZswapSecretKeys.fromSeed(Ct(e)).coinPublicKey}function Ca(e,t){let r=t??Zt(ba(),oe,$e);return Zt(r,e)}function Js(e,t,r){let n=t.slice(0,20);return Zt(Ca(e,r),`shielded-${n}.json`)}function vf(e,t,r,n){let s=Js(e,t,r);if(!Dn(s))return null;try{let o=JSON.parse(wf(s,"utf-8"));if(o.version!==va)return null;if(o.network!==e)return null;if(o.coinPublicKeyHex!==t)return null;if(typeof o.lastAppliedEventId!=="number")return null;if(typeof o.zswapState!=="string")return null;if(n&&o.chainId&&o.chainId!==n)return null;return{state:Br.ZswapLocalState.deserialize(new Uint8Array(Buffer.from(o.zswapState,"hex"))),lastAppliedEventId:o.lastAppliedEventId}}catch{return null}}function Ks(e,t,r,n,s,o){let i={version:va,network:e,coinPublicKeyHex:t,lastAppliedEventId:n,timestamp:new Date().toISOString(),zswapState:Buffer.from(r.serialize()).toString("hex"),...o?{chainId:o}:{}},a=Js(e,t,s),c=Sf(a);if(!Dn(c))gf(c,{recursive:!0,mode:Ee});let d=a+`.tmp.${bf(4).toString("hex")}`;try{hf(d,JSON.stringify(i),{mode:xe}),yf(d,a)}catch(u){try{Vs(d)}catch{}throw u}}function Pn(e,t,r){let n=r??Zt(ba(),oe,$e);if(e&&t){let o=Js(e,t,r);try{Vs(o)}catch{}return}let s=(o)=>{if(!Dn(o))return;try{for(let i of Sa(o))if(i.startsWith("shielded-")&&i.endsWith(".json"))try{Vs(Zt(o,i))}catch{}}catch{}};if(e){s(Ca(e,r));return}if(!Dn(n))return;try{for(let o of Sa(n))s(Zt(n,o))}catch{}}async function Ea(e,t,r,n={}){let s=Br.ZswapSecretKeys.fromSeed(Ct(e)),o=s.coinPublicKey,i=n.forceFresh?null:vf(t,o,void 0,n.chainId),a=i?i.lastAppliedEventId+1:0,c=await wa(s,r,{initialState:i?.state,startFromId:a,onProgress:n.onProgress,signal:n.signal,timeoutMs:n.timeoutMs,onCheckpoint:(d,u)=>{try{Ks(t,o,d,u,void 0,n.chainId)}catch{}}});if(c.lastAppliedEventId>=0)Ks(t,o,c.state,c.lastAppliedEventId,void 0,n.chainId);else if(!i)Ks(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 va=2;var qs=T(()=>{Et();ya()});function xa(e={}){let t=Math.min(Math.max(e.windowMs??15000,1000),60000),r=[],n=null,s=(i)=>{let a=i-t;while(r.length>0&&r[0].t<a)r.shift()},o=()=>{let i=r[r.length-1],a=r[0],c=i.highest>0?Math.min(100,Math.round(i.applied/i.highest*100)):null,d=null,u=null;if(r.length>=2){let l=i.applied-a.applied,f=i.t-a.t;if(f>=1000&&l>0){d=l/(f/1000);let p=Math.max(0,i.highest-i.applied);u=p>0?p/d:0}}return{applied:i.applied,highest:i.highest,percent:c,ratePerSec:d,etaSec:u}};return{sample(i){return r.push(i),s(i.t),n=o(),n},snapshot(){return n},reset(){r.length=0,n=null}}}function Aa(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 ${kf(e.etaSec)}`);if(e.ratePerSec!==null&&e.ratePerSec>0)r.push(`${Math.round(e.ratePerSec)} evt/s`);return r.join(" · ")}function kf(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 Ys from"@midnightntwrk/ledger-v9";import{MidnightBech32m as Cf,UnshieldedAddress as Ef}from"@midnightntwrk/wallet-sdk/address-format";function Qt(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 jr(e){let t=e.trim(),r=/^(\d*)(?:\.(\d*))?$/.exec(t);if(!r||r[1]===""&&!r[2])throw Error(`Invalid amount: "${e}" — must be a positive number, e.g. 1.5`);let n=r[2]??"";if(n.length>zs)throw Error(`Invalid amount: "${e}" — NIGHT has ${zs} decimals, this has ${n.length}`);let s=Number(t);if(s<=0)throw Error(`Invalid amount: "${e}" — must be greater than 0`);let o=BigInt((r[1]||"0")+n.padEnd(zs,"0"));if(Qt(s)!==o)throw Error(`Invalid amount: "${e}" — too many digits to handle exactly`);return s}function xf(e,t){let r=Oe(t.networkId);try{return Cf.parse(e).decode(Ef,r)}catch(n){throw Error(`Invalid recipient address: ${n.message}
|
|
111
|
+
Expected a bech32m address for network "${t.networkId}"`)}}function _n(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 Xs(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 Pe(){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 Af(e,t,r,n){await Promise.race([e.facade.dust.waitForSyncedState(),new Promise((a,c)=>setTimeout(()=>c(Error("Insufficient funds: dust wallet sync timed out")),ds))]);let{fee:s}=await e.facade.estimateRegistration(t);await e.facade.waitForGeneratedDust(t,s,{timeoutMs:n});let o=await e.facade.registerNightUtxosForDustGeneration(t,e.keystore.getPublicKey(),e.keystore.signDataAsync,r),i;try{i=await e.facade.finalizeRecipe(o)}catch(a){try{await e.facade.revert(o)}catch{}throw a}return await e.facade.submitTransaction(i)}async function Tf(e,t,r,n){let s=Date.now(),o=s+ni,i,a=!1,c=setInterval(()=>{if(a&&n){let d=Xs(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 Af(e,t,r,o-Date.now())}catch(d){if(i=d,vn(d)&&Date.now()+ps<o){a=!0;let u=Xs(Date.now()-s);n?.(`Waiting for dust generation capacity (${u} elapsed, ~5 min on fresh wallets)...`),await new Promise((l)=>setTimeout(l,ps));continue}throw d}throw i??Error("Dust registration timed out")}finally{clearInterval(c)}}async function et(e,t,r){let n=r??await e.facade.waitForSyncedState();if(Rt(n))return t?.("Dust available"),{alreadyAvailable:!0};if(n.unshielded.availableCoins.length===0&&(n.unshielded.pendingCoins?.length??0)===0)throw Error("This wallet has no NIGHT, so it generates no Dust to pay fees. Fund it first (on undeployed: midnight airdrop <amount>), then run: midnight dust register");let s=n.unshielded.availableCoins.filter((a)=>!a.meta.registeredForDustGeneration),o;if(s.length>0)t?.(`Registering ${s.length} UTXO(s) for dust generation...`),o=await Tf(e,s,n.dust.address,t);else t?.("UTXOs already registered, waiting for dust generation...");t?.("Waiting for dust tokens...");let i=Date.now();while(Date.now()-i<ls){try{if((await Promise.race([e.facade.waitForSyncedState(),new Promise((c,d)=>setTimeout(()=>d(Error("Poll sync timed out")),ds))])).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 Nf(e,t,r,n,s,o,i){let a=Date.now(),c=a+ls,d,u=0;while(!0)try{if(d)await Os(e,"lite");let l=new Date(Date.now()+nn*60*1000);F("transfer","Building transfer transaction...");let f=await e.facade.transferTransaction([{type:"unshielded",outputs:[{amount:r,receiverAddress:t,type:Ys.unshieldedToken().raw}]}],{ttl:l,payFees:!0});F("transfer","Signing recipe...");let p=await e.facade.signRecipe(f,e.keystore.signDataAsync);F("transfer","Generating ZK proof..."),n?.();let m=await Promise.race([e.facade.finalizeRecipe(p),new Promise((S,v)=>{setTimeout(()=>v(Error("ZK proof generation timed out")),rn)})]);F("transfer","Submitting transaction to node..."),s?.();let h=Date.now(),w=i?setInterval(()=>i(Date.now()-h),1000):void 0,y;try{y=await e.facade.submitTransaction(m)}finally{if(w)clearInterval(w)}return F("transfer",`Transaction submitted: ${y}`),y}catch(l){if(d=l,(l?.code===si||l?.message?.includes("115")||l?.message?.toLowerCase().includes("stale"))&&++u<ri)continue;if(Mr(l))throw l;if(vn(l)&&Date.now()<c){let p=Xs(Date.now()-a);o?.(`Dust insufficient, re-ensuring (${p} elapsed)...`);try{let m=await Os(e,"lite"),h=m.dust.balance(new Date);if(h>0n&&h<hr)throw Error(`Insufficient dust for transaction fees.
|
|
112
|
+
Available: ${_n(h)} DUST, need ≥${_n(hr)} DUST.
|
|
107
113
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
108
|
-
Check status: midnight dust status`);await
|
|
109
|
-
Available: ${
|
|
114
|
+
Check status: midnight dust status`);await et(e,o,m)}catch(m){if(String(m?.message).startsWith("Insufficient dust"))throw m;await new Promise((h)=>setTimeout(h,5000))}continue}throw l}}async function er(e){let{seedBuffer:t,networkConfig:r,recipientAddress:n,amountNight:s,signal:o,onSync:i,onSyncDetail:a,onDust:c,onProving:d,onSubmitting:u,onSubmittingTick:l,onSyncWarning:f}=e,p=Qt(s),m=xf(n,r),h=Te(f),w=Pe();try{return await ve().withFacade(t,r,async({bundle:y,state:S})=>{if(o?.aborted)throw Error("Operation cancelled");F("transfer","Sync complete, checking balance...");let v=S.unshielded.balances[Ys.unshieldedToken().raw]??0n,A=S.unshielded.availableCoins?.length??0;if(F("transfer",`Balance: ${Number(v)/cs} NIGHT, coins: ${A}`),v<p){let ee=Number(v)/cs;throw Error(`Insufficient balance: ${ee.toFixed(6)} NIGHT available, ${s} NIGHT requested`)}let N=S.dust.balance(new Date);if(N>0n&&N<hr)throw Error(`Insufficient dust for transaction fees.
|
|
115
|
+
Available: ${_n(N)} DUST, need ≥${_n(hr)} DUST.
|
|
110
116
|
Dust regenerates over time from registered NIGHT UTXOs.
|
|
111
|
-
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(
|
|
112
|
-
`)},fail(d){if(t)return;t=!0,
|
|
117
|
+
Check status: midnight dust status`);if(o?.aborted)throw Error("Operation cancelled");if(F("transfer","Ensuring dust availability..."),await et(y,c,S),F("transfer","Dust available"),o?.aborted)throw Error("Operation cancelled");return F("transfer","Building and submitting transaction..."),{txHash:await Nf(y,m,p,d,u,c,l),amountMicroNight:p}},{syncMode:"lite",requireStrictSync:!0,signal:o,onStatus:c,onSyncProgress:i,onSyncDetail:a,onSyncWarning:f})}finally{w(),h()}}var zs=6;var _t=T(()=>{pt();He();yt();mt();Fr();Fr()});function Na(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function G(e){let t=!1;if(!Nr()){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,tr=null,process.stderr.write(`\r✓ ${d??a}\x1B[K
|
|
118
|
+
`)},fail(d){if(t)return;t=!0,tr=null,process.stderr.write(`\r✗ ${d??a}\x1B[K
|
|
113
119
|
`)},log(d){process.stderr.write(`\r\x1B[K${d}
|
|
114
|
-
`),process.stderr.write(`⠋ ${a}`)}};return
|
|
115
|
-
`)},fail(a){if(t)return;t=!0,clearInterval(o),
|
|
120
|
+
`),process.stderr.write(`⠋ ${a}`)}};return tr=c,c}let r=0,n=e,s=()=>{let a=H(Ta[r]),d=(process.stderr.columns||80)-4,u=n;if(Na(u).length>d)u=Na(u).slice(0,d);process.stderr.write(`\r${a} ${u}\x1B[K`),r=(r+1)%Ta.length};s();let o=setInterval(s,Rf),i={update(a){n=a},stop(a){if(t)return;t=!0,clearInterval(o),tr=null;let c=a??n;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${c}\x1B[K
|
|
121
|
+
`)},fail(a){if(t)return;t=!0,clearInterval(o),tr=null;let c=a??n;process.stderr.write(`\r\x1B[31m✗\x1B[0m ${c}\x1B[K
|
|
116
122
|
`)},log(a){process.stderr.write(`\r\x1B[K${a}
|
|
117
|
-
`),s()}};return
|
|
118
|
-
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}=
|
|
123
|
+
`),s()}};return tr=i,i}async function $n(e,t,r){let n=Date.now(),s=(a)=>{let c=Math.floor(a/1000),d=Math.floor(c/60).toString().padStart(2,"0"),u=(c%60).toString().padStart(2,"0");return`${d}:${u}`},o=()=>e.update(`${t} ${s(Date.now()-n)}`);o();let i=setInterval(o,1000);try{return await r}finally{clearInterval(i)}}var Ta,Rf=80,tr=null;var at=T(()=>{Ta=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var Pa={};me(Pa,{default:()=>Ia});import*as Ra from"@midnightntwrk/ledger-v9";import{MidnightBech32m as If}from"@midnightntwrk/wallet-sdk/address-format";async function Ia(e){if(e.subcommand)return Pf(e);return Da(e)}function Df(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 Pf(e){if(We(e))je();let t=e.subcommand;F("balance",`address=${t}`);let r=Df(t),n=C(e,"network");if(n&&r&&n!==r)throw Error(`Address belongs to ${r} but --network is ${n}.
|
|
124
|
+
Drop --network (we'll infer from the address) or pass an address for ${n}.`);if(!n&&r)e={...e,flags:{...e.flags,network:r}};let{name:s,config:o}=ce({args:e});if(R(e,"shielded")){let a=Ci(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 Da(c)}throw Error("Shielded balances are private — they can only be read with the wallet's secret key, "+`not from an address alone.
|
|
119
125
|
This address isn't one of your wallets. Check its shielded balance from the wallet that owns it:
|
|
120
|
-
midnight balance --wallet <name> --shielded --network ${s}`)}
|
|
121
|
-
`);else for(let[c,d]of a.balances)process.stdout.write(`${
|
|
126
|
+
midnight balance --wallet <name> --shielded --network ${s}`)}Ie(o,{proofServer:C(e,"proof-server"),node:C(e,"node"),indexerWS:C(e,"indexer-ws")},s);let i=G(`Checking balance on ${s}...`);try{let a=await ve().unshielded(t,o,{forceFresh:R(e,"no-cache"),onProgress:(c,d)=>{if(d>0){let u=Math.round(c/d*100);i.update(`Syncing transactions... ${u}%`)}}});if(i.stop(`Synced ${a.txCount} transactions`),R(e,"json")){let c={};for(let[u,l]of a.balances){let f=Pr(u)?"NIGHT":u;c[f]=Pr(u)?At(l):l.toString()}let d=c.NIGHT!==void 0?{NIGHT:c.NIGHT}:{};if(lt(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
|
|
127
|
+
`);else for(let[c,d]of a.balances)process.stdout.write(`${Pr(c)?"NIGHT":c}=${d}
|
|
122
128
|
`);if(process.stderr.write(`
|
|
123
|
-
`+
|
|
129
|
+
`+W("Balance")+`
|
|
124
130
|
|
|
125
|
-
`),process.stderr.write(
|
|
126
|
-
`),process.stderr.write(
|
|
127
|
-
`),process.stderr.write(
|
|
128
|
-
`),process.stderr.write(
|
|
131
|
+
`),process.stderr.write(E("Address",Q(t))+`
|
|
132
|
+
`),process.stderr.write(E("Network",s)+`
|
|
133
|
+
`),process.stderr.write(E("UTXOs",a.utxoCount.toString())+`
|
|
134
|
+
`),process.stderr.write(E("Transactions",a.txCount.toString())+`
|
|
129
135
|
`),process.stderr.write(`
|
|
130
136
|
`),a.balances.size===0)process.stderr.write(` ${g("No balance found")}
|
|
131
|
-
`);else for(let[c,d]of a.balances)if(
|
|
132
|
-
`);else{let
|
|
137
|
+
`);else for(let[c,d]of a.balances)if(Pr(c))process.stderr.write(E("NIGHT",P(fn(d)))+`
|
|
138
|
+
`);else{let u=c.slice(0,8)+"…"+c.slice(-8);process.stderr.write(E(`Token ${u}`,P(d.toString()))+`
|
|
133
139
|
`)}process.stderr.write(`
|
|
134
|
-
`+
|
|
140
|
+
`+K()+`
|
|
135
141
|
|
|
136
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
137
|
-
`+
|
|
142
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Da(e){if(We(e))je();let{name:t,config:r}=ce({args:e});F("balance",`network=${t} indexerWS=${r.indexerWS}`);let{seed:n,walletPath:s,config:o}=As(e);F("balance",`wallet path=${s??"(from --seed/MN_SEED)"}`);let i=o?.addresses[t]??Se(n,t),a=o?.shieldedAddresses?.[t]??"";Ie(r,{proofServer:C(e,"proof-server"),node:C(e,"node"),indexerWS:C(e,"indexer-ws")},t);let c=Te(),d=Pe(),u=R(e,"no-cache"),l=R(e,"json"),f=Ra.unshieldedToken().raw,p=null;try{if(!l){if(process.stderr.write(`
|
|
143
|
+
`+W("Balance")+`
|
|
138
144
|
|
|
139
|
-
`),process.stderr.write(
|
|
140
|
-
`),a)process.stderr.write(
|
|
141
|
-
`);process.stderr.write(
|
|
145
|
+
`),process.stderr.write(E("Address",Q(i))+`
|
|
146
|
+
`),a)process.stderr.write(E("Shielded",Q(a))+`
|
|
147
|
+
`);process.stderr.write(E("Network",t)+`
|
|
142
148
|
`),process.stderr.write(`
|
|
143
149
|
`+P("Unshielded")+`
|
|
144
|
-
`)}if(!
|
|
145
|
-
`),process.stderr.write(
|
|
150
|
+
`)}if(!l)p=G("Checking unshielded...");F("balance",`phase=unshielded forceFresh=${u}`);let m=await ve().unshielded(i,r,{forceFresh:u}),h=m.balances.get(f)??0n,w=m.utxoCount;if(F("balance",`unshielded fromCache=${m.fromCache} utxos=${w} txs=${m.txCount}`),p)if(p.stop("Unshielded ready"),p=null,h>0n)process.stderr.write(E(" NIGHT",P(fn(h)))+`
|
|
151
|
+
`),process.stderr.write(E(" UTXOs",w.toString())+`
|
|
146
152
|
`);else process.stderr.write(` ${g("No unshielded balance")}
|
|
147
|
-
`);if(!
|
|
153
|
+
`);if(!l)process.stdout.write(`NIGHT=${h}
|
|
148
154
|
`),process.stderr.write(`
|
|
149
155
|
`+P("Shielded")+`
|
|
150
|
-
`);let y=
|
|
151
|
-
`),process.stderr.write(
|
|
156
|
+
`);let y=gn(t,R(e,"force-shielded")),S=a,v=0n,A=0,N=0;if(y){if(!l)p=G("Syncing shielded...");let L=xa(),ee=Oe(r.networkId);if(S=If.encode(ee,xr(n)).asString(),s)jt(s,t,S);await Qe(t,r);let X=await qt(r.node).catch(()=>null)??void 0,V=await Ea(n,t,r.indexerWS,{forceFresh:u,chainId:X,onProgress:(O,_)=>{if(!p)return;let ne=L.sample({applied:O,highest:_,t:Date.now()});p.update(Aa(ne,"Syncing shielded"))}});if(v=V.balance,A=V.availableCoins,N=0,p)if(p.stop("Shielded ready"),p=null,v>0n)process.stderr.write(E(" NIGHT",P(fn(v)))+`
|
|
157
|
+
`),process.stderr.write(E(" Coins",`${A} available, ${N} pending`)+`
|
|
152
158
|
`);else process.stderr.write(` ${g("No shielded balance")}
|
|
153
|
-
`)}else if(!
|
|
154
|
-
`);if(
|
|
159
|
+
`)}else if(!l)process.stderr.write(` ${g("Skipped — "+hn(t))}
|
|
160
|
+
`);if(l){if(lt(e)){I({network:t,unshielded:{NIGHT:At(h),utxoCount:w},shielded:{NIGHT:At(v),availableCoins:A,pendingCoins:N},shieldedSynced:y});return}I({address:i,shieldedAddress:S,network:t,unshielded:{NIGHT:At(h),utxoCount:w},shielded:{NIGHT:At(v),availableCoins:A,pendingCoins:N},shieldedSynced:y});return}process.stdout.write(`SHIELDED_NIGHT=${y?v:"skipped"}
|
|
155
161
|
`),process.stderr.write(`
|
|
156
|
-
`+
|
|
162
|
+
`+K()+`
|
|
157
163
|
|
|
158
|
-
`)}catch(
|
|
164
|
+
`)}catch(m){throw p?.fail("Failed"),m}finally{d(),c()}}var _a=T(()=>{mt();ge();Me();Gt();Ae();ge();Ts();pt();_r();yt();qs();zt();Be();En();He();_t();ue();at()});var Oa={};me(Oa,{default:()=>$a});async function $a(e){let t=pn(e,{requireExplicit:!0,label:"address"}),r=C(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=he({args:e}),o=Se(t,s,n),i=`m/44'/2400'/0'/NightExternal/${n}`;if(R(e,"json")){I({address:o,network:s,index:n,path:i});return}process.stdout.write(o+`
|
|
159
165
|
`),process.stderr.write(`
|
|
160
|
-
`),process.stderr.write(
|
|
161
|
-
`),process.stderr.write(
|
|
162
|
-
`),process.stderr.write(
|
|
163
|
-
`),process.stderr.write(
|
|
164
|
-
`),process.stderr.write(
|
|
166
|
+
`),process.stderr.write(E("Network",s)+`
|
|
167
|
+
`),process.stderr.write(E("Index",n.toString())+`
|
|
168
|
+
`),process.stderr.write(E("Address",Q(o))+`
|
|
169
|
+
`),process.stderr.write(E("Path",g(i))+`
|
|
170
|
+
`),process.stderr.write(K()+`
|
|
165
171
|
|
|
166
|
-
`)}var
|
|
172
|
+
`)}var Ma=T(()=>{Gt();Be();Ae();ue()});var La={};me(La,{default:()=>Fa});async function Fa(e){let t=he({args:e}),r=Buffer.from(rt,"hex"),n=Se(r,t);if(R(e,"json")){I({address:n,network:t});return}process.stdout.write(n+`
|
|
167
173
|
`),process.stderr.write(`
|
|
168
|
-
`),process.stderr.write(
|
|
169
|
-
`),process.stderr.write(
|
|
170
|
-
`),process.stderr.write(
|
|
171
|
-
`),process.stderr.write(
|
|
174
|
+
`),process.stderr.write(E("Network",t)+`
|
|
175
|
+
`),process.stderr.write(E("Address",Q(n))+`
|
|
176
|
+
`),process.stderr.write(E("Seed",g("0x01 (genesis)"))+`
|
|
177
|
+
`),process.stderr.write(K()+`
|
|
172
178
|
|
|
173
|
-
`)}var
|
|
179
|
+
`)}var Ua=T(()=>{Be();Ae();ue()});var ja={};me(ja,{default:()=>Ba});import*as Wa from"@midnightntwrk/ledger-v9";function Hr(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 _f(e){return{readTime:Hr(e,"readTime",1000000000n),computeTime:Hr(e,"computeTime",1000000000n),blockUsage:Hr(e,"blockUsage",10000n),bytesWritten:Hr(e,"bytesWritten",10000n),bytesChurned:Hr(e,"bytesChurned",1000000n)}}async function Ba(e){let t=Wa.LedgerParameters.initialParameters(),r=_f(t);if(R(e,"json")){I(r);return}for(let[n,s]of Object.entries(r))process.stdout.write(`${n}=${s}
|
|
174
180
|
`);process.stderr.write(`
|
|
175
|
-
`+
|
|
181
|
+
`+W("Block Limits")+`
|
|
176
182
|
|
|
177
183
|
`),process.stderr.write(g(" Derived from LedgerParameters.initialParameters()")+`
|
|
178
184
|
|
|
179
|
-
`);for(let[n,s]of Object.entries(r)){let o
|
|
185
|
+
`);for(let[n,s]of Object.entries(r)){let o=$f[n]??"";process.stderr.write(E(n,`${P(s.toLocaleString())} ${g(o)}`)+`
|
|
180
186
|
`)}process.stderr.write(`
|
|
181
|
-
`+
|
|
187
|
+
`+K()+`
|
|
182
188
|
`),process.stderr.write(g(" bytesWritten is typically the tightest constraint")+`
|
|
183
189
|
`),process.stderr.write(g(" for large contract deployments.")+`
|
|
184
190
|
|
|
185
|
-
`)}var
|
|
191
|
+
`)}var $f;var Ha=T(()=>{ue();$f={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});var Ja={};me(Ja,{default:()=>Va});import*as Ga from"@midnightntwrk/ledger-v9";import{MidnightBech32m as Ka,ShieldedAddress as Of}from"@midnightntwrk/wallet-sdk/address-format";async function Va(e,t){Lt(e);let r=e.subcommand;if(!r)throw Error(`Missing amount.
|
|
186
192
|
Usage: midnight airdrop <amount> [--wallet <name|file|address>]
|
|
187
193
|
Example: midnight airdrop 1000
|
|
188
194
|
Example: midnight airdrop 1000 --wallet alice
|
|
189
|
-
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=
|
|
195
|
+
Example: midnight airdrop 1000 --wallet mn_addr_undeployed1...`);let n=jr(r),{name:s,config:o}=ce({args:e});if(Ie(o,{proofServer:C(e,"proof-server"),node:C(e,"node"),indexerWS:C(e,"indexer-ws")},s),s!=="undeployed")throw Error(`Airdrop is only available on the "undeployed" network (local devnet).
|
|
190
196
|
Current network: "${s}"
|
|
191
|
-
On preprod/preview, use a faucet or transfer from another wallet.`);let i=
|
|
197
|
+
On preprod/preview, use a faucet or transfer from another wallet.`);let i=C(e,"wallet"),a=R(e,"shielded")||i!==void 0&&i.startsWith("mn_shield-addr_"),c=Ff(e,s,o,a);if(a)return Wf(e,c,n,s,o,t);return Uf(e,c,n,s,o,t)}function Mf(e){return e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_")}function Ff(e,t,r,n){let s=C(e,"wallet");if(s!==void 0&&Mf(s))return Lf(s,t,r,n);let o=re(s),i=ie(o);if(n){let a=Oe(r.networkId),c=Buffer.from(i.seed,"hex"),d=xr(c),u=Ka.encode(a,d).asString();return{kind:"wallet",raw:d,bech32m:u,walletPath:o}}return{kind:"address",address:i.addresses[t]}}function Lf(e,t,r,n){let s=e.startsWith("mn_shield-addr_");if(n&&!s)throw Error(`--shielded was passed but --wallet is an unshielded address.
|
|
192
198
|
Pass a shielded address (mn_shield-addr_...) or drop --shielded.
|
|
193
|
-
Got: ${e}`);if(!n&&s)throw Error(`--wallet is a shielded address but --shielded was not passed.
|
|
194
|
-
Add --shielded, or pass an unshielded address (mn_addr_...).
|
|
195
199
|
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}".
|
|
196
200
|
Expected prefix: ${o}
|
|
197
|
-
Got: ${e}`);if(n){let i=
|
|
198
|
-
`+
|
|
201
|
+
Got: ${e}`);if(n){let i=Oe(r.networkId),a;try{a=Ka.parse(e).decode(Of,i)}catch(c){throw Error(`Invalid shielded address: ${c.message}`)}return{kind:"address",raw:a,bech32m:e}}return{kind:"address",address:e}}async function Uf(e,t,r,n,s,o){if(We(e))je();let i=t.address,a=Buffer.from(rt,"hex");process.stderr.write(`
|
|
202
|
+
`+W("Airdrop")+`
|
|
199
203
|
|
|
200
|
-
`),process.stderr.write(
|
|
201
|
-
`),process.stderr.write(
|
|
202
|
-
`),process.stderr.write(
|
|
203
|
-
`),process.stderr.write(
|
|
204
|
+
`),process.stderr.write(E("Network",n)+`
|
|
205
|
+
`),process.stderr.write(E("From",g("genesis (seed 0x01)"))+`
|
|
206
|
+
`),process.stderr.write(E("To",Q(i,!0))+`
|
|
207
|
+
`),process.stderr.write(E("Amount",P(r+" NIGHT"))+`
|
|
204
208
|
`),process.stderr.write(`
|
|
205
|
-
`);let c=
|
|
209
|
+
`);let c=G("Starting genesis wallet...");try{let d=await er({seedBuffer:a,networkConfig:s,recipientAddress:i,amountNight:r,signal:o,onSync(u,l){if(l>0){let f=Math.round(u/l*100);c.update(`Syncing genesis wallet... ${f}%`)}},onDust(u){c.update(`Dust: ${u}`)},onProving(){c.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){c.update("Submitting and waiting for finalization (typically 12 to 30s)...")},onSubmittingTick(u){let l=Math.floor(u/1000),f=Math.floor(l/60).toString().padStart(2,"0"),p=(l%60).toString().padStart(2,"0");c.update(`Submitting and waiting for finalization... ${f}:${p} elapsed (typically 12 to 30s)`)},onSyncWarning(u,l){c.update(`Syncing genesis wallet... (${l}, retrying)`)}});if(c.stop("Transaction submitted"),R(e,"json")){I({txHash:d.txHash,amount:r,recipient:i,network:n});return}process.stdout.write(d.txHash+`
|
|
206
210
|
`),process.stderr.write(`
|
|
207
|
-
`+
|
|
211
|
+
`+ft(`Airdropped ${r} NIGHT to your wallet`,d.txHash)+`
|
|
208
212
|
`),process.stderr.write(`
|
|
209
|
-
`+
|
|
213
|
+
`+K()+`
|
|
210
214
|
`),process.stderr.write(g(" Verify: midnight balance")+`
|
|
211
215
|
`),process.stderr.write(g(" Register dust: midnight dust register")+`
|
|
212
216
|
`),process.stderr.write(g(" Note: Dust generation takes a few minutes on a fresh wallet.")+`
|
|
@@ -215,128 +219,128 @@ Got: ${e}`);if(n){let i=vt(r.networkId),a;try{a=Ra.parse(e).decode(Yp,i)}catch(c
|
|
|
215
219
|
`)}catch(d){if(c.fail("Failed"),d instanceof Error&&d.message.toLowerCase().includes("dust"))throw Error(`${d.message}
|
|
216
220
|
|
|
217
221
|
On a fresh localnet, the minimum airdrop is ~1 NIGHT.
|
|
218
|
-
Try: midnight airdrop 1`);throw d}}async function
|
|
219
|
-
`+
|
|
222
|
+
Try: midnight airdrop 1`);throw d}}async function Wf(e,t,r,n,s,o){let i=Qt(r);if(We(e))je();let a=Buffer.from(rt,"hex"),c=Ga.unshieldedToken().raw,{raw:d,bech32m:u}=t;if(t.kind==="wallet")jt(t.walletPath,n,u);process.stderr.write(`
|
|
223
|
+
`+W("Shielded Airdrop")+`
|
|
220
224
|
|
|
221
|
-
`),process.stderr.write(
|
|
222
|
-
`),process.stderr.write(
|
|
223
|
-
`),process.stderr.write(
|
|
224
|
-
`),process.stderr.write(
|
|
225
|
+
`),process.stderr.write(E("Network",n)+`
|
|
226
|
+
`),process.stderr.write(E("From",g("genesis shielded (seed 0x01)"))+`
|
|
227
|
+
`),process.stderr.write(E("To",Q(u,!0))+`
|
|
228
|
+
`),process.stderr.write(E("Amount",P(r+" NIGHT (shielded)"))+`
|
|
225
229
|
`),process.stderr.write(`
|
|
226
|
-
`);let
|
|
230
|
+
`);let l=Te(),f=Pe(),p=G("Syncing genesis wallet...");try{let m=await ve().withFacade(a,s,async({bundle:h,state:w})=>{let y=w.shielded.balances[c]??0n;if(y<i){let L=Number(y)/1e6;throw Error(`Genesis wallet has insufficient shielded balance: ${L.toFixed(6)} NIGHT available, ${r} NIGHT requested`)}if(p.update("Checking dust..."),await et(h,(L)=>p.update(L)),o?.aborted)throw Error("Operation cancelled");p.update("Building shielded transaction...");let S=await h.facade.transferTransaction([{type:"shielded",outputs:[{type:c,amount:i,receiverAddress:d}]}],{ttl:new Date(Date.now()+3600000)});p.update("Signing...");let v=await h.facade.signRecipe(S,h.keystore.signDataAsync);p.update("Generating ZK proof (this may take a few minutes)...");let A=await h.facade.finalizeRecipe(v),N=await $n(p,"Submitting and waiting for finalization (typically 12 to 30s)...",h.facade.submitTransaction(A));return String(N)},{syncMode:"full",requireStrictSync:!0,signal:o,onStatus:(h)=>p.update(h),onSyncProgress:(h,w)=>{if(w>0){let y=Math.min(Math.round(h/w*100),100);p.update(y>=100?"Syncing genesis wallet...":`Syncing genesis wallet... ${y}%`)}},onSyncDetail:(h)=>p.update(`Syncing genesis wallet... (waiting on: ${h})`)});if(p.stop("Transaction submitted"),R(e,"json")){I({txHash:m,amount:r,shieldedAddress:u,network:n,type:"shielded"});return}process.stdout.write(m+`
|
|
227
231
|
`),process.stderr.write(`
|
|
228
|
-
`+
|
|
232
|
+
`+ft(`Airdropped ${r} shielded NIGHT to your wallet`,m)+`
|
|
229
233
|
`),process.stderr.write(`
|
|
230
|
-
`+
|
|
234
|
+
`+K()+`
|
|
231
235
|
`),process.stderr.write(g(" Verify: midnight balance --shielded")+`
|
|
232
236
|
|
|
233
|
-
`)}catch(
|
|
237
|
+
`)}catch(m){throw p.fail("Failed"),m}finally{f(),l()}}var qa=T(()=>{mt();Me();Ae();ge();pt();Be();_t();He();yt();ue();at()});var Za={};me(Za,{default:()=>Ya});import*as Xa from"@midnightntwrk/ledger-v9";import{MidnightBech32m as za,ShieldedAddress as Bf}from"@midnightntwrk/wallet-sdk/address-format";async function Ya(e,t){Lt(e);let r=e.subcommand,n=e.positionals[0];if(!r)throw Error(`Missing recipient address.
|
|
234
238
|
Usage: midnight transfer <to> <amount>
|
|
235
239
|
Example: midnight transfer mn_addr_undeployed1... 100
|
|
236
240
|
Example: midnight transfer alice 100`);if(!n)throw Error(`Missing amount.
|
|
237
241
|
Usage: midnight transfer <to> <amount>
|
|
238
|
-
Example: midnight transfer mn_addr_undeployed1... 100`);let s=
|
|
239
|
-
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function
|
|
240
|
-
`+
|
|
241
|
-
|
|
242
|
-
`),process.stderr.write(
|
|
243
|
-
`),process.stderr.write(
|
|
244
|
-
`),process.stderr.write(
|
|
245
|
-
`),process.stderr.write(
|
|
242
|
+
Example: midnight transfer mn_addr_undeployed1... 100`);let s=R(e,"shielded"),o=jf(r,e,s);if(s)return Gf(e,o,n,t);return Hf(e,o,n,t)}function jf(e,t,r){if(e.startsWith("mn_addr_")||e.startsWith("mn_shield-addr_"))return e;let n=re(e),s=ie(n),o=he({args:t});if(r){let i=s.shieldedAddresses?.[o];if(!i)throw Error(`Wallet "${e}" has no shielded address for network "${o}".
|
|
243
|
+
Regenerate the wallet or run "midnight balance --shielded" first.`);return i}return s.addresses[o]}async function Hf(e,t,r,n){let s=jr(r),o=re(C(e,"wallet")),i=ie(o),a=Buffer.from(i.seed,"hex"),{name:c,config:d}=ce({args:e}),u=i.addresses[c];if(Ie(d,{proofServer:C(e,"proof-server"),node:C(e,"node"),indexerWS:C(e,"indexer-ws")},c),process.stderr.write(`
|
|
244
|
+
`+W("Transfer")+`
|
|
245
|
+
|
|
246
|
+
`),process.stderr.write(E("Network",c)+`
|
|
247
|
+
`),process.stderr.write(E("From",Q(u,!0))+`
|
|
248
|
+
`),process.stderr.write(E("To",Q(t,!0))+`
|
|
249
|
+
`),process.stderr.write(E("Amount",P(s+" NIGHT"))+`
|
|
246
250
|
`),process.stderr.write(`
|
|
247
|
-
`),
|
|
251
|
+
`),We(e))je();let l=G("Starting wallet...");try{let f=await er({seedBuffer:a,networkConfig:d,recipientAddress:t,amountNight:s,signal:n,onSync(p,m){if(m>0){let h=Math.min(Math.round(p/m*100),100);l.update(h>=100?"Syncing wallet...":`Syncing wallet... ${h}%`)}},onSyncDetail(p){l.update(`Syncing wallet... (waiting on: ${p})`)},onDust(p){l.update(`Dust: ${p}`)},onProving(){l.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){l.update("Submitting and waiting for finalization (typically 12 to 30s)...")},onSubmittingTick(p){let m=Math.floor(p/1000),h=Math.floor(m/60).toString().padStart(2,"0"),w=(m%60).toString().padStart(2,"0");l.update(`Submitting and waiting for finalization... ${h}:${w} elapsed (typically 12 to 30s)`)},onSyncWarning(p,m){l.update(`Syncing wallet... (${m}, retrying)`)}});if(l.stop("Transaction submitted"),R(e,"json")){I({txHash:f.txHash,amount:s,recipient:t,network:c});return}process.stdout.write(f.txHash+`
|
|
248
252
|
`),process.stderr.write(`
|
|
249
|
-
`+
|
|
253
|
+
`+ft(`Transferred ${s} NIGHT`,f.txHash)+`
|
|
250
254
|
`),process.stderr.write(`
|
|
251
|
-
`+
|
|
255
|
+
`+K()+`
|
|
252
256
|
`),process.stderr.write(g(" Verify: midnight balance")+`
|
|
253
257
|
|
|
254
|
-
`)}catch(
|
|
255
|
-
Expected a shielded address (mn_shield-addr_...) for network "${
|
|
256
|
-
`+
|
|
258
|
+
`)}catch(f){throw l.fail("Failed"),f}}async function Gf(e,t,r,n){let s=jr(r),o=Qt(s),i=re(C(e,"wallet")),a=ie(i),c=Buffer.from(a.seed,"hex"),{name:d,config:u}=ce({args:e});if(!gn(d,R(e,"force-shielded")))throw Error(hn(d));let l=a.addresses[d],f=Oe(u.networkId),p=Xa.unshieldedToken().raw;Ie(u,{proofServer:C(e,"proof-server"),node:C(e,"node"),indexerWS:C(e,"indexer-ws")},d);let m;try{m=za.parse(t).decode(Bf,f)}catch(S){throw Error(`Invalid shielded address: ${S.message}
|
|
259
|
+
Expected a shielded address (mn_shield-addr_...) for network "${u.networkId}"`)}if(process.stderr.write(`
|
|
260
|
+
`+W("Shielded Transfer")+`
|
|
257
261
|
|
|
258
|
-
`),process.stderr.write(
|
|
259
|
-
`),process.stderr.write(
|
|
260
|
-
`),process.stderr.write(
|
|
262
|
+
`),process.stderr.write(E("Network",d)+`
|
|
263
|
+
`),process.stderr.write(E("To",Q(t,!0))+`
|
|
264
|
+
`),process.stderr.write(E("Amount",P(s+" NIGHT (shielded)"))+`
|
|
261
265
|
`),process.stderr.write(`
|
|
262
|
-
`),
|
|
263
|
-
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(y.update("Checking dust..."),await
|
|
266
|
+
`),We(e))je();let h=Te(),w=Pe(),y=G("Syncing wallet...");try{let S=await ve().withFacade(c,u,async({bundle:v,state:A})=>{let N=za.encode(f,A.shielded.address).asString();jt(i,d,N);let L=A.shielded.balances[p]??0n;if(L<o){let _=Number(L)/1e6;throw Error(`Insufficient shielded balance: ${_.toFixed(6)} NIGHT available, ${s} NIGHT requested.
|
|
267
|
+
Fund shielded balance: midnight airdrop ${s} --shielded`)}if(y.update("Checking dust..."),await et(v,(_)=>y.update(_)),n?.aborted)throw Error("Operation cancelled");y.update("Building shielded transaction...");let ee=await v.facade.transferTransaction([{type:"shielded",outputs:[{type:p,amount:o,receiverAddress:m}]}],{ttl:new Date(Date.now()+3600000)});y.update("Signing...");let X=await v.facade.signRecipe(ee,v.keystore.signDataAsync);y.update("Generating ZK proof (this may take a few minutes)...");let V=await v.facade.finalizeRecipe(X),O=await $n(y,"Submitting and waiting for finalization (typically 12 to 30s)...",v.facade.submitTransaction(V));return String(O)},{syncMode:"full",requireStrictSync:!0,signal:n,onStatus:(v)=>y.update(v),onSyncProgress:(v,A)=>{if(A>0){let N=Math.min(Math.round(v/A*100),100);y.update(N>=100?"Syncing wallet...":`Syncing wallet... ${N}%`)}},onSyncDetail:(v)=>y.update(`Syncing wallet... (waiting on: ${v})`)});if(y.stop("Transaction submitted"),R(e,"json")){I({txHash:S,amount:s,recipient:t,network:d,type:"shielded"});return}process.stdout.write(S+`
|
|
264
268
|
`),process.stderr.write(`
|
|
265
|
-
`+
|
|
269
|
+
`+ft(`Transferred ${s} shielded NIGHT`,S)+`
|
|
266
270
|
`),process.stderr.write(`
|
|
267
|
-
`+
|
|
271
|
+
`+K()+`
|
|
268
272
|
`),process.stderr.write(g(" Verify: midnight balance --shielded")+`
|
|
269
273
|
|
|
270
|
-
`)}catch(S){throw y.fail("Failed"),S}finally{w(),
|
|
274
|
+
`)}catch(S){throw y.fail("Failed"),S}finally{w(),h()}}var Qa=T(()=>{mt();Me();Ae();ge();Ts();pt();_t();He();yt();ue();at()});async function Kf(e,t){let r=await Ye(e,t,null);try{return await r.facade.dust.serializeState()}finally{await Fe(r)}}async function ec(e,t,r,n={}){let s=Xe(e),i=await(n.repository??ve()).dust(e,r,{signal:n.signal,onProgress:n.onProgress}),a=await(n.buildBaseDust??Kf)(e,r),c=i.lastAppliedEventId>=0?$s(a,{state:i.state,lastAppliedEventId:i.lastAppliedEventId}):a;return{network:t,dustPublicKey:s,offset:i.lastAppliedEventId,balance:i.balance,eventCount:i.eventsApplied,fromCache:i.fromCache,partial:i.partial,snapshot:c}}var tc=T(()=>{Nt();He();yt()});var nc={};me(nc,{default:()=>rc});async function rc(e,t){let r=e.subcommand;if(!r||r!=="register"&&r!=="status"&&r!=="export")throw new q(`Missing or invalid subcommand.
|
|
271
275
|
Usage:
|
|
272
276
|
midnight dust register Register NIGHT UTXOs for dust generation
|
|
273
277
|
midnight dust status Check dust registration status
|
|
274
|
-
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=
|
|
278
|
+
midnight dust export Export a restorable dust snapshot (dustSerializedState)`);let{name:n,config:s}=ce({args:e});if(Ie(s,{proofServer:C(e,"proof-server"),node:C(e,"node"),indexerWS:C(e,"indexer-ws")},n),We(e))je();let o=R(e,"json"),i=lt(e);if(r==="export"){await Vf(pn(e),n,s,o,i,t);return}let a=ie(re(C(e,"wallet"))),c=Buffer.from(a.seed,"hex"),d=a.addresses[n];if(r==="status"){let p=await Jf(d,n,s.indexerWS,t);if(!p.isRegistered){qf(n,p,o,i);return}let m=!R(e,"no-cache");await Xf(c,s,p,o,i,m,t);return}Lt(e);let u={},l=Te((p,m)=>u.current?.(p,m)),f=Pe();try{await zf(c,s,o,t,u)}finally{f(),l()}}async function Vf(e,t,r,n,s,o){let i=G(`Reading dust events from ${t}...`);try{let a=await ec(e,t,r,{signal:o,onProgress:(c,d)=>i.update(d>0?`Reading dust events... ${c}/${d+1}`:`Reading dust events... ${c}`)});if(i.stop(a.partial?"Dust snapshot ready (incomplete)":a.fromCache&&a.eventCount===0?"Cache up to date":"Dust snapshot ready"),n){I({subcommand:"export",network:a.network,dustPublicKey:a.dustPublicKey,offset:a.offset,dustBalance:Ue(a.balance),eventCount:a.eventCount,fromCache:a.fromCache,partial:a.partial,snapshot:a.snapshot});return}if(process.stdout.write(a.snapshot+`
|
|
275
279
|
`),s)return;if(process.stderr.write(`
|
|
276
|
-
`+
|
|
277
|
-
`),process.stderr.write(
|
|
278
|
-
`),process.stderr.write(
|
|
280
|
+
`+E("Network",a.network)+`
|
|
281
|
+
`),process.stderr.write(E("Dust balance",Dr(a.balance))+`
|
|
282
|
+
`),process.stderr.write(E("Snapshot offset",String(a.offset))+`
|
|
279
283
|
`),a.partial)process.stderr.write(`
|
|
280
|
-
`+
|
|
284
|
+
`+Y(P("⚠ Snapshot is INCOMPLETE — the sync did not reach the chain tip."))+`
|
|
281
285
|
`+g(" Restoring it still beats a cold start, but the wallet has events left to catch up on.")+`
|
|
282
286
|
`+g(" Re-run `mn dust export` to resume from this checkpoint and finish.")+`
|
|
283
287
|
`);process.stderr.write(`
|
|
284
288
|
`+g("Restore with the wallet SDK dustSerializedState to skip the cold dust sync.")+`
|
|
285
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
286
|
-
`+
|
|
289
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Jf(e,t,r,n){process.stderr.write(`
|
|
290
|
+
`+W("Dust Status")+`
|
|
287
291
|
|
|
288
|
-
`),process.stderr.write(
|
|
292
|
+
`),process.stderr.write(E("Network",t)+`
|
|
289
293
|
|
|
290
|
-
`);let s=
|
|
294
|
+
`);let s=G(`Checking registration on ${t}...`);try{let o=await Vt(e,r,(c,d)=>{if(d>0){let u=Math.min(Math.round(c/d*100),100);s.update(u>=100?"Checking registration...":`Checking registration... ${u}%`)}});if(n?.aborted)throw Error("Operation cancelled");let{registeredUtxos:i,unregisteredUtxos:a}=o;return s.stop("Registration checked"),{isRegistered:i>0,registeredUtxos:i,unregisteredUtxos:a}}catch(o){throw s.fail("Failed"),o}}function qf(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
|
|
291
295
|
`),process.stdout.write(`registered_utxos=${s}
|
|
292
296
|
`),process.stdout.write(`unregistered_utxos=${o}
|
|
293
|
-
`),process.stderr.write(
|
|
294
|
-
`),process.stderr.write(
|
|
297
|
+
`),process.stderr.write(E("Registered",P("no"))+`
|
|
298
|
+
`),process.stderr.write(E("UTXOs",`${s} registered, ${o} unregistered`)+`
|
|
295
299
|
`),i===0)process.stderr.write(`
|
|
296
300
|
`+g("No NIGHT UTXOs at this address. Fund the wallet first.")+`
|
|
297
301
|
`);else process.stderr.write(`
|
|
298
302
|
`+g("Not generating dust. Run: midnight dust register")+`
|
|
299
303
|
`);process.stderr.write(`
|
|
300
|
-
`+
|
|
304
|
+
`+K()+`
|
|
301
305
|
|
|
302
|
-
`)}async function
|
|
303
|
-
`+
|
|
306
|
+
`)}async function zf(e,t,r,n,s){let o=t.networkId.toLowerCase();process.stderr.write(`
|
|
307
|
+
`+W("Dust Register")+`
|
|
304
308
|
|
|
305
|
-
`),process.stderr.write(
|
|
309
|
+
`),process.stderr.write(E("Network",o)+`
|
|
306
310
|
|
|
307
|
-
`);let i=
|
|
311
|
+
`);let i=G("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:u})=>{if(n?.aborted)throw Error("Operation cancelled");i.update("Checking dust status...");let l=await et(d,(p)=>i.update(p),u);if(n?.aborted)throw Error("Operation cancelled");let f=await zi(d);return{result:l,dustBal:f.dust.balance(new Date)}},{syncMode:"lite",requireStrictSync:!0,signal:n,onStatus:(d)=>i.update(d),onSyncProgress:(d,u)=>{if(u>0){let l=Math.min(Math.round(d/u*100),100);i.update(l>=100?"Syncing wallet...":`Syncing wallet... ${l}%`)}},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:Ue(c)};if(a.txHash)d.txHash=a.txHash;I(d);return}process.stdout.write(c.toString()+`
|
|
308
312
|
`),process.stderr.write(`
|
|
309
|
-
`+
|
|
313
|
+
`+ft(a.alreadyAvailable?`Dust tokens already available: ${Dr(c)}`:`Dust tokens available: ${Dr(c)}`)+`
|
|
310
314
|
|
|
311
|
-
`)}catch(a){throw i.fail("Failed"),a}}async function
|
|
315
|
+
`)}catch(a){throw i.fail("Failed"),a}}async function Xf(e,t,r,n,s,o,i){let a=t.networkId.toLowerCase(),c=G(`Reading dust events from ${a}...`);try{let d=await ve().dust(e,t,{forceFresh:!o,signal:i,onStatus:(f)=>c.update(f)});c.stop(d.fromCache&&d.eventsApplied===0?"Cache up to date":"Dust events applied");let{registeredUtxos:u,unregisteredUtxos:l}=r;if(n){if(s){I({network:a,registered:!0,registeredUtxos:u,unregisteredUtxos:l,dustBalance:Ue(d.balance),dustAvailable:d.availableCoins>0});return}I({subcommand:"status",registered:!0,registeredUtxos:u,unregisteredUtxos:l,dustBalance:Ue(d.balance),dustAvailable:d.availableCoins>0,eventsApplied:d.eventsApplied,ownedUtxos:d.ownedUtxoCount,cached:d.fromCache,network:a});return}if(process.stdout.write(`registered=yes
|
|
312
316
|
`),process.stdout.write(`dust=${d.balance}
|
|
313
|
-
`),process.stdout.write(`registered_utxos=${
|
|
314
|
-
`),process.stdout.write(`unregistered_utxos=${
|
|
315
|
-
`),process.stderr.write(
|
|
316
|
-
`),process.stderr.write(
|
|
317
|
-
`),process.stderr.write(
|
|
318
|
-
`),process.stderr.write(
|
|
319
|
-
`),process.stderr.write(
|
|
320
|
-
`),
|
|
321
|
-
`+g(`${
|
|
317
|
+
`),process.stdout.write(`registered_utxos=${u}
|
|
318
|
+
`),process.stdout.write(`unregistered_utxos=${l}
|
|
319
|
+
`),process.stderr.write(E("Registered",P("yes"))+`
|
|
320
|
+
`),process.stderr.write(E("UTXOs",`${u} registered, ${l} unregistered`)+`
|
|
321
|
+
`),process.stderr.write(E("Dust Balance",P(Dr(d.balance)))+`
|
|
322
|
+
`),process.stderr.write(E("Dust Available",d.availableCoins>0?"yes":"no")+`
|
|
323
|
+
`),process.stderr.write(E("Events applied",d.eventsApplied.toString()+(d.fromCache?" (delta)":""))+`
|
|
324
|
+
`),l>0)process.stderr.write(`
|
|
325
|
+
`+g(`${l} UTXO(s) not yet registered. Run: midnight dust register`)+`
|
|
322
326
|
`);process.stderr.write(`
|
|
323
|
-
`+
|
|
324
|
-
|
|
325
|
-
`)}catch(d){throw c.fail("Failed"),d}}var
|
|
326
|
-
`)}else if(n){if(
|
|
327
|
-
`)}else{if(
|
|
328
|
-
`)}}var
|
|
329
|
-
Valid keys: ${
|
|
330
|
-
Valid keys: ${
|
|
331
|
-
`)}else if(t==="unset"){
|
|
332
|
-
`)}else{let n=e.positionals[1];if(n===void 0)throw new
|
|
333
|
-
Usage: midnight config set ${r} <value>`);if(
|
|
334
|
-
`)}}var
|
|
327
|
+
`+K()+`
|
|
328
|
+
|
|
329
|
+
`)}catch(d){throw c.fail("Failed"),d}}var sc=T(()=>{ze();mt();Me();Gt();Ae();ge();He();_t();_r();tc();yt();ue();at()});var ic={};me(ic,{default:()=>oc});async function oc(e){if(e.subcommand!=="clear")throw new q("Usage: midnight cache clear [--network <name>] [--wallet <name|file>]");let r=C(e,"wallet"),n=C(e,"network"),s=R(e,"json");if(r){let o=re(r),i=ie(o),a=he({args:e}),c=i.addresses[a];Ge(c,a);let d=Xe(Buffer.from(i.seed,"hex"));gt(a,d),Rn(a,d);let u=ka(Buffer.from(i.seed,"hex"));if(Pn(a,u),s){I({action:"clear",scope:"wallet",wallet:r,network:a});return}process.stderr.write(U("✓")+` Cache cleared for wallet "${r}" on ${a}
|
|
330
|
+
`)}else if(n){if(Ge(void 0,n),gt(n),Rn(n),Pn(n),s){I({action:"clear",scope:"network",network:n});return}process.stderr.write(U("✓")+` Cache cleared for network "${n}"
|
|
331
|
+
`)}else{if(Ge(),gt(),Rn(),Pn(),s){I({action:"clear",scope:"all"});return}process.stderr.write(U("✓")+` Cache cleared
|
|
332
|
+
`)}}var ac=T(()=>{ze();It();Nt();qs();Hs();Me();Ae()});var dc={};me(dc,{default:()=>cc});async function cc(e){let t=e.subcommand;if(!t||!["get","set","unset"].includes(t))throw new q(`Usage: midnight config <get|set|unset> <key> [value]
|
|
333
|
+
Valid keys: ${Ss().join(", ")}`);let r=e.positionals[0];if(!r)throw new q(`Missing config key.
|
|
334
|
+
Valid keys: ${Ss().join(", ")}`);if(t==="get"){let n=pi(r);if(R(e,"json")){I({action:"get",key:r,value:n});return}process.stdout.write(n+`
|
|
335
|
+
`)}else if(t==="unset"){mi(r);let n=r==="network"?"(default)":"(removed)";if(R(e,"json")){I({action:"unset",key:r,value:n});return}process.stderr.write(U("✓")+` ${r} ${n}
|
|
336
|
+
`)}else{let n=e.positionals[1];if(n===void 0)throw new q(`Missing value for config set.
|
|
337
|
+
Usage: midnight config set ${r} <value>`);if(fi(r,n),R(e,"json")){I({action:"set",key:r,value:n});return}process.stderr.write(U("✓")+` ${r} = ${n}
|
|
338
|
+
`)}}var lc=T(()=>{ze();Wt()});import{execSync as Gr}from"child_process";import{existsSync as uc,mkdirSync as Yf,readFileSync as Zf,writeFileSync as pc}from"fs";import{homedir as Qf}from"os";import{join as Qs}from"path";function mc(){try{return Gr("docker compose version",{...Mn,timeout:1e4}).trim()}catch{try{throw Gr("docker --version",{...Mn,timeout:5000}),Error(`Docker Compose v2 is required.
|
|
335
339
|
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.
|
|
336
|
-
Install Docker from https://docs.docker.com/get-docker/`)}}}function
|
|
337
|
-
`),r=[];for(let n of t){if(!n.trim())continue;try{let s=JSON.parse(n),o=s.Service??"unknown";r.push({name:o,state:s.State??"unknown",health:s.Health??"",port:
|
|
340
|
+
Install Docker from https://docs.docker.com/get-docker/`)}}}function hc(){if(!sm)throw new gc;if(uc(Zs)&&uc(On)&&Zf(Zs,"utf-8").trim()===fc)return!1;return Yf(eo,{recursive:!0,mode:Ee}),pc(On,nm,"utf-8"),pc(Zs,fc,"utf-8"),!0}function rr(e){return Gr(`docker compose -f "${On}" ${e}`,Mn)}function Fn(){try{let e=rr("ps --format json");if(!e.trim())return[];let t=e.trim().split(`
|
|
341
|
+
`),r=[];for(let n of t){if(!n.trim())continue;try{let s=JSON.parse(n),o=s.Service??"unknown";r.push({name:o,state:s.State??"unknown",health:s.Health??"",port:om[o]??"",image:s.Image??""})}catch{}}return r}catch{return[]}}function wc(e=120000,t=3000){let r=Date.now()+e;while(Date.now()<r){let n=Fn();if(n.length===3&&n.every((o)=>o.state==="running")){if(n.every((i)=>i.health==="healthy"||i.health===""))return!0}Gr(`sleep ${t/1000}`,{timeout:t+1000})}return!1}function to(){return On}function yc(){let e=[];for(let t of im)try{Gr(`docker rm -f "${t}"`,{...Mn,timeout:1e4}),e.push(t)}catch{}return e}var fc="3.0.6",em="midnightntwrk/midnight-node:1.0.0",tm="midnightntwrk/indexer-standalone:4.3.3",rm="midnightntwrk/proof-server:8.1.0",eo,On,Zs,nm,Mn,sm=!1,gc,om,im;var Sc=T(()=>{eo=Qs(Qf(),oe,ii),On=Qs(eo,"compose.yml"),Zs=Qs(eo,".version"),nm=`services:
|
|
338
342
|
proof-server:
|
|
339
|
-
image: '${
|
|
343
|
+
image: '${rm}'
|
|
340
344
|
container_name: "proof-server"
|
|
341
345
|
# Self-heal across Docker Desktop restarts and transient stops. Without this,
|
|
342
346
|
# a stopped node/proof-server never comes back while the indexer (below) does,
|
|
@@ -347,7 +351,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function Fn(){if(qa(
|
|
|
347
351
|
- "6300:6300"
|
|
348
352
|
|
|
349
353
|
indexer:
|
|
350
|
-
image: '${
|
|
354
|
+
image: '${tm}'
|
|
351
355
|
container_name: "indexer"
|
|
352
356
|
# unless-stopped covers two cases: (1) indexer >=4.3.x runs an SPO sub-indexer
|
|
353
357
|
# that queries block #1 at startup and exits the whole process if it isn't there
|
|
@@ -383,7 +387,7 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function Fn(){if(qa(
|
|
|
383
387
|
condition: service_started
|
|
384
388
|
|
|
385
389
|
node:
|
|
386
|
-
image: '${
|
|
390
|
+
image: '${em}'
|
|
387
391
|
container_name: "node"
|
|
388
392
|
# Self-heal across Docker Desktop restarts / transient stops (see proof-server).
|
|
389
393
|
restart: unless-stopped
|
|
@@ -397,174 +401,183 @@ Install Docker from https://docs.docker.com/get-docker/`)}}}function Fn(){if(qa(
|
|
|
397
401
|
start_period: 5s
|
|
398
402
|
environment:
|
|
399
403
|
CFG_PRESET: "dev"
|
|
400
|
-
`,
|
|
401
|
-
|
|
402
|
-
|
|
404
|
+
`,Mn={encoding:"utf-8",timeout:30000};gc=class gc extends Error{code="LOCALNET_UNAVAILABLE";constructor(){super(`mn localnet can't start a ledger-9 network yet: no published indexer image runs ledger 9.
|
|
405
|
+
Run a ledger-9 stack yourself (node 2.1.0-rc.2, proof-server 9.0.0-rc.8, a 4.4 indexer) and point mn at it:
|
|
406
|
+
per command: --node ws://localhost:9944 --indexer-ws ws://localhost:8088/api/v4/graphql/ws --proof-server http://localhost:6300
|
|
407
|
+
or once: midnight config set node <url>; midnight config set indexer-ws <url>; midnight config set proof-server <url>`);this.name="LocalnetUnavailableError"}};om={node:"9944",indexer:"8088","proof-server":"6300"};im=["node","indexer","proof-server"]});async function bc(e,t={}){let r=t.timeoutMs??30000,n=t.pollIntervalMs??1000,s=Date.now()+r;while(Date.now()<s){try{let o=await Jt({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 vc=T(()=>{Cn()});async function kc(e,t,r={}){let n=r.timeoutMs??30000,s=r.pollIntervalMs??1000,o=Date.now()+n;while(Date.now()<o){try{if((await Vt(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 Cc=T(()=>{_r()});async function Ec(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 Rc={};me(Rc,{default:()=>Nc});import{spawn as xc}from"child_process";import{existsSync as am,rmSync as cm}from"node:fs";import{resolve as dm}from"node:path";function lm(e){return Ac.includes(e)}function Tc(e){let t=[];for(let r of e){let n=r.state==="running"?U:ae,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(`
|
|
408
|
+
`)}async function um(e){if(hc())process.stderr.write(g(` Wrote compose.yml to ${to()}`)+`
|
|
409
|
+
`);let r=G("Starting local network...");try{if(rr("up -d"),r.update("Waiting for services to be healthy..."),!wc(120000))r.stop(Y("Services started but not all healthy yet")),process.stderr.write(`
|
|
403
410
|
`+g(" Tip: run ")+P("midnight localnet logs")+g(" to check for errors")+`
|
|
404
|
-
`);else{r.update("Waiting for chain to produce first block...");try{
|
|
411
|
+
`);else{r.update("Waiting for chain to produce first block...");try{await Promise.resolve().then(() => vc());await Promise.resolve().then(() => Cc());await Promise.resolve();await Promise.resolve().then(() => ge());await Promise.resolve().then(() => Be());await Promise.resolve();let l=kr("undeployed");await bc(l.node,{timeoutMs:30000}),r.update("Waiting for indexer to ingest genesis state...");let f=Se(Buffer.from(rt,"hex"),"undeployed");await kc(l.indexerWS,f,{timeoutMs:30000}),r.update("Waiting for proof server..."),await Ec(l.proofServer,{timeoutMs:30000}),r.stop("Local network is running")}catch(o){r.stop(Y("Services running but chain/indexer/proof-server not fully ready yet")),process.stderr.write(`
|
|
405
412
|
`+g(" Tip: give it a few more seconds then retry. Run ")+P("midnight localnet logs")+g(" if this persists.")+`
|
|
406
413
|
`)}}}catch(s){if(r.fail("Failed to start local network"),s instanceof Error){if(s.message.includes("is already in use by container"))throw Error(`Container name conflict — containers with the same names already exist
|
|
407
414
|
`+`(likely from a previous midnight-local-network setup).
|
|
408
415
|
|
|
409
416
|
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.
|
|
410
|
-
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=
|
|
411
|
-
`+
|
|
417
|
+
`+"Check ports 9944, 8088, and 6300, then try again.")}throw s}let n=Fn();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(`
|
|
418
|
+
`+Tc(n)+`
|
|
412
419
|
`);for(let s of n)process.stdout.write(`${s.name}=${s.state}:${s.port}
|
|
413
420
|
`);process.stderr.write(`
|
|
414
421
|
`+g(" Next: ")+P("midnight wallet generate dev --network undeployed")+`
|
|
415
|
-
`)}async function
|
|
416
|
-
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function
|
|
417
|
-
`+
|
|
422
|
+
`)}async function pm(e){let t=G("Stopping local network...");try{if(rr("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 fm(e){let t=G("Tearing down local network...");try{rr("down --volumes");await Promise.resolve().then(() => It());await Promise.resolve().then(() => Nt());Ge(void 0,"undeployed"),gt("undeployed");let s=mm();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)")+`
|
|
423
|
+
`)}catch(r){throw t.fail("Failed to tear down local network"),r}}function mm(){let e=dm(process.cwd(),"midnight-level-db");if(!am(e))return!1;try{return cm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function gm(e){let t=Fn();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(`
|
|
424
|
+
`+W("Localnet Status")+`
|
|
418
425
|
|
|
419
426
|
`),process.stderr.write(g(" No services running.")+`
|
|
420
|
-
`),process.stderr.write(g("
|
|
427
|
+
`),process.stderr.write(g(" ")+P("midnight localnet up")+g(" is refused on this ledger-9 build; see ")+P("midnight help localnet")+g(".")+`
|
|
421
428
|
|
|
422
429
|
`);return}process.stderr.write(`
|
|
423
|
-
`+
|
|
430
|
+
`+W("Localnet Status")+`
|
|
424
431
|
|
|
425
|
-
`),process.stderr.write(
|
|
432
|
+
`),process.stderr.write(Tc(t)+`
|
|
426
433
|
`),process.stderr.write(`
|
|
427
|
-
`+
|
|
434
|
+
`+K()+`
|
|
428
435
|
|
|
429
436
|
`);for(let r of t)process.stdout.write(`${r.name}=${r.state}:${r.port}
|
|
430
|
-
`)}async function
|
|
431
|
-
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",
|
|
437
|
+
`)}async function hm(e){let t=G("Removing conflicting containers...");try{try{rr("down")}catch{}let r=yc();if(r.length>0)t.stop(`Removed ${r.length} container${r.length>1?"s":""}: ${r.join(", ")}`);else t.stop("No conflicting containers found");if(e){I({subcommand:"clean",status:"cleaned",removed:r});return}}catch(r){throw t.fail("Failed to clean up"),r}}async function wm(e){let t=to(),r=C(e,"tail"),n=R(e,"json");if(r!==void 0||n){let o=r??"200",i=xc("docker",["compose","-f",t,"logs","--tail",o,"--no-color"],{stdio:["ignore","pipe","pipe"]}),a="",c="";return i.stdout.on("data",(d)=>{a+=d.toString()}),i.stderr.on("data",(d)=>{c+=d.toString()}),new Promise((d,u)=>{i.on("close",(l)=>{if(l!==0&&l!==null){u(Error(`docker compose logs exited with code ${l}: ${c.trim()}`));return}if(n)I({tail:Number(o),lines:a.split(`
|
|
438
|
+
`).filter(Boolean)});else process.stdout.write(a);d()}),i.on("error",u)})}let s=xc("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 Nc(e){let t=e.subcommand;if(!t||!lm(t))throw new q(`Usage: midnight localnet <${Ac.join("|")}>
|
|
432
439
|
|
|
433
440
|
Subcommands:
|
|
434
|
-
up Start the local network
|
|
441
|
+
up Start the local network (refused on this ledger-9 build)
|
|
435
442
|
stop Stop containers (preserves state)
|
|
436
443
|
down Remove containers, networks, volumes
|
|
437
444
|
status Show service status
|
|
438
445
|
logs Stream service logs
|
|
439
446
|
clean Remove conflicting containers
|
|
440
447
|
|
|
441
|
-
Example: midnight localnet
|
|
442
|
-
`+
|
|
448
|
+
Example: midnight localnet status`);mc();let r=R(e,"json");switch(process.stderr.write(`
|
|
449
|
+
`+W("Localnet")+`
|
|
443
450
|
|
|
444
|
-
`),t){case"up":return
|
|
451
|
+
`),t){case"up":return um(r);case"stop":return pm(r);case"down":return fm(r);case"status":return gm(r);case"logs":return wm(e);case"clean":return hm(r)}}var Ac;var Ic=T(()=>{ze();Sc();ue();at();Ac=["up","stop","down","status","logs","clean"]});var $c={};me($c,{default:()=>_c});import*as Pc from"fs";import*as ro from"path";import{homedir as ym}from"os";import{generateMnemonic as Sm,mnemonicToSeedSync as Dc,mnemonicToEntropy as bm,validateMnemonic as vm}from"@scure/bip39";import{wordlist as no}from"@scure/bip39/wordlists/english.js";async function _c(e){let t=e.subcommand;switch(t){case"generate":return km(e);case"list":case"ls":return Cm(e);case"use":return Em(e);case"info":return xm(e);case"remove":case"rm":return Am(e);case"seed":return Tm(e);default:throw new q(`Unknown wallet subcommand: "${t??"(none)"}"
|
|
445
452
|
Available: generate, list, use, info, remove, seed
|
|
446
|
-
Run "midnight help wallet" for usage.`)}}async function
|
|
447
|
-
Usage: midnight wallet generate <name> [--network <name>]`);if(!
|
|
448
|
-
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=
|
|
449
|
-
Use --force to overwrite.`);let a,c;if(n!==void 0)
|
|
453
|
+
Run "midnight help wallet" for usage.`)}}async function km(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
454
|
+
Usage: midnight wallet generate <name> [--network <name>]`);if(!kt(t))throw Error(`Invalid wallet name: "${t}"
|
|
455
|
+
Wallet name must be a simple name (no path separators, .json suffix, or special characters).`);let r=he({args:e}),n=C(e,"seed"),s=C(e,"mnemonic");if(n!==void 0&&s!==void 0)throw Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let o=ro.join(ym(),oe,on),i=ro.join(o,`${t}.json`);if(Pc.existsSync(i)&&!R(e,"force"))throw Error(`Wallet "${t}" already exists: ${i}
|
|
456
|
+
Use --force to overwrite.`);let a,c;if(n!==void 0)a=Tr(n,"--seed");else if(s!==void 0){if(!vm(s,no))throw Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");c=s,a=Buffer.from(Dc(c))}else c=Sm(no,256),a=Buffer.from(Dc(c));let d=xt(a),u=Er(a),l=d[r],f={seed:a.toString("hex"),addresses:d,shieldedAddresses:u,createdAt:new Date().toISOString()};if(c)f.mnemonic=c;let p=un(f,i);if(Es(t),R(e,"json")){let h={name:t,addresses:d,shieldedAddresses:u,activeAddress:l,activeNetwork:r,seed:a.toString("hex"),file:p,createdAt:f.createdAt,active:!0};if(c)h.mnemonic=c;I(h);return}process.stdout.write(l+`
|
|
450
457
|
`),process.stderr.write(`
|
|
451
|
-
`+
|
|
452
|
-
|
|
453
|
-
`),process.stderr.write(
|
|
454
|
-
`),process.stderr.write(
|
|
455
|
-
`),process.stderr.write(
|
|
456
|
-
`);let
|
|
457
|
-
`);if(process.stderr.write(
|
|
458
|
-
`),process.stderr.write(
|
|
458
|
+
`+W("Wallet Generated")+`
|
|
459
|
+
|
|
460
|
+
`),process.stderr.write(E("Name",t)+`
|
|
461
|
+
`),process.stderr.write(E("Network",r)+`
|
|
462
|
+
`),process.stderr.write(E("Address",Q(l))+`
|
|
463
|
+
`);let m=u[r];if(m)process.stderr.write(E("Shielded",Q(m))+`
|
|
464
|
+
`);if(process.stderr.write(E("File",p)+`
|
|
465
|
+
`),process.stderr.write(E("Active","yes")+`
|
|
459
466
|
`),process.stderr.write(`
|
|
460
|
-
`),c)process.stderr.write(
|
|
467
|
+
`),c)process.stderr.write(Y(P(" MNEMONIC (save securely!):"))+`
|
|
461
468
|
`),process.stderr.write(` ${c}
|
|
462
469
|
|
|
463
|
-
`);process.stderr.write(
|
|
470
|
+
`);process.stderr.write(Y(P(" SEED (hex):"))+`
|
|
464
471
|
`),process.stderr.write(` ${a.toString("hex")}
|
|
465
472
|
|
|
466
|
-
`),process.stderr.write(
|
|
473
|
+
`),process.stderr.write(K()+`
|
|
467
474
|
`),process.stderr.write(g(" Next: midnight wallet list | midnight balance")+`
|
|
468
475
|
|
|
469
|
-
`),process.stderr.write(
|
|
470
|
-
`)}async function
|
|
476
|
+
`),process.stderr.write(U("✓")+` Wallet saved
|
|
477
|
+
`)}async function Cm(e){let t=xs(),r=he({args:e});if(R(e,"json")){if(lt(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(`
|
|
471
478
|
No wallets found.
|
|
472
479
|
`),process.stderr.write(g(" Create one: midnight wallet generate <name> --network <name>")+`
|
|
473
480
|
|
|
474
481
|
`);return}process.stderr.write(`
|
|
475
|
-
`+
|
|
482
|
+
`+W("Wallets")+`
|
|
476
483
|
|
|
477
484
|
`);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")}
|
|
478
|
-
`);for(let a of t){let c=a.isActive?
|
|
485
|
+
`);for(let a of t){let c=a.isActive?U("●"):" ",d=a.isActive?P(H(a.name)):H(a.name),u=" ".repeat(n-a.name.length),l=a.addresses[r]??"(unknown)",f=a.shieldedAddresses?.[r],p=f?Q(f,!0):g("—".padEnd(o));process.stderr.write(` ${c} ${d}${u} ${Q(l,!0)} ${p}
|
|
479
486
|
`)}process.stderr.write(`
|
|
480
|
-
`+
|
|
487
|
+
`+K()+`
|
|
481
488
|
`),process.stderr.write(g(` ● = active wallet · network: ${r} · details: midnight wallet info <name>`)+`
|
|
482
489
|
|
|
483
|
-
`)}async function
|
|
484
|
-
Usage: midnight wallet use <name>`);if(
|
|
485
|
-
`)}async function
|
|
490
|
+
`)}async function Em(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
491
|
+
Usage: midnight wallet use <name>`);if(Es(t),R(e,"json")){I({wallet:t,active:!0});return}process.stderr.write(U("✓")+` Active wallet set to "${t}"
|
|
492
|
+
`)}async function xm(e){let t=C(e,"wallet")??e.positionals[0]??Ht(),r=re(t),n=ie(r),s=t===Ht(),o=he({args:e}),i=n.addresses[o];if(R(e,"json")){if(lt(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+`
|
|
486
493
|
`),process.stderr.write(`
|
|
487
|
-
`+
|
|
494
|
+
`+W(`Wallet: ${t}`)+`
|
|
488
495
|
|
|
489
|
-
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],
|
|
490
|
-
`),process.stderr.write(` ${g("unshielded")} ${
|
|
491
|
-
`),
|
|
496
|
+
`);let a=Object.keys(n.addresses);for(let c=0;c<a.length;c++){let d=a[c],u=d===o,l=n.addresses[d],f=n.shieldedAddresses?.[d],p=u?P(H(d))+g(" (active)"):d;if(process.stderr.write(` ${p}
|
|
497
|
+
`),process.stderr.write(` ${g("unshielded")} ${Q(l)}
|
|
498
|
+
`),f)process.stderr.write(` ${g("shielded ")} ${Q(f)}
|
|
492
499
|
`);else process.stderr.write(` ${g("shielded ")} ${g("(unavailable)")}
|
|
493
500
|
`);if(c<a.length-1)process.stderr.write(`
|
|
494
501
|
`)}process.stderr.write(`
|
|
495
|
-
`+
|
|
502
|
+
`+K()+`
|
|
496
503
|
|
|
497
504
|
`),process.stderr.write(` ${g("created")} ${n.createdAt}
|
|
498
505
|
`),process.stderr.write(` ${g("file ")} ${r}
|
|
499
|
-
`),process.stderr.write(` ${g("active ")} ${s?
|
|
500
|
-
|
|
501
|
-
`)}async function
|
|
502
|
-
Usage: midnight wallet remove <name>`);if(
|
|
503
|
-
`)}async function
|
|
504
|
-
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(
|
|
505
|
-
`),process.stderr.write(
|
|
506
|
-
`),process.stderr.write(
|
|
507
|
-
`),process.stderr.write(
|
|
506
|
+
`),process.stderr.write(` ${g("active ")} ${s?U("yes"):"no"}
|
|
507
|
+
|
|
508
|
+
`)}async function Am(e){let t=e.positionals[0];if(!t)throw Error(`Missing wallet name.
|
|
509
|
+
Usage: midnight wallet remove <name>`);if(Ei(t),R(e,"json")){I({wallet:t,removed:!0});return}process.stderr.write(U("✓")+` Wallet "${t}" removed
|
|
510
|
+
`)}async function Tm(e){let t=C(e,"wallet")??e.positionals[0]??Ht(),r=re(t),n=await import("fs"),s=JSON.parse(n.readFileSync(r,"utf-8"));if(!s.seed)throw Error(`Wallet "${t}" has no seed in ${r}`);let o=R(e,"entropy"),i;if(o){if(!s.mnemonic)throw Error(`Wallet "${t}" has no mnemonic on file — cannot derive BIP-39 entropy.
|
|
511
|
+
`+"The 32-byte entropy can only be computed from the original 24-word mnemonic.");i=Buffer.from(bm(s.mnemonic,no)).toString("hex")}if(R(e,"json")){let c={name:t,seed:s.seed};if(s.mnemonic)c.mnemonic=s.mnemonic;if(i)c.entropy=i;I(c);return}if(process.stderr.write(`
|
|
512
|
+
`),process.stderr.write(Y(P(" ⚠ WARNING: This will display your wallet seed and mnemonic."))+`
|
|
513
|
+
`),process.stderr.write(Y(" Anyone with this seed can access your funds.")+`
|
|
514
|
+
`),process.stderr.write(Y(" Never share it. Never paste it into a website.")+`
|
|
508
515
|
`),process.stderr.write(`
|
|
509
|
-
`),!await
|
|
516
|
+
`),!await Nm(" Show seed? (y/N) ")){process.stderr.write(g(" Cancelled.")+`
|
|
510
517
|
|
|
511
518
|
`);return}if(process.stdout.write(s.seed+`
|
|
512
519
|
`),process.stderr.write(`
|
|
513
|
-
`),process.stderr.write(
|
|
514
|
-
`),process.stderr.write(
|
|
515
|
-
`),i)process.stderr.write(
|
|
516
|
-
`);if(s.mnemonic)process.stderr.write(
|
|
517
|
-
`);if(process.stderr.write(
|
|
520
|
+
`),process.stderr.write(E("Name",t)+`
|
|
521
|
+
`),process.stderr.write(E("Seed (64-byte PBKDF2)",s.seed)+`
|
|
522
|
+
`),i)process.stderr.write(E("Entropy (32-byte BIP-39)",i)+`
|
|
523
|
+
`);if(s.mnemonic)process.stderr.write(E("Mnemonic",s.mnemonic)+`
|
|
524
|
+
`);if(process.stderr.write(E("File",r)+`
|
|
518
525
|
`),i)process.stderr.write(`
|
|
519
526
|
`),process.stderr.write(g(" Note: seed and entropy derive DIFFERENT Midnight wallets from the")+`
|
|
520
527
|
`),process.stderr.write(g(" same mnemonic. Use the value your target project accepts.")+`
|
|
521
528
|
`);process.stderr.write(`
|
|
522
|
-
`)}function
|
|
529
|
+
`)}function Nm(e){return new Promise((t)=>{let r=jo("readline"),n=r.createInterface({input:process.stdin,output:process.stderr});n.question(e,(s)=>{n.close(),t(s.trim().toLowerCase()==="y")})})}var Oc=T(()=>{ze();Be();Ae();Gt();Me();ue()});var Wc={};me(Wc,{default:()=>Uc});function oo(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 so(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 Ln(e){let t=`${an}${e}`,r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw Error(`Dashboard returned HTTP ${r.status} for ${e}`);return r.json()}async function Pm(e){let t=C(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 Wn(e,t={}){let r=new AbortController,n=setTimeout(()=>r.abort(),Dm),s=Date.now();try{return{response:await fetch(e,{...t,signal:r.signal}),latencyMs:Date.now()-s}}finally{clearTimeout(n)}}async function _m(e){let t=new Date().toISOString();try{let{response:r,latencyMs:n}=await Wn(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"{ block { height } }"})});if(!r.ok){if(r.status===403)return{status:"degraded",latencyMs:n,lastChecked:t,notes:"HTTP 403 — likely WAF blocking"};return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`}}let s=await r.json();if(!s?.data)return{status:"down",latencyMs:n,lastChecked:t,notes:"No data field"};let o=s.data?.block?.height;return{status:n>Un?"degraded":"up",latencyMs:n,lastChecked:t,...o!==void 0?{blockHeight:o}:{},...n>Un?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function $m(e){let t=new Date().toISOString(),r=e.replace(/^wss:/,"https:").replace(/^ws:/,"http:");try{let{response:n,latencyMs:s}=await Wn(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"system_health",params:[]})});if(!n.ok){if(n.status===403)return{status:"degraded",latencyMs:s,lastChecked:t,notes:"HTTP 403 — likely WAF blocking"};return{status:"down",latencyMs:s,lastChecked:t,notes:`HTTP ${n.status}`}}let i=(await n.json())?.result;if(!i)return{status:"down",latencyMs:s,lastChecked:t,notes:"No result in response"};let a=i.peers??0,c=i.isSyncing??!1,d="up",u;if(c)d="degraded",u="Node is syncing";else if(a===0)d="degraded",u="No peers";return{status:d,latencyMs:s,lastChecked:t,peers:a,isSyncing:c,...u?{notes:u}:{}}}catch(n){return{status:"down",latencyMs:0,lastChecked:t,notes:n.message}}}async function Om(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 Wn(e);if(!r.ok)return{status:"down",latencyMs:n,lastChecked:t,notes:`HTTP ${r.status}`};return{status:n>Fc?"degraded":"up",latencyMs:n,lastChecked:t,...n>Fc?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function Mm(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 Wn(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>Un?"degraded":"up",latencyMs:n,lastChecked:t,...n>Un?{notes:`Slow (${n}ms)`}:{}}}catch(r){return{status:"down",latencyMs:0,lastChecked:t,notes:r.message}}}async function Lc(e){if(!Ne(e))return{};let t=kr(e),r=Rm[e];if(!r)return{};let[n,s,o,i]=await Promise.all([_m(t.indexer),$m(t.node),Om(r.faucet),Mm(r.explorer)]);return{indexer:n,rpc:s,faucet:o,explorer:i}}function Fm(e,t,r){process.stderr.write(`
|
|
523
530
|
`+P(e)+`
|
|
524
531
|
`),process.stderr.write(g(" "+"─".repeat(62))+`
|
|
525
|
-
`);let n=new Set([...Object.keys(r),...t?Object.keys(t):[]]);for(let s of n){let o=r[s],i=t?.[s],a=(
|
|
526
|
-
`)}else if(i){let c=
|
|
527
|
-
`)}}}function
|
|
528
|
-
`+
|
|
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=(Im[s]??s).padEnd(18);if(o){let c=Mc[o.status]??g("—"),d=o.latencyMs>0?g(` ${o.latencyMs}ms`):"",u=o.notes?g(` — ${o.notes}`):"",l="";if(i&&i.status!==o.status&&i.status!=="unknown")l=g(` (canary: ${i.status}${i.lastChecked?" "+oo(i.lastChecked):""})`);process.stderr.write(` ${Ir(a)}${c}${d}${u}${l}
|
|
533
|
+
`)}else if(i){let c=Mc[i.status]??g("—"),d=i.latencyMs>0?g(` ${i.latencyMs}ms`):"",u=i.lastChecked?g(` (${oo(i.lastChecked)})`):"",l=i.notes?g(` — ${i.notes}`):"";process.stderr.write(` ${Ir(a)}${c}${d}${u}${l}
|
|
534
|
+
`)}}}function Lm(e,t){let r=t?e.filter((n)=>n.affects.toLowerCase().includes(t.toLowerCase())):e;if(r.length===0)return;process.stderr.write(`
|
|
535
|
+
`+W("Known Issues")+`
|
|
529
536
|
|
|
530
537
|
`);for(let n of r)process.stderr.write(` ${ae(n.id.padEnd(28))}${n.summary}
|
|
531
538
|
`),process.stderr.write(` ${" ".repeat(28)}${g(n.status)}
|
|
532
|
-
`)}async function
|
|
533
|
-
`+
|
|
534
|
-
`),i?.lastUpdated)process.stderr.write(g(` Canary: ${
|
|
539
|
+
`)}async function Uc(e){let t=R(e,"json"),r=R(e,"all"),n=R(e,"watch"),s=await Pm(e)??"preprod",o=G("Checking network status..."),i=null,a=null,c,d;if(r)d=["preprod","preview"];else d=[s];let[u,...l]=await Promise.all([Promise.all([Ln("/api/status"),Ln("/api/issues")]).catch((h)=>(c=h.message,null)),...d.map((h)=>Lc(h))]);if(u)[i,a]=u;o.stop("Done");let f={};for(let h=0;h<d.length;h++)f[d[h]]=l[h];if(t){let h={lastUpdated:i?.lastUpdated??null,dashboard:an,canaryAvailable:i!==null,networks:{}};for(let y of d){let S=f[y]??{},v=i?.networks[y],A={...v,...S};h.networks[y]={overall:so(A),live:S,canary:v??null}}if(a){let y=r?void 0:d[0];h.issues=y?a.issues.filter((S)=>S.affects.toLowerCase().includes(y.toLowerCase())):a.issues}if(c)h.canaryError=c;I(h);let w=d.reduce((y,S)=>{let v={...i?.networks[S]??{},...f[S]??{}},A=so(v);if(A==="down")return"down";if(A==="degraded"&&y!=="down")return"degraded";return y},"up");if(w==="down")process.exitCode=2;else if(w==="degraded")process.exitCode=1;return}let p=()=>{if(process.stderr.write(`
|
|
540
|
+
`+W("Midnight Network Status")+`
|
|
541
|
+
`),i?.lastUpdated)process.stderr.write(g(` Canary: ${oo(i.lastUpdated)}`)+" ");if(process.stderr.write(g("Live: just now")+`
|
|
535
542
|
`),c)process.stderr.write(g(` (Dashboard unreachable: ${c})`)+`
|
|
536
543
|
`);if(d.length===0){process.stderr.write(`
|
|
537
544
|
`+g("No network data available.")+`
|
|
538
545
|
|
|
539
|
-
`);return}for(let
|
|
540
|
-
`+
|
|
541
|
-
`),process.stderr.write(g(" Dashboard: ")+
|
|
542
|
-
|
|
543
|
-
`)};if(
|
|
544
|
-
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(
|
|
545
|
-
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((
|
|
546
|
-
Expected: managed/<name>/compiler/${
|
|
547
|
-
Searched: ${
|
|
548
|
-
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function
|
|
549
|
-
`),"approve";if(t.
|
|
550
|
-
`),"approve";if(t.autoApproveReads&&
|
|
546
|
+
`);return}for(let h of d)Fm(h,i?.networks[h],f[h]??{});if(a){let h=r?void 0:d[0];Lm(a.issues,h)}process.stderr.write(`
|
|
547
|
+
`+K()+`
|
|
548
|
+
`),process.stderr.write(g(" Dashboard: ")+H(an)+`
|
|
549
|
+
|
|
550
|
+
`)};if(p(),n){let h=setInterval(async()=>{try{let[w,...y]=await Promise.all([Promise.all([Ln("/api/status"),Ln("/api/issues")]).catch(()=>null),...d.map((S)=>Lc(S))]);if(w)[i,a]=w;for(let S=0;S<d.length;S++)f[d[S]]=y[S];process.stderr.write("\x1B[2J\x1B[H"),p()}catch{process.stderr.write(g(" Refresh failed — retrying in 30s")+`
|
|
551
|
+
`)}},30000);await new Promise(()=>{process.on("SIGINT",()=>{clearInterval(h),process.exit(0)})})}let m=d.reduce((h,w)=>{let y={...i?.networks[w]??{},...f[w]??{}},S=so(y);if(S==="down")return"down";if(S==="degraded"&&h!=="down")return"degraded";return h},"up");if(m==="down")process.exitCode=2;else if(m==="degraded")process.exitCode=1}var Rm,Im,Mc,Dm=15000,Un=5000,Fc=1e4;var Bc=T(()=>{ge();ue();at();Rm={preprod:{faucet:"https://faucet.preprod.midnight.network/",explorer:"https://preprod.midnightexplorer.com/"},preview:{faucet:"https://faucet.preview.midnight.network/",explorer:null},undeployed:{faucet:"",explorer:""}},Im={indexer:"Indexer",rpc:"RPC Node",faucet:"Faucet",explorer:"Explorer",chain:"Chain",dust:"Dust Generation",wallet:"Wallet Ops",dapp:"DApp Flow"},Mc={up:U("UP"),down:ae("DOWN"),degraded:P("\x1B[33mDEGRADED\x1B[0m"),unknown:g("—")}});import{existsSync as io,readFileSync as Um,readdirSync as Wm}from"node:fs";import{join as nr,basename as Bm}from"node:path";function ct(e,t){let r=nr(e,"compiler",Bn);if(io(r))return Hc(r,e,[]);for(let n of jc){let s=n?nr(e,n,"managed"):nr(e,"managed");if(!io(s))continue;let o;try{o=Wm(s).sort()}catch{continue}let i=o.filter((u)=>io(nr(s,u,"compiler",Bn)));if(i.length===0)continue;let a;if(t){if(!i.includes(t))throw Error(`Contract "${t}" not found in ${s}
|
|
552
|
+
Available: ${i.join(", ")}`);a=t}else a=i[0];let c=i.filter((u)=>u!==a),d=nr(s,a,"compiler",Bn);return Hc(d,nr(s,a),c)}throw Error(`No compiled contract found in ${e}
|
|
553
|
+
Expected: managed/<name>/compiler/${Bn}
|
|
554
|
+
Searched: ${jc.map((n)=>n?`${n}/managed/`:"managed/").join(", ")}
|
|
555
|
+
Run "compact compile" first, or use --managed <path> to specify the managed directory.`)}function Hc(e,t,r){let n;try{n=JSON.parse(Um(e,"utf-8"))}catch(o){throw Error(`Failed to parse ${e}: ${o.message}`)}return{info:jm(n,e,t,r),infoPath:e}}function jm(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:Bm(r),managedDir:r,compilerVersion:o,languageVersion:i,runtimeVersion:a,circuits:c,witnesses:d,siblings:n}}function Le(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(Le).join(", ")}]`;case"Boolean":return"boolean";case"String":return"string";case"Vector":return e.types?.[0]?`${Le(e.types[0])}[]`:"unknown[]";case"Map":if(e.types&&e.types.length>=2)return`Map<${Le(e.types[0])}, ${Le(e.types[1])}>`;return"Map<unknown, unknown>";case"Set":return e.types?.[0]?`Set<${Le(e.types[0])}>`:"Set<unknown>";case"Option":return e.types?.[0]?`${Le(e.types[0])} | null`:"unknown | null";default:return e["type-name"]??"unknown"}}function Gc(e){let t=e.arguments.map((r)=>`${r.name}: ${Le(r.type)}`).join(", ");return`${e.name}(${t})`}function Kc(e){if(e.pure)return"pure";let t=["impure"];if(e.proof)t.push("proof");return t.join(", ")}function Vc(e){let t=e.arguments.map((s)=>`${s.name}: ${Le(s.type)}`).join(", "),r=Le(e["result type"]),n=r!=="void"?` → ${r}`:"";return`${e.name}(${t})${n}`}function Jc(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:Le(r.type)})),returnType:Le(t["result-type"])})),witnesses:e.witnesses.map((t)=>({name:t.name,arguments:t.arguments.map((r)=>({name:r.name,type:Le(r.type)})),returnType:Le(t["result type"])}))}}var Bn="contract-info.json",jc;var jn=T(()=>{jc=["","contract/src","contract","contracts/src","contracts","src"]});import*as qc from"node:readline";function Km(e){return Hm.has(e)}function Vm(e){return Gm.has(e)}function Jm(e){let t=[],r=e.dappName?`Request from "${e.dappName}"`:"DApp Request";if(t.push(P(r)),t.push(""),t.push(` ${g("Action:")} ${H(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(` ${U("[A]pprove")} ${ae("[R]eject")}`),Ti(t,"heavy")}function qm(e,t){if(t.approveFees)return`--approve-fees approves only paying the Dust fee for an agent's own balanced transaction (and its submit); ${e.method} needs a terminal to approve`;return`${Vm(e.method)?"Balancing prompts like any other write":`${e.method} needs a terminal to approve`}: use --approve-all for non-interactive environments, or --approve-fees for a fee wallet that only pays an agent's Dust fee`}async function zc(e,t={}){if(t.approveAll)return process.stderr.write(g(` Auto-approved: ${e.method}`)+`
|
|
556
|
+
`),"approve";if(t.approveFees&&e.feeOnly)return process.stderr.write(g(` Auto-approved (fee-only): ${e.method}`)+`
|
|
557
|
+
`),"approve";if(t.autoApproveReads&&Km(e.method))return process.stderr.write(g(` Auto-approved (read-only): ${e.method}`)+`
|
|
551
558
|
`),"approve";if(!process.stdin.isTTY)return process.stderr.write(ae(" Cannot prompt for approval: stdin is not a TTY")+`
|
|
552
|
-
`),process.stderr.write(g(
|
|
553
|
-
`),"reject";if(
|
|
559
|
+
`),process.stderr.write(g(` ${qm(e,t)}`)+`
|
|
560
|
+
`),"reject";if(Kr)return process.stderr.write(ae(" Rejected: another approval prompt is active")+`
|
|
554
561
|
`),"reject";process.stderr.write(`
|
|
555
|
-
`+
|
|
556
|
-
|
|
557
|
-
`),
|
|
558
|
-
`),"reject"}return new Promise((n)=>{let s=(o)=>{
|
|
559
|
-
`)}),c.on("connection",(l)=>{let
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
${
|
|
567
|
-
${
|
|
562
|
+
`+Jm(e)+`
|
|
563
|
+
|
|
564
|
+
`),Kr=!0;let r;try{r=qc.createInterface({input:process.stdin,output:process.stderr})}catch{return Kr=!1,process.stderr.write(ae(" Cannot create readline interface")+`
|
|
565
|
+
`),"reject"}return new Promise((n)=>{let s=(o)=>{Kr=!1,r.close(),n(o)};r.on("close",()=>{if(Kr)s("reject")}),r.question(Y(" Approve? [A/r] "),(o)=>{let i=o.trim().toLowerCase();if(i==="r"||i==="reject")s("reject");else s("approve")})})}var Hm,Gm,Kr=!1;var Xc=T(()=>{ue();Hm=new Set(["getShieldedBalances","getUnshieldedBalances","getDustBalance","getShieldedAddresses","getUnshieldedAddress","getDustAddress","getTxHistory","getConfiguration","getConnectionStatus"]),Gm=new Set(["balanceUnsealedTransaction","balanceSealedTransaction"])});import{WebSocketServer as zm}from"ws";function Ym(e){if(ao(e))return Xm[e.code]??-32603;return-32603}function ao(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="DAppConnectorAPIError"}function Zm(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 Hn(e,t){if(typeof t==="bigint")return t.toString();return t}function Qm(e,t){return t}function eg(e){let t;try{t=JSON.parse(e,Qm)}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 Yc(e){let{port:t,handlers:r,onConnect:n,onDisconnect:s,onRequest:o,onResponse:i}=e,a=new Map,c=new zm({port:t,host:"127.0.0.1"}),d=new Promise((l,f)=>{c.once("listening",()=>l()),c.once("error",f)});d.catch(()=>{}),c.on("error",(l)=>{process.stderr.write(`WebSocket server error: ${l.message}
|
|
566
|
+
`)}),c.on("connection",(l)=>{let f=`conn_${++tg}`,p={ws:l,id:f,connectedAt:new Date,authenticated:!1,requestCount:0,notify(w,y){if(l.readyState!==l.OPEN)return;let S={jsonrpc:"2.0",method:w,...y&&{params:y}};l.send(JSON.stringify(S,Hn))}};a.set(f,p),n?.(p);let m=!1,h=()=>{if(m)return;m=!0,a.delete(f),s?.(p)};l.on("message",async(w)=>{let y=null,S,v,A=Date.now();try{S=eg(w.toString("utf-8")),y=S.id,p.requestCount++,o?.(p,S);let N=Object.hasOwn(r,S.method)?r[S.method]:void 0;if(!N){let V={jsonrpc:"2.0",id:S.id,error:{code:-32601,message:`Method not found: ${S.method}`}};l.send(JSON.stringify(V,Hn));return}v={notify:p.notify.bind(p),connectionId:f,requestId:S.id,metadata:{}};let L=await N(S.params??{},v),ee=Date.now()-A;if(S.method==="connect"&&L&&typeof L==="object")p.authenticated=!0,p.networkId=L.networkId;let X={jsonrpc:"2.0",id:S.id,result:L};l.send(JSON.stringify(X,Hn)),i?.(p,S,ee,L,void 0,v.metadata)}catch(N){let L=Date.now()-A,ee=N?.rpcCode??Ym(N),X=N instanceof Error?N.message:"Internal error",V=ao(N)?{type:N.type,code:N.code}:Zm(N),O={jsonrpc:"2.0",id:y,error:{code:ee,message:X,data:V}};if(l.send(JSON.stringify(O,Hn)),S){let _={message:X,code:ao(N)?N.code:void 0};i?.(p,S,L,void 0,_,v?.metadata)}}}),l.on("close",h),l.on("error",()=>{h();try{l.close()}catch{}})});async function u(){for(let l of a.values())l.ws.close(1001,"Server shutting down");return a.clear(),new Promise((l,f)=>{c.close((p)=>{if(p)f(p);else l()})})}return{wss:c,connections:a,ready:d,close:u}}function te(e,t){let r=Error(t);return r.type="DAppConnectorAPIError",r.code=e,r.reason=t,r}var Xm,tg=0;var co=T(()=>{Xm={Rejected:-32000,PermissionRejected:-32001,Disconnected:-32002,InvalidRequest:-32602,InternalError:-32603}});function Zc(e){let t=[],r,n;function s(){if(r!==void 0&&n!==void 0){let a=Date.now()-n;t.push({phase:r,durationMs:a}),e?.onComplete?.(r,a),r=void 0,n=void 0}}function o(a){s(),r=a,n=Date.now(),e?.onStart?.(a)}function i(){return[...t]}return{start:o,complete:s,getTimings:i}}function Qc(e){return Buffer.from(e).toString("hex")}function sr(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 td(e,t){if(e<=t.maxFeeSpecks)return;return`the estimated fee ${Ue(e)} DUST is over --max-fee ${Ue(t.maxFeeSpecks)} DUST`}function rd(e,t){if(e<t.maxPending)return;return`${e} balanced transactions are still waiting to be submitted (--max-pending ${t.maxPending})`}var rg,ed;var nd=T(()=>{ze();ue();rg=10n**15n,ed={maxFeeSpecks:10n*rg,maxPending:2}});import{Transaction as ng}from"@midnightntwrk/ledger-v9";function lo(e,t){let r=[];r.push({label:"Tx size",value:ag(e.length/2)});let n=sg(e,t);if(n){let s=og(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 sg(e,t){let r=ig(e),n=t==="sealed"?[["signature","proof","binding"],["signature","proof","pre-binding"]]:[["signature","proof","pre-binding"],["signature","pre-proof","pre-binding"]];for(let[s,o,i]of n)try{return ng.deserialize(s,o,i,r).toString(!0)}catch{}return null}function og(e){let t={networkId:null,action:null,circuits:[],ttl:null},r=e.match(/network_id:\s*"([^"]+)"/);if(r)t.networkId=r[1];if(e.includes("Deploy ContractState"))t.action="Deploy contract";else if(e.match(/Call\s/))t.action="Call contract";let n=/(\w+):\s*<verifier key>/g,s;while((s=n.exec(e))!==null)t.circuits.push(s[1]);if(t.circuits.length===0){let i=e.match(/Call\s+\S+\s+(\w+)/);if(i)t.circuits.push(i[1])}let o=e.match(/ttl:\s*Timestamp\((\d+)\)/);if(o){let i=parseInt(o[1],10),a=new Date(i*1000);t.ttl=a.toISOString().replace("T"," ").slice(0,19)}return t}function ig(e){return new Uint8Array(Buffer.from(e,"hex"))}function ag(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 sd=()=>{};import{Transaction as od,addressFromKey as id}from"@midnightntwrk/ledger-v9";function or(e,t){return t==="unsealed"?od.deserialize("signature","proof","pre-binding",e):od.deserialize("signature","proof","binding",e)}function uo(e){return new Set([cg,...e.intents?.keys()??[],...e.fallibleOffer?.keys()??[]])}function ad(e,t){return[...e.intents??new Map].filter(([,r])=>r.ttl.getTime()<=t.getTime()).map(([r,n])=>({segment:r,ttl:n.ttl}))}function po(e){let t=[];for(let[r,n]of e.intents??new Map){let s=[["guaranteed",n.guaranteedUnshieldedOffer],["fallible",n.fallibleUnshieldedOffer]];for(let[o,i]of s)i?.inputs.forEach((a,c)=>t.push({where:`intent ${r} ${o} unshielded input ${c}`,owner:a.owner,signed:i.signatures[c]!==void 0}))}return t}function cd(e,t){if(e.rewards!==void 0)return["it is a rewards claim, not a standard transaction"];let r=[],n=id(t);for(let{where:s,owner:o,signed:i}of po(e)){if(id(o)===n)r.push(`${s} spends this wallet's own funds`);if(!i)r.push(`${s} is unsigned, so this wallet would sign it`)}for(let s of uo(e)){let o;try{o=e.imbalances(s)}catch(i){r.push(`segment ${s}'s balance could not be computed: ${i.message??i}`);continue}for(let[i,a]of o){if(i.tag==="dust"||a>=0n)continue;r.push(`segment ${s} is short ${-a} of ${i.tag} token ${i.raw}, which a Dust-only balance can't fund`)}}return r}var cg=0;var fo=()=>{};function dd(e){let t=po(e),r=t.filter((n)=>n.signed).length;if(r===0)return"none";return r===t.length?"all":"some"}function dg(e){return[...uo(e)].filter((t)=>[...e.imbalances(t)].some(([r,n])=>r.tag==="unshielded"&&n!==0n))}function ld(e,t){let r=dd(e);if(r==="some")throw new ir;if(r==="all"&&t){let n=dg(e);if(n.length>0)throw new mo(n)}}async function ud(e,t,r){if(t.type!=="UNBOUND_TRANSACTION")return e.signRecipe(t,r);let n=or(t.baseTransaction.serialize(),"unsealed"),s=dd(n);if(s==="none")return e.signRecipe(t,r);if(s==="some")throw new ir;if(!t.balancingTransaction)return t;let o=await e.signRecipe({type:"UNPROVEN_TRANSACTION",protocolVersion:t.protocolVersion,transaction:t.balancingTransaction},r);if(o.type!=="UNPROVEN_TRANSACTION")throw Error(`The wallet SDK signed an unproven transaction into a ${o.type} recipe`);return{...t,balancingTransaction:o.transaction}}var ir,mo;var pd=T(()=>{fo();ir=class ir 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,ir.prototype)}};mo=class mo 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,mo.prototype)}}});async function fd(e,t){let r;try{r=await xn(e,ug,{hash:t},lg)}catch(o){throw new Vr(t,o.message)}let n=r.transactions?.find((o)=>o.__typename==="RegularTransaction");if(!n)throw new Vr(t,"the indexer has no such transaction");let s=n.transactionResult?.status;if(s!=="PARTIAL_SUCCESS")throw new Vr(t,`the indexer reports it as ${s??"having no result"}, not a partial success`);return n.transactionResult?.segments??[]}var lg=1e4,ug=`query ($hash: HexEncoded!) {
|
|
567
|
+
transactions(offset: { hash: $hash }) {
|
|
568
|
+
__typename
|
|
569
|
+
... on RegularTransaction { transactionResult { status segments { id success } } }
|
|
570
|
+
}
|
|
571
|
+
}`,Vr;var md=T(()=>{Ls();Vr=class Vr extends Error{constructor(e,t){super(`Could not read the segment results of transaction ${e} from the indexer: ${t}`);this.name="SegmentResultsUnavailableError",Object.setPrototypeOf(this,Vr.prototype)}}});import*as ar from"rxjs";import{MidnightBech32m as go,UnshieldedAddress as pg,ShieldedAddress as fg}from"@midnightntwrk/wallet-sdk/address-format";function $t(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 hd(e,t){switch(e.lifecycle.status){case"finalized":return{txHash:e.hash,txStatus:{status:"finalized",executionStatus:mg(e,t)}};case"rejected":return{txHash:e.hash,txStatus:{status:"discarded"}};case"pending":return{txHash:e.hash,txStatus:{status:"pending"}}}}function mg(e,t){switch(e.status){case"SUCCESS":return{0:"Success"};case"FAILURE":return{0:"Failure"};case"PARTIAL_SUCCESS":if(!t||t.length===0)throw Error(`Transaction ${e.hash} partly succeeded, but its segment results are missing`);return Object.fromEntries(t.map((r)=>[r.id,r.success?"Success":"Failure"]));case void 0:return{}}}function gg(e){if(e!=="schnorr")throw Error(`Unexpected signature scheme "${e}": mn signs with BIP-340 Schnorr only`);return"schnorr_bip340"}function wd(e){let{bundle:t,networkConfig:r,approvalOptions:n,callbacks:s}=e,o=e.feeLimits??ed,{facade:i,keystore:a}=t,c=Oe(r.networkId),d,u,l=i.state().subscribe((k)=>{if(u=k.protocolVersion,k.isSynced)d=k});function f(){if(!d)throw te("Disconnected","Wallet not synced yet");return d}function p(){if(!u)throw te("Disconnected","Wallet not synced yet");let k=na(u);if(k.length>0){let b=k.map((x)=>`${x} at ${u[x]}`).join(", ");throw te("Disconnected",`This wallet can't take transactions until all three of its wallets are on ledger 9 (fork at ${st.v9}); still behind: ${b}. Wait for them to sync past the fork and retry.`)}}let m=new Map;function h(k,b,x,D=!1){let M=m.get(k);if(!M)M=new Map,m.set(k,M);let B=setTimeout(async()=>{if(M.delete(b),M.size===0)m.delete(k);try{await i.revert(x)}catch{}process.stderr.write(g(` abandoned tx reverted (${k})`)+`
|
|
572
|
+
`)},ai);M.set(b,{finalized:x,timer:B,feeOnly:D})}function w(k,b){let x=m.get(k);if(!x)return;let D=x.get(b);if(D)clearTimeout(D.timer),x.delete(b);if(x.size===0)m.delete(k)}async function y(k){let b=m.get(k);if(!b||b.size===0)return;m.delete(k);for(let[,x]of b){clearTimeout(x.timer);try{await i.revert(x.finalized)}catch{}}process.stderr.write(g(` reverted ${b.size} pending tx(s) on disconnect`)+`
|
|
573
|
+
`)}function S(){return new Date(Date.now()+nn*60*1000)}async function v(k,b){b?.start("signing");let x;try{x=await ud(i,k,a.signDataAsync)}catch(j){try{await i.revert(k)}catch{}if(j instanceof ir)throw te("InvalidRequest",j.message);throw j}b?.start("proving");let D,M,B=i.finalizeRecipe(x);try{M=await Promise.race([B,new Promise((j,Ce)=>{D=setTimeout(()=>Ce(Error("ZK proof generation timed out")),rn)})])}catch(j){try{await i.revert(k)}catch{}throw B.then((Ce)=>i.revert(Ce)).catch(()=>{}),j}finally{clearTimeout(D)}return b?.complete(),{hex:Qc(M.serialize()),finalized:M}}function A(k,b){try{return i.adoptTransaction(sr(k),b)}catch(x){throw te("InvalidRequest",`The transaction could not be read at stage ${b} as this wallet's ledger version: ${$t(x)}`)}}async function N(k,b=[],x,D=!1){x?.notify("approval:pending",{method:k});let M=await zc({method:k,network:r.networkId,details:b,dappName:x?.connectionId,feeOnly:D},n),B=M==="reject"?"rejected":"approved";if(x?.notify("approval:resolved",{method:k,result:B}),M==="reject")throw te("Rejected",n.approveFees?`${gd}: this fee wallet (--approve-fees) approves without the operator only paying the Dust fee for an agent's own transaction and submitting a transaction it balanced that way on the same connection`:gd)}function L(k,b,x){if(x===!1)throw te("InvalidRequest","This wallet is a fee wallet (--approve-fees): it only pays the Dust fee, so payFees: false leaves it nothing to do");let D;try{D=or(sr(k),b)}catch(B){throw te("InvalidRequest",`The transaction could not be read as a proven ledger-9 ${b} transaction: ${$t(B)}`)}let M=cd(D,a.getPublicKey());if(M.length>0)throw te("Rejected",`This wallet is a fee wallet (--approve-fees) and pays only the Dust fee; it refuses this transaction because ${M.join("; ")}`)}function ee(k,b){let x;try{x=ad(or(sr(k),b),new Date)}catch(D){throw te("InvalidRequest",$t(D))}if(x.length>0){let D=x.map(({segment:M,ttl:B})=>`intent ${M}'s TTL (${B.toISOString()})`).join(", ");throw te("InvalidRequest",`The transaction has expired: ${D} has passed. Build it again with a later TTL.`)}}function X(k,b){try{ld(or(sr(k),"unsealed"),b)}catch(x){throw te("InvalidRequest",$t(x))}}function V(){let k=0;for(let[,b]of m)k+=b.size;return k}function O(k){return te("Rejected",`This wallet is a fee wallet (--approve-fees) and refuses this transaction: ${k}`)}let _=0;function ne(){let k=rd(V()+_,o);if(k)throw O(k);_++;let b=!1;return()=>{if(!b)b=!0,_--}}async function de(k,b){let x=await Mt(()=>i.estimateTransactionFee(k,{ttl:b}));process.stderr.write(g(` fee-only: estimated fee ${Ue(x)} DUST (limit ${Ue(o.maxFeeSpecks)})`)+`
|
|
574
|
+
`);let D=td(x,o);if(D)throw O(D)}async function Zr(k,b,x,D){let M=String(x.tx??"");if(!M)throw te("InvalidRequest","tx is required");p();let B=x.options?.payFees,j=n.approveFees===!0;if(j)L(M,b,B);let Ce=j?["dust"]:B===!1?["shielded","unshielded"]:"all",_e=S(),Ve=b==="unsealed"?A(M,"Unbound"):A(M,"Finalized");if(ee(M,b),b==="unsealed")X(M,Ce==="all"||Ce.includes("unshielded"));let Je=j?ne():void 0;try{if(j)await de(Ve,_e);let qe=St(k,D);qe.start("approve"),await N(k,lo(M,b),D,j),qe.start("building");let Ft={ttl:_e,tokenKindsToBalance:Ce},rs;if(b==="unsealed"){let ns=Ve;rs=await Mt(()=>i.balanceUnboundTransaction(ns,Ft))}else{let ns=Ve;rs=await Mt(()=>i.balanceFinalizedTransaction(ns,Ft))}let{hex:Bo,finalized:wu}=await v(rs,qe);return h(D.connectionId,Bo,wu,j),D.metadata.phases=qe.getTimings(),{tx:Bo}}finally{Je?.()}}function dt(k){return go.encode(c,k).asString()}function le(k){let b={};for(let x of k){let D=x.kind;if(D!=="shielded"&&D!=="unshielded")throw te("InvalidRequest",`Invalid output kind: "${D}" — must be "shielded" or "unshielded"`);if(!b[D])b[D]=[];let M=BigInt(x.value),B;if(D==="unshielded")B=go.parse(x.recipient).decode(pg,c);else B=go.parse(x.recipient).decode(fg,c);b[D].push({type:x.type,receiverAddress:B,amount:M})}return Object.entries(b).map(([x,D])=>({type:x,outputs:D}))}function St(k,b){return Zc({onStart:(x)=>{let D=b?.connectionId??"unknown";s?.onPhaseStart?.(D,k,x),b?.notify("progress",{method:k,phase:x,status:"started"})},onComplete:(x,D)=>{let M=b?.connectionId??"unknown";s?.onPhaseComplete?.(M,k,x,D),b?.notify("progress",{method:k,phase:x,status:"completed",durationMs:D})}})}function bt(){return d!==void 0&&Rt(d)}async function ke(k){return new Promise((b)=>{if(bt()){b(!0);return}let x=i.state().pipe(ar.filter(()=>bt()),ar.take(1),ar.timeout(k)).subscribe({next:()=>{x.unsubscribe(),b(!0)},error:()=>{x.unsubscribe(),b(!1)}})})}function vt(k){return te("InternalError",`No Dust is free to pay the fee (${$t(k)}). Each balanced transaction reserves a whole Dust coin until it is submitted and on chain, or released when its connection closes or it expires; ${V()} balanced transaction(s) are waiting to be submitted on this server. Retry once they settle. To pay for more transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.`)}async function Mt(k){for(let b=1;b<=wr;b++)try{return await k()}catch(x){let D=String(x?.message??x??"");if(!Xi(x))throw x;if(b===wr)throw vt(x);if(process.stderr.write(g(` dust unavailable, waiting for recovery (${b}/${wr})... [${D.slice(0,60)}]`)+`
|
|
575
|
+
`),!await ke(gs)&&b<wr)await new Promise((B)=>setTimeout(B,gs))}throw Error("unreachable")}let fe={connect:async(k)=>{let b=String(k.networkId??"");if(b.toLowerCase()!==r.networkId.toLowerCase())throw te("InvalidRequest",`Network mismatch: wallet is on ${r.networkId}, requested ${b}`);return{networkId:r.networkId}},getUnshieldedBalances:async()=>f().unshielded.balances,getShieldedBalances:async()=>f().shielded.balances,getDustBalance:async()=>{let b=f().dust.balance(new Date);return{cap:b,balance:b}},getUnshieldedAddress:async()=>{let k=f();return{unshieldedAddress:dt(k.unshielded.address)}},getShieldedAddresses:async()=>{let b=f().shielded.address;return{shieldedAddress:dt(b),shieldedCoinPublicKey:b.coinPublicKeyString(),shieldedEncryptionPublicKey:b.encryptionPublicKeyString()}},getDustAddress:async()=>{let k=f();return{dustAddress:dt(k.dust.address)}},getTxHistory:async(k)=>{f();let b=Number(k.pageNumber??0),x=Number(k.pageSize??20),D=b*x,M=await i.getAllFromTxHistory(),B=[];for(let j of M.slice(D,D+x)){if(j.lifecycle.status!=="finalized"||j.status!=="PARTIAL_SUCCESS"){B.push(hd(j));continue}try{B.push(hd(j,await fd(r.indexer,j.hash)))}catch(Ce){throw te("InternalError",$t(Ce))}}return B},getConfiguration:async()=>({indexerUri:r.indexer,indexerWsUri:r.indexerWS,proverServerUri:r.proofServer,substrateNodeUri:r.node,networkId:r.networkId}),getConnectionStatus:async()=>({status:"connected",networkId:c}),makeTransfer:async(k,b)=>{let x=k.desiredOutputs;if(!Array.isArray(x)||x.length===0)throw te("InvalidRequest","desiredOutputs must be a non-empty array");p();let D=St("makeTransfer",b),M=x.map((Je,qe)=>({label:`Output ${qe+1}`,value:`${Je.value} → ${String(Je.recipient).slice(0,20)}... (${Je.kind})`}));D.start("approve"),await N("makeTransfer",M,b),D.start("building");let B=le(x),j=k.options?.payFees??!0,Ce=await Mt(()=>i.transferTransaction(B,{ttl:S(),payFees:j})),{hex:_e,finalized:Ve}=await v(Ce,D);return h(b.connectionId,_e,Ve),b.metadata.phases=D.getTimings(),{tx:_e}},submitTransaction:async(k,b)=>{let x=String(k.tx??"");if(!x)throw te("InvalidRequest","tx is required");p();let D=St("submitTransaction",b),M=n.approveFees===!0&&m.get(b.connectionId)?.get(x)?.feeOnly===!0;D.start("approve");try{await N("submitTransaction",lo(x,"sealed"),b,M)}catch(j){let _e=m.get(b.connectionId)?.get(x);if(_e)try{await i.revert(_e.finalized)}catch{}throw w(b.connectionId,x),j}let B=A(x,"Finalized");D.start("submitting");try{let j=await i.submitTransaction(B);return D.complete(),w(b.connectionId,x),b.metadata.phases=D.getTimings(),{txHash:j}}catch(j){D.complete();let _e=m.get(b.connectionId)?.get(x);if(_e)try{await i.revert(_e.finalized)}catch{}w(b.connectionId,x);let Ve=$t(j),Je=Error(`Transaction submission failed: ${Ve}`);throw Je.cause=j,Je}},balanceUnsealedTransaction:(k,b)=>Zr("balanceUnsealedTransaction","unsealed",k,b),balanceSealedTransaction:(k,b)=>Zr("balanceSealedTransaction","sealed",k,b),makeIntent:async(k,b)=>{let{desiredInputs:x,desiredOutputs:D,options:M}=k;if(!M)throw te("InvalidRequest","options is required for makeIntent");p();let B=St("makeIntent",b);B.start("approve"),await N("makeIntent",[],b),B.start("building");let j={};if(Array.isArray(x))for(let qe of x){let Ft=qe.kind;if(!j[Ft])j[Ft]={};j[Ft][qe.type]=BigInt(qe.value)}let Ce=le(D??[]),_e=await Mt(()=>i.initSwap(j,Ce,{ttl:S(),payFees:M.payFees??!0})),{hex:Ve,finalized:Je}=await v(_e,B);return h(b.connectionId,Ve,Je),b.metadata.phases=B.getTimings(),{tx:Ve}},signData:async(k,b)=>{let x=String(k.data??""),D=k.options;if(!x||!D?.encoding)throw te("InvalidRequest","data and options.encoding are required");if(D.keyType&&D.keyType!=="unshielded")throw te("InvalidRequest",`Unsupported keyType: "${D.keyType}" — only "unshielded" is supported`);await N("signData",[{label:"Encoding",value:D.encoding},{label:"Data",value:x.length>64?x.slice(0,64)+"...":x}],b);let M;switch(D.encoding){case"hex":M=sr(x);break;case"base64":M=new Uint8Array(Buffer.from(x,"base64"));break;case"text":M=new Uint8Array(Buffer.from(x,"utf-8"));break;default:throw te("InvalidRequest",`Unknown encoding: ${D.encoding}`)}let B=await a.signDataAsync(M),j=a.getPublicKey();return{data:x,signature:B.value,verifyingKey:j.value,scheme:gg(B.tag)}},getProvingProvider:async()=>({provingProvider:"ready",proverServerUri:r.proofServer}),hintUsage:async(k)=>{let b=k.methodNames??[];process.stderr.write(g(` DApp hints usage: ${b.join(", ")}`)+`
|
|
576
|
+
`)}};function ye(){l.unsubscribe();for(let[,k]of m)for(let[,b]of k)clearTimeout(b.timer);m.clear()}function tt(){for(let[,k]of m)if(k.size>0)return!0;return!1}return{handlers:fe,revertPendingTxs:y,hasPendingTxs:tt,dispose:ye}}var gd="User rejected the request";var yd=T(()=>{He();ge();Xc();co();pt();Fr();nd();sd();fo();pd();md();zt();ue()});import{Socket as hg}from"node:net";function Sd(e){let{name:t,config:r}=ce({args:{command:"serve",subcommand:void 0,positionals:[],flags:{...e.network?{network:e.network}:{},...ln(e.endpoints??{})}}});return Ie(r,e.endpoints??{},t),{networkName:t,networkConfig:r}}function wg(e,t){let r=(s,o)=>s!==void 0&&s.replace(/\/+$/,"")===o.replace(/\/+$/,""),n=[];if(!r(e.substrateNodeUri,t.node))n.push(`node ${e.substrateNodeUri} (need ${t.node})`);if(!r(e.indexerWsUri,t.indexerWS))n.push(`indexer ${e.indexerWsUri} (need ${t.indexerWS})`);return n.length>0?n.join(", "):void 0}function yg(e){return new Promise((t)=>{let r=new hg;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 Sg(e){let r=(await bd(e,"getConnectionStatus"))?.networkId;return typeof r==="string"?r:null}async function bg(e){let t=await bd(e,"getConfiguration");return t&&typeof t==="object"?t:null}async function bd(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 Gn(e){let t=e.port??yr,r=(e.network??"undeployed").toLowerCase(),n=e.onMessage??(()=>{});if(await yg(t)){let s=await Sg(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 bg(t),a=i?wg(i,Sd(e).networkConfig):"its endpoints could not be read";if(a)throw Error(`mn serve on port ${t} is on a different ${o} chain: ${a}. Stop it first (\`pkill -f 'mn serve'\`) and retry.`);return n(`Reusing existing mn serve on port ${t}`),{port:t,async stop(){}}}return vg(e)}async function vg(e){let t=e.port??yr,r=e.onMessage??(()=>{}),n=ie(re(e.wallet)),s=Buffer.from(n.seed,"hex"),{networkName:o,networkConfig:i}=Sd(e);await Qe(o,i);let a=n.addresses[o],c=Te((m,h)=>{r(`SDK: ${h}`)}),d=Pe();r("Building wallet facade...");let u=wt(a,o),l=await Ye(s,i,u);r("Syncing wallet..."),await ht(l,{onProgress:(m,h)=>{if(h>0){let w=Math.min(Math.round(m/h*100),100);r(`Syncing wallet... ${w}%`)}}}),r("Wallet synced"),r("Waiting for dust..."),await bn(l),r("Dust ready");try{await ot(a,o,l.facade)}catch{}let f=wd({bundle:l,networkConfig:i,approvalOptions:{approveAll:!0,autoApproveReads:!0},callbacks:{onPhaseStart:(m,h,w)=>{r(`${w}...`)},onPhaseComplete:(m,h,w,y)=>{r(`${w} ${Math.round(y)}ms`)}}}),p=Yc({port:t,handlers:f.handlers,onConnect:(m)=>{r(`connected ${m.id}`)},onDisconnect:(m)=>{r(`disconnected ${m.id}`),f.revertPendingTxs(m.id).catch(()=>{})},onRequest:(m,h)=>{r(`${m.id} → ${h.method}`)},onResponse:(m,h,w,y,S)=>{if(S)r(`${m.id} ← ${h.method} FAILED: ${S.message}`);else r(`${m.id} ← ${h.method} (${Math.round(w)}ms)`)}});try{await p.ready}catch(m){throw f.dispose(),await p.close(),await Fe(l),c(),d(),Error(`Could not start mn serve on port ${t}: ${m.message}`)}return r(`Server ready on ws://localhost:${t}`),{port:t,async stop(){p.close(),f.dispose(),d(),c();try{await Fe(l)}catch{}}}}var ho=T(()=>{Me();Ae();zt();ge();He();It();_t();yd();co()});import{existsSync as vd}from"node:fs";import{join as kd}from"node:path";function Cd(e){for(let t of Kn){let r=kd(e,t);if(vd(r))return r}return null}function Cg(e){for(let t of kg){let r=kd(e,t);if(vd(r))return r}return null}function Ed(e){let{projectRoot:t,witnessNames:r}=e,n=Cg(t),s=[`Contract declares ${r.length} witness(es): ${r.join(", ")}`,"but no compiled witnesses module was found.","",`Searched (relative to ${t}):`,...Kn.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(`
|
|
577
|
+
`)}var Kn,kg;var wo=T(()=>{Kn=["dist/witnesses.js","src/witnesses.js","contract/dist/witnesses.js","contract/src/witnesses.js"],kg=["src/witnesses.ts","contract/src/witnesses.ts"]});function Vn(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(Vn)}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]=Vn(e[r]);return t}return e}function xd(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 Eg}from"node:child_process";import{writeFileSync as xg,unlinkSync as Ad,existsSync as Jn,symlinkSync as Td}from"node:fs";import{join as Jr,dirname as Nd}from"node:path";import{fileURLToPath as Ag}from"node:url";function Tg(){let e=Nd(Ag(import.meta.url));for(let t=0;t<8;t++){let r=Jr(e,"node_modules");if(Jn(r))return r;let n=Nd(e);if(n===e)break;e=n}return null}async function cr(e){let t=Dg(e),r=await So(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`State script returned unexpected output:
|
|
578
|
+
${r}`)}}async function qn(e){let t=Rg(e),r=e.privateStateSecretKey?{MN_PRIVATE_STATE_SECRET:e.privateStateSecretKey}:void 0,n=await So(e.dappDir,t,e.onMessage,r);try{return JSON.parse(n)}catch{throw Error(`Deploy script returned unexpected output:
|
|
579
|
+
${n}`)}}async function zn(e){let t=Ig(e),r=await So(e.dappDir,t,e.onMessage);try{return JSON.parse(r)}catch{throw Error(`Call script returned unexpected output:
|
|
580
|
+
${r}`)}}function Rd(e){return`
|
|
568
581
|
import WebSocket from 'ws';
|
|
569
582
|
|
|
570
583
|
const RPC_URL = 'ws://127.0.0.1:${e}';
|
|
@@ -605,37 +618,24 @@ function rpcCall(method, params = {}) {
|
|
|
605
618
|
function rpcClose() {
|
|
606
619
|
if (rpcWs) rpcWs.close();
|
|
607
620
|
}
|
|
608
|
-
`}function
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
async balanceTx(tx, ttl) {
|
|
619
|
-
const { toHex } = await import('@midnight-ntwrk/midnight-js-utils');
|
|
620
|
-
const txHex = toHex(tx.serialize());
|
|
621
|
-
const result = await rpcCall('balanceUnsealedTransaction', { tx: txHex });
|
|
622
|
-
|
|
623
|
-
const { fromHex } = await import('@midnight-ntwrk/midnight-js-utils');
|
|
624
|
-
const { Transaction } = await import('@midnight-ntwrk/midnight-js-types');
|
|
625
|
-
const bytes = fromHex(result.tx);
|
|
626
|
-
return Transaction.deserialize('signature', 'proof', 'binding', bytes);
|
|
627
|
-
},
|
|
628
|
-
async submitTx(tx) {
|
|
629
|
-
const { toHex } = await import('@midnight-ntwrk/midnight-js-utils');
|
|
630
|
-
const txHex = toHex(tx.serialize());
|
|
631
|
-
await rpcCall('submitTransaction', { tx: txHex });
|
|
632
|
-
return tx.identifiers()[0];
|
|
621
|
+
`}function Dd(){return`
|
|
622
|
+
const walletState = await rpcCall('getShieldedAddresses', {});
|
|
623
|
+
|
|
624
|
+
const walletProvider = createWalletProvider({
|
|
625
|
+
getCoinPublicKey: () => walletState.shieldedCoinPublicKey,
|
|
626
|
+
getEncryptionPublicKey: () => walletState.shieldedEncryptionPublicKey,
|
|
627
|
+
// ttl is ignored: mn serve applies its own TTL when balancing.
|
|
628
|
+
async balanceTx(tx) {
|
|
629
|
+
const result = await rpcCall('balanceUnsealedTransaction', { tx: toHex(tx.serialize()) });
|
|
630
|
+
return Transaction.deserialize('signature', 'proof', 'binding', fromHex(result.tx));
|
|
633
631
|
},
|
|
634
|
-
};
|
|
632
|
+
});
|
|
635
633
|
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
634
|
+
const midnightProvider = createMidnightProvider(async (tx) => {
|
|
635
|
+
await rpcCall('submitTransaction', { tx: toHex(tx.serialize()) });
|
|
636
|
+
return tx.identifiers()[0];
|
|
637
|
+
});
|
|
638
|
+
`}function Pd(e,t){return`
|
|
639
639
|
import { pathToFileURL } from 'node:url';
|
|
640
640
|
import { resolve } from 'node:path';
|
|
641
641
|
import { CompiledContract } from '@midnight-ntwrk/compact-js';
|
|
@@ -649,7 +649,7 @@ const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract',
|
|
|
649
649
|
// Both relative-to-cwd locations and contract/<...> locations are checked
|
|
650
650
|
// so mn dev (which chdirs into the contract sub-package) and mn contract
|
|
651
651
|
// deploy run from a workspace root both work.
|
|
652
|
-
const WITNESS_CANDIDATES = ${JSON.stringify(
|
|
652
|
+
const WITNESS_CANDIDATES = ${JSON.stringify(Kn)};
|
|
653
653
|
let witnesses;
|
|
654
654
|
let createPrivateState;
|
|
655
655
|
for (const p of WITNESS_CANDIDATES) {
|
|
@@ -680,7 +680,7 @@ if (!witnesses) {
|
|
|
680
680
|
// Uses a deterministic seed derived from the wallet so post/takeDown use the same key.
|
|
681
681
|
// The private state provider (leveldb) persists between calls, but initialPrivateState
|
|
682
682
|
// is the fallback when no stored state exists yet.
|
|
683
|
-
${
|
|
683
|
+
${Ng}
|
|
684
684
|
function makeInitialPrivateState() {
|
|
685
685
|
if (createPrivateState) {
|
|
686
686
|
// Secret precedence (see resolvePrivateStateSecretKey, injected above via
|
|
@@ -706,46 +706,42 @@ const compiled = witnesses
|
|
|
706
706
|
CompiledContract.withVacantWitnesses,
|
|
707
707
|
(c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR),
|
|
708
708
|
);
|
|
709
|
-
`}function
|
|
710
|
-
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
711
|
-
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
712
|
-
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
713
|
-
import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';
|
|
714
|
-
|
|
709
|
+
`}function _d(e,t){return`
|
|
715
710
|
const zkConfigProvider = new NodeZkConfigProvider(MANAGED_DIR);
|
|
716
711
|
|
|
717
712
|
const providers = {
|
|
718
713
|
privateStateProvider: levelPrivateStateProvider({
|
|
719
|
-
privateStateStoreName: ${JSON.stringify(
|
|
714
|
+
privateStateStoreName: ${JSON.stringify(t)},
|
|
720
715
|
privateStoragePasswordProvider: () => Promise.resolve('mn-contract-default-pwd-16ch'),
|
|
721
716
|
accountId: 'mn-contract-runner',
|
|
722
717
|
}),
|
|
723
|
-
publicDataProvider: indexerPublicDataProvider(
|
|
724
|
-
${JSON.stringify(
|
|
725
|
-
${JSON.stringify(
|
|
726
|
-
),
|
|
718
|
+
publicDataProvider: indexerPublicDataProvider({
|
|
719
|
+
queryURL: ${JSON.stringify(e.indexer)},
|
|
720
|
+
subscriptionURL: ${JSON.stringify(e.indexerWS??e.indexer.replace("http","ws"))},
|
|
721
|
+
}),
|
|
727
722
|
zkConfigProvider,
|
|
728
|
-
proofProvider: httpClientProofProvider(${JSON.stringify(
|
|
723
|
+
proofProvider: httpClientProofProvider({ url: ${JSON.stringify(e.proofServer)}, zkConfigProvider }),
|
|
729
724
|
walletProvider,
|
|
730
|
-
midnightProvider
|
|
725
|
+
midnightProvider,
|
|
731
726
|
};
|
|
732
|
-
`}function
|
|
727
|
+
`}function Rg(e){let t=e.privateStateKey??`${e.contractName}PrivateState`,r=JSON.stringify(e.args??[]);return`
|
|
733
728
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
734
729
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
735
730
|
|
|
736
|
-
${
|
|
737
|
-
${
|
|
731
|
+
${Rd(e.servePort)}
|
|
732
|
+
${Pd(e.contractName,e.managedDir)}
|
|
738
733
|
|
|
739
734
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
740
735
|
await rpcConnect();
|
|
741
736
|
process.stderr.write('Connected\\n');
|
|
742
737
|
|
|
743
|
-
${
|
|
744
|
-
${
|
|
738
|
+
${Id}
|
|
739
|
+
${Dd()}
|
|
740
|
+
${_d(e.networkConfig,t)}
|
|
745
741
|
|
|
746
742
|
import { deployContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
747
743
|
|
|
748
|
-
${
|
|
744
|
+
${$d}
|
|
749
745
|
const constructorArgs = (${r}).map(coerceArg);
|
|
750
746
|
process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n');
|
|
751
747
|
const deployed = await deployContract(providers, {
|
|
@@ -761,19 +757,20 @@ process.stderr.write('Deploy complete: ' + address + '\\n');
|
|
|
761
757
|
console.log(JSON.stringify({ contractAddress: address }));
|
|
762
758
|
rpcClose();
|
|
763
759
|
process.exit(0);
|
|
764
|
-
`}function
|
|
760
|
+
`}function Ig(e){let t=e.privateStateKey??`${e.contractName}PrivateState`;return`
|
|
765
761
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
766
762
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
767
763
|
|
|
768
|
-
${
|
|
769
|
-
${
|
|
764
|
+
${Rd(e.servePort)}
|
|
765
|
+
${Pd(e.contractName,e.managedDir)}
|
|
770
766
|
|
|
771
767
|
process.stderr.write('Connecting to mn serve...\\n');
|
|
772
768
|
await rpcConnect();
|
|
773
769
|
process.stderr.write('Connected\\n');
|
|
774
770
|
|
|
775
|
-
${
|
|
776
|
-
${
|
|
771
|
+
${Id}
|
|
772
|
+
${Dd()}
|
|
773
|
+
${_d(e.networkConfig,t)}
|
|
777
774
|
|
|
778
775
|
import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts';
|
|
779
776
|
|
|
@@ -786,14 +783,14 @@ const deployed = await findDeployedContract(providers, {
|
|
|
786
783
|
});
|
|
787
784
|
|
|
788
785
|
process.stderr.write('Calling ${e.circuit}...\\n');
|
|
789
|
-
${
|
|
786
|
+
${$d}
|
|
790
787
|
const args = (${JSON.stringify(e.args??[])}).map(coerceArg);
|
|
791
788
|
await deployed.callTx.${e.circuit}(...args);
|
|
792
789
|
|
|
793
790
|
console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(e.circuit)} }));
|
|
794
791
|
rpcClose();
|
|
795
792
|
process.exit(0);
|
|
796
|
-
`}function
|
|
793
|
+
`}function Dg(e){return`
|
|
797
794
|
import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
|
|
798
795
|
setNetworkId(${JSON.stringify(e.networkConfig.networkId.toLowerCase())});
|
|
799
796
|
|
|
@@ -812,10 +809,10 @@ if (typeof contractMod.ledger !== 'function') {
|
|
|
812
809
|
}
|
|
813
810
|
|
|
814
811
|
process.stderr.write('Querying contract state...\\n');
|
|
815
|
-
const provider = indexerPublicDataProvider(
|
|
816
|
-
${JSON.stringify(e.networkConfig.indexer)},
|
|
817
|
-
${JSON.stringify(e.networkConfig.indexerWS??e.networkConfig.indexer.replace("http","ws"))},
|
|
818
|
-
);
|
|
812
|
+
const provider = indexerPublicDataProvider({
|
|
813
|
+
queryURL: ${JSON.stringify(e.networkConfig.indexer)},
|
|
814
|
+
subscriptionURL: ${JSON.stringify(e.networkConfig.indexerWS??e.networkConfig.indexer.replace("http","ws"))},
|
|
815
|
+
});
|
|
819
816
|
|
|
820
817
|
const contractState = await provider.queryContractState(${JSON.stringify(e.contractAddress)});
|
|
821
818
|
if (!contractState) {
|
|
@@ -856,106 +853,113 @@ for (const key of Object.keys(state)) {
|
|
|
856
853
|
|
|
857
854
|
console.log(JSON.stringify({ fields, maps }));
|
|
858
855
|
process.exit(0);
|
|
859
|
-
`}function
|
|
860
|
-
`,r?.(
|
|
861
|
-
|
|
862
|
-
|
|
856
|
+
`}function _g(e){if(!yo)return[];let t=[];if(!Jn(e)){try{Td(yo,e),t.push(e)}catch{}return t}for(let r of Pg){let n=Jr(yo,r),s=Jr(e,r);if(!Jn(n)||Jn(s))continue;try{Td(n,s),t.push(s)}catch{}}return t}async function So(e,t,r,n){let s=Jr(e,"node_modules"),o=_g(s),i=Jr(e,`.mn-contract-${Date.now()}.mjs`);xg(i,t);let a=()=>{try{Ad(i)}catch{}for(let c of o.slice().reverse())try{Ad(c)}catch{}};return new Promise((c,d)=>{let u=Eg("node",[i],{cwd:e,stdio:["ignore","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1",...n}}),l="",f="";u.stdout?.on("data",(p)=>{l+=p.toString()}),u.stderr?.on("data",(p)=>{let m=p.toString().trim();if(m)f+=m+`
|
|
857
|
+
`,r?.(m)}),u.on("close",(p)=>{if(a(),p!==0){d(Error(f.trim()||`Script exited with code ${p}`));return}c(l.trim())}),u.on("error",(p)=>{a(),d(p)})})}var yo,Id=`
|
|
858
|
+
import { createWalletProvider, createMidnightProvider, Transaction } from '@midnight-ntwrk/midnight-js-types';
|
|
859
|
+
import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils';
|
|
860
|
+
import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';
|
|
861
|
+
import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';
|
|
862
|
+
import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
|
|
863
|
+
import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';
|
|
864
|
+
`,Ng,$d,Pg;var qr=T(()=>{wo();yo=Tg();Ng=`
|
|
865
|
+
const resolvePrivateStateSecretKey = (${xd.toString()});
|
|
866
|
+
`;$d=`
|
|
863
867
|
const coerceArg = (${Vn.toString()});
|
|
864
|
-
`;
|
|
868
|
+
`;Pg=["@midnight-ntwrk","ws"]});import{indexerPublicDataProvider as $g}from"@midnight-ntwrk/midnight-js-indexer-public-data-provider";function Od(e){return $g({queryURL:e.indexer,subscriptionURL:e.indexerWS??e.indexer.replace("http","ws")})}var Md=()=>{};var Bd={};me(Bd,{default:()=>Ld});import{resolve as Xn}from"node:path";function zr(){return{update(){},stop(){},fail(){},log(){}}}function Og(e){return Fd.includes(e)}async function Ld(e,t){let r=e.subcommand;if(!r||!Og(r))throw new q(`Usage: midnight contract <${Fd.join("|")}>
|
|
865
869
|
|
|
866
870
|
inspect Show circuits, witnesses, and types for a compiled contract
|
|
867
871
|
deploy Deploy a contract to the network
|
|
868
872
|
call Call a circuit on a deployed contract
|
|
869
873
|
state Read the ledger state of a deployed contract
|
|
870
874
|
|
|
871
|
-
Run "midnight help contract" for more info.`);switch(r){case"inspect":return
|
|
872
|
-
`+
|
|
875
|
+
Run "midnight help contract" for more info.`);switch(r){case"inspect":return Mg(e);case"deploy":return Fg(e);case"call":return Ug(e);case"state":return Wg(e)}}function Yn(e){let t=C(e,"managed"),r=C(e,"path");return Xn(t??r??process.cwd())}async function Mg(e){let t=R(e,"json"),r=Yn(e),n=C(e,"name"),{info:s}=ct(r,n);if(t){I(Jc(s));return}if(process.stderr.write(`
|
|
876
|
+
`+W(`Contract: ${s.name}`)+`
|
|
873
877
|
|
|
874
|
-
`),process.stderr.write(
|
|
875
|
-
`),process.stderr.write(
|
|
876
|
-
`),process.stderr.write(
|
|
878
|
+
`),process.stderr.write(E("Compiler",s.compilerVersion)+`
|
|
879
|
+
`),process.stderr.write(E("Language",s.languageVersion)+`
|
|
880
|
+
`),process.stderr.write(E("Runtime",s.runtimeVersion)+`
|
|
877
881
|
`),process.stderr.write(`
|
|
878
882
|
`+P(" Circuits")+`
|
|
879
883
|
`),s.circuits.length===0)process.stderr.write(g(" (none)")+`
|
|
880
|
-
`);else for(let o of s.circuits){let i=
|
|
884
|
+
`);else for(let o of s.circuits){let i=Gc(o),a=Kc(o),c=o.pure?H(a):Y(a);process.stderr.write(` ${i} ${g("—")} ${c}
|
|
881
885
|
`)}if(process.stderr.write(`
|
|
882
886
|
`+P(" Witnesses")+`
|
|
883
887
|
`),s.witnesses.length===0)process.stderr.write(g(" (none)")+`
|
|
884
|
-
`);else for(let o of s.witnesses)process.stderr.write(` ${
|
|
888
|
+
`);else for(let o of s.witnesses)process.stderr.write(` ${Vc(o)}
|
|
885
889
|
`);if(s.siblings.length>0){process.stderr.write(`
|
|
886
890
|
`+P(" Other contracts in this project")+`
|
|
887
|
-
`);for(let o of s.siblings)process.stderr.write(` ${
|
|
891
|
+
`);for(let o of s.siblings)process.stderr.write(` ${H(o)}
|
|
888
892
|
`);process.stderr.write(`
|
|
889
893
|
`+g(" Inspect a sibling: mn contract inspect --name <name>")+`
|
|
890
894
|
`)}process.stderr.write(`
|
|
891
|
-
`)}async function
|
|
895
|
+
`)}async function bo(e,t){await Promise.resolve().then(() => Ae());let n=C(e,"network")??"undeployed",s={node:C(e,"node"),indexerWS:C(e,"indexer-ws"),proofServer:C(e,"proof-server")},{name:o,config:i}=ce({args:{command:"contract",subcommand:t,positionals:[],flags:{network:n,...ln(s)}}});return Ie(i,s,o),{network:n,networkConfig:i,endpoints:s}}async function Ud({network:e,networkConfig:t},r,n){await Promise.resolve().then(() => Me());await Promise.resolve().then(() => yt());await Promise.resolve();let c=ie(re(n)),d=Buffer.from(c.seed,"hex"),u=c.addresses[e],l=r?zr():G("Checking wallet..."),f=ve();try{let m=(await f.unshielded(u,t)).balances.get(mr)??0n;if(m===0n)throw l.fail("No NIGHT balance"),Error(`Wallet has 0 NIGHT on ${e}.
|
|
892
896
|
|
|
893
897
|
Fund your wallet before deploying:
|
|
894
898
|
Address: ${u}
|
|
895
899
|
`+(e==="undeployed"?` Run: midnight airdrop 1000
|
|
896
900
|
`:` Use the Midnight faucet or transfer from another wallet.
|
|
897
|
-
`));let
|
|
901
|
+
`));let h=await f.dust(d,t,{onStatus:(w)=>l.update(w)});if(h.balance===0n&&h.availableCoins===0)throw l.fail("No dust available"),Error(`Wallet has no dust on ${e}. Dust is required to pay transaction fees.
|
|
898
902
|
|
|
899
903
|
Register for dust generation:
|
|
900
904
|
Run: midnight dust register --network ${e}
|
|
901
905
|
Then wait: midnight dust status --network ${e}
|
|
902
|
-
`);
|
|
903
|
-
`+
|
|
906
|
+
`);l.stop(`Wallet OK (${m} NIGHT, dust available)`)}catch(p){throw l.fail("Wallet check failed"),p}}async function Wd({network:e,endpoints:t},r,n){await Promise.resolve().then(() => ho());let o=r?zr():G("Starting mn serve..."),i=await Gn({network:e,endpoints:t,wallet:n,onMessage:(a)=>o.update(a)});return o.stop("mn serve ready (port "+i.port+")"),{port:i.port,stop:()=>i.stop()}}async function Fg(e){let t=R(e,"json"),r=Xn(C(e,"path")??process.cwd()),n=Yn(e),s=C(e,"name");await Promise.resolve().then(() => qr());if(!t)process.stderr.write(`
|
|
907
|
+
`+W("Contract Deploy")+`
|
|
904
908
|
|
|
905
|
-
`);let{info:
|
|
906
|
-
`),process.stderr.write(
|
|
907
|
-
`),
|
|
909
|
+
`);let{info:i}=ct(n,s),a=i.witnesses.map((w)=>w.name);if(a.length>0){await Promise.resolve().then(() => wo());if(!Cd(r))throw Error(Ed({projectRoot:r,witnessNames:a}))}let c=await bo(e,"deploy"),{network:d,networkConfig:u}=c,l=C(e,"args"),f=[];if(l)try{let w=JSON.parse(l);f=Array.isArray(w)?w:Object.values(w)}catch(w){throw new q(`Invalid --args JSON: ${w.message}`)}let p=C(e,"secret-key");if(p!==void 0&&!/^[0-9a-fA-F]{64}$/.test(p))throw new q("--secret-key must be 32 bytes of hex (64 chars)");if(!t){if(process.stderr.write(E("Contract",i.name)+`
|
|
910
|
+
`),process.stderr.write(E("Network",d)+`
|
|
911
|
+
`),f.length>0)process.stderr.write(E("Constructor args",String(f.length))+`
|
|
908
912
|
`);process.stderr.write(`
|
|
909
|
-
`)}await
|
|
910
|
-
`),process.stderr.write(
|
|
913
|
+
`)}await Ud(c,t,C(e,"wallet"));let m=await Wd(c,t,C(e,"wallet")),h=t?zr():G("Deploying contract...");try{let w=await qn({dappDir:r,networkConfig:u,managedDir:i.managedDir,contractName:i.name,servePort:m.port,args:f,privateStateSecretKey:p,onMessage:(y)=>h.update(y)});if(h.stop(U("✓")+" Contract deployed"),t)I({subcommand:"deploy",contractName:i.name,address:w.contractAddress,network:d});else process.stderr.write(`
|
|
914
|
+
`),process.stderr.write(E("Address",w.contractAddress)+`
|
|
911
915
|
`),process.stderr.write(`
|
|
912
|
-
`+
|
|
913
|
-
`),
|
|
914
|
-
`)}catch(w){throw
|
|
916
|
+
`+U(" ✓ Deploy successful")+`
|
|
917
|
+
`),Lg(w.contractAddress,i.circuits,d),process.stdout.write(w.contractAddress+`
|
|
918
|
+
`)}catch(w){throw h.fail("Deploy failed"),w}finally{await m.stop()}}function Lg(e,t,r){let n=r==="undeployed"?"":` --network ${r}`;process.stderr.write(`
|
|
915
919
|
`+g(" Next:")+`
|
|
916
|
-
`),process.stderr.write(g(" mn contract state --address ")+
|
|
917
|
-
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(g(" mn contract call --address ")+
|
|
920
|
+
`),process.stderr.write(g(" mn contract state --address ")+H(e)+g(n)+`
|
|
921
|
+
`);let s=t.find((o)=>o.arguments.length===0);if(s)process.stderr.write(g(" mn contract call --address ")+H(e)+g(" --circuit ")+H(s.name)+g(n)+`
|
|
918
922
|
`);process.stderr.write(`
|
|
919
|
-
`)}async function
|
|
920
|
-
`+
|
|
923
|
+
`)}async function Ug(e){let t=R(e,"json"),r=Xn(C(e,"path")??process.cwd()),n=Yn(e),s=C(e,"name"),o=en(e,"address","contract address"),i=en(e,"circuit","circuit name"),a=C(e,"args");await Promise.resolve().then(() => qr());if(!t)process.stderr.write(`
|
|
924
|
+
`+W("Contract Call")+`
|
|
921
925
|
|
|
922
|
-
`);let{info:
|
|
923
|
-
`),process.stderr.write(
|
|
924
|
-
`),process.stderr.write(
|
|
926
|
+
`);let{info:d}=ct(n,s),u=[];if(a)try{let w=JSON.parse(a);u=Array.isArray(w)?w:Object.values(w)}catch(w){throw new q(`Invalid --args JSON: ${w.message}`)}let l=await bo(e,"call"),{network:f,networkConfig:p}=l;if(!t)process.stderr.write(E("Contract",d.name)+`
|
|
927
|
+
`),process.stderr.write(E("Circuit",i)+`
|
|
928
|
+
`),process.stderr.write(E("Address",o.slice(0,20)+"...")+`
|
|
925
929
|
|
|
926
|
-
`);await
|
|
927
|
-
`+
|
|
930
|
+
`);await Ud(l,t,C(e,"wallet"));let m=await Wd(l,t,C(e,"wallet")),h=t?zr():G(`Calling ${i}...`);try{let w=await zn({dappDir:r,networkConfig:p,managedDir:d.managedDir,contractName:d.name,contractAddress:o,circuit:i,args:u,servePort:m.port,onMessage:(y)=>h.update(y)});if(h.stop(U("✓")+` ${i} called`),t)I({subcommand:"call",contractName:d.name,circuit:i,address:o,network:f,status:w.status});else process.stderr.write(`
|
|
931
|
+
`+U(" ✓ Circuit call successful")+`
|
|
928
932
|
|
|
929
|
-
`)}catch(w){throw
|
|
930
|
-
`+
|
|
933
|
+
`)}catch(w){throw h.fail("Call failed"),w}finally{await m.stop()}}async function Wg(e){let t=R(e,"json"),r=Xn(C(e,"path")??process.cwd()),n=Yn(e),s=C(e,"name"),o=en(e,"address","contract address");await Promise.resolve().then(() => qr());let{network:a,networkConfig:c}=await bo(e,"state");if(!t)process.stderr.write(`
|
|
934
|
+
`+W("Contract State")+`
|
|
931
935
|
|
|
932
|
-
`),process.stderr.write(
|
|
933
|
-
`),process.stderr.write(
|
|
936
|
+
`),process.stderr.write(E("Address",o.slice(0,20)+"...")+`
|
|
937
|
+
`),process.stderr.write(E("Network",a)+`
|
|
934
938
|
|
|
935
|
-
`);let
|
|
936
|
-
`);for(let[
|
|
937
|
-
`);for(let[
|
|
939
|
+
`);let d=t?zr():G("Querying contract state...");try{let{info:u}=ct(n,s),l=await cr({dappDir:r,networkConfig:c,managedDir:u.managedDir,contractName:u.name,contractAddress:o,onMessage:(f)=>d.update(f)});if(d.stop(U("✓")+" State retrieved"),t)I({subcommand:"state",address:o,network:a,...l});else{let f=Object.keys(l.fields).length>0,p=Object.keys(l.maps).length>0;if(f||p){process.stderr.write(P(" Ledger State")+`
|
|
940
|
+
`);for(let[m,h]of Object.entries(l.fields))process.stderr.write(` ${m}: ${H(h)}
|
|
941
|
+
`);for(let[m,h]of Object.entries(l.maps))process.stderr.write(` ${m}: ${g(`Map (${h.size} entries)`)}
|
|
938
942
|
`)}else process.stderr.write(g(" (no ledger fields found)")+`
|
|
939
943
|
`);process.stderr.write(`
|
|
940
|
-
`)}}catch(u){
|
|
944
|
+
`)}}catch(u){d.stop(Y("⚠")+" Parsed state unavailable, showing raw");await Promise.resolve().then(() => Md());let p=await Od(c).queryContractState(o);if(!p)throw Error(`No contract found at address ${o} on ${a}`);let m=p.data??p;if(t)I({subcommand:"state",address:o,network:a,raw:m});else process.stderr.write(P(" Raw State")+`
|
|
941
945
|
`),process.stderr.write(g(" (run from dApp root for parsed ledger fields)")+`
|
|
942
|
-
`),process.stderr.write(` ${JSON.stringify(
|
|
946
|
+
`),process.stderr.write(` ${JSON.stringify(m).slice(0,200)}
|
|
943
947
|
|
|
944
|
-
`)}}var
|
|
945
|
-
Run this command from the root of a dApp project, or create a ${
|
|
946
|
-
Check the build log: ${i}`);if(await
|
|
947
|
-
Check the build log: ${i}`)}function
|
|
948
|
+
`)}}var Fd;var jd=T(()=>{ge();ze();ue();at();jn();Fd=["inspect","deploy","call","state"]});import{existsSync as dr,readFileSync as Xr,readdirSync as Bg}from"node:fs";import{join as Ot,resolve as jg}from"node:path";function Zn(e){let t=jg(e??process.cwd()),r=Ot(t,vo);if(!dr(r))throw Error(`No ${vo} found in ${t}
|
|
949
|
+
Run this command from the root of a dApp project, or create a ${vo} file.`);let n;try{n=JSON.parse(Xr(r,"utf-8"))}catch(o){throw Error(`Failed to parse ${r}: ${o.message}`)}return{config:Kg(n,r),configPath:r,dappDir:t}}function ko(e){let t=Ot(e,Hg);if(!dr(t))return[];let r=Bg(t,{withFileTypes:!0}),n=[];for(let s of r){if(!s.isDirectory())continue;let o=Ot(t,s.name),i=Ot(o,"suite.json");if(!dr(i))continue;let a;try{a=JSON.parse(Xr(i,"utf-8"))}catch(c){throw Error(`Failed to parse ${i}: ${c.message}`)}n.push({suite:Vg(a,i),suiteDir:o})}return n}function Jd(e){let t=Ot(e,"assertions.json");if(!dr(t))return null;let r;try{r=JSON.parse(Xr(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return Jg(r,t)}function qd(e){let t=Ot(e,"actions.json");if(!dr(t))return null;let r;try{r=JSON.parse(Xr(t,"utf-8"))}catch(n){throw Error(`Failed to parse ${t}: ${n.message}`)}return qg(r,t)}function zd(e){let t=Ot(e,"prompt.md");if(!dr(t))return null;return Xr(t,"utf-8")}function Kg(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&&!Hd.includes(r.network))throw Error(`${t}: "network" must be one of: ${Hd.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"||!Gg.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 Vg(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(!Gd.includes(r.strategy))throw Error(`${t}: "strategy" must be one of: ${Gd.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&&!Kd.includes(r.browserMode))throw Error(`${t}: "browserMode" must be one of: ${Kd.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 Jg(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 qg(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"||!Vd.includes(s.type))throw Error(`${t}: action "${s.id}" has invalid type "${s.type}". Valid: ${Vd.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",Hg="tests/suites",Hd,Gd,Kd,Gg,Vd;var Xd=T(()=>{Hd=["undeployed","preprod","preview"],Gd=["browser","cli","hybrid"],Kd=["dom","script","vision","auto"],Gg=/^(cache-clear|localnet-up|balance:\d+|dust|dust-register|dust-wait|mn-serve|build-and-serve)$/;Vd=["contract-deploy","contract-call","contract-state","wallet-cmd"]});function Yd(){let e=[];return{cleanups:e,addCleanup(t){e.push(t)}}}import{spawn as zg}from"node:child_process";import{createWriteStream as Xg}from"node:fs";import{join as Yg}from"node:path";import Zg from"node:http";import Qg from"node:net";async function Qd(e){let{dappDir:t,buildCmd:r,buildDir:n=".",port:s,url:o,logFile:i,timeoutMs:a=240000,onMessage:c=()=>{}}=e;if(await eh(s)){if(await Zd(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 th(s),await new Promise((h)=>setTimeout(h,2000))}let d=Yg(t,n),u=Xg(i,{flags:"a"}),l=zg("bash",["-lc",r],{cwd:d,stdio:["ignore","pipe","pipe"],detached:!1});l.stdout?.pipe(u),l.stderr?.pipe(u);let f=!1,p=null;l.on("exit",(h)=>{f=!0,p=h}),c(`Building (${r})...`);let m=Date.now()+a;while(Date.now()<m){if(f)throw Error(`Build process exited with code ${p} before the UI was ready.
|
|
950
|
+
Check the build log: ${i}`);if(await Zd(o))return c("UI ready"),{port:s,child:l,stop(){if(!f)l.kill("SIGTERM"),setTimeout(()=>{if(!f)l.kill("SIGKILL")},5000).unref();u.end()}};await new Promise((h)=>setTimeout(h,2000))}throw l.kill("SIGTERM"),u.end(),Error(`UI did not start within ${Math.round(a/1000)}s at ${o}
|
|
951
|
+
Check the build log: ${i}`)}function eh(e){return new Promise((t)=>{let r=new Qg.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 th(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 Zd(e){return new Promise((t)=>{let r=Zg.get(e,{timeout:3000},(n)=>{t(n.statusCode===200),n.resume()});r.on("error",()=>t(!1)),r.on("timeout",()=>{r.destroy(),t(!1)})})}var el=()=>{};import*as rl from"@midnightntwrk/ledger-v9";import{join as rh}from"node:path";async function nl(e,t,r,n){let s=[];for(let o of e.prep){let i=Date.now();n.onStepStart(o);try{await nh(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 nh(e,t,r,n,s){if(e==="cache-clear")return sh(t);if(e==="localnet-up")return oh(t,s);if(e.startsWith("balance:")){let o=parseInt(e.split(":")[1],10);return ih(o,t,s)}if(e==="dust"||e==="dust-register"||e==="dust-wait")return ah(t,s);if(e==="mn-serve")return ch(t,n,s);if(e==="build-and-serve")return dh(t,r,n,s);throw Error(`Unknown prep step: ${e}`)}async function sh(e){let t=e.network??"undeployed";Ge(void 0,t)}async function oh(e,t){let r=e.network??"undeployed",{config:n}=ce({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}});await ra(r,n),t.onMessage(`Using the ledger-9 stack at ${n.node} (indexer ${n.indexer})`)}async function ih(e,t,r){let n=t.network??"undeployed",{config:s}=ce({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:n}}});await Qe(n,s);let o=ie(re()),i=Buffer.from(o.seed,"hex"),a=o.addresses[n];r.onMessage("Checking balance...");let c=Te((m,h)=>{r.onMessage(`SDK: ${h}`)}),d=Pe(),u=wt(a,n),l=await Ye(i,s,u);try{let m=await ht(l,{syncMode:"lite",onProgress:(y,S)=>{if(S>0){let v=Math.min(Math.round(y/S*100),100);r.onMessage(`Syncing wallet... ${v}%`)}},onSyncDetail:(y)=>{r.onMessage(`Syncing wallet... (${y})`)}}),h=rl.unshieldedToken().raw,w=m.unshielded.balances[h]??0n;if(w>0n){r.onMessage(`Balance OK: ${w}`);try{await ot(a,n,l.facade)}catch{}return}}finally{d(),c();try{await Fe(l)}catch{}}if(n!=="undeployed")throw Error(`Wallet has 0 NIGHT on ${n}. Fund your wallet before running tests:
|
|
948
952
|
mn airdrop ${e} (if faucet available)
|
|
949
|
-
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let
|
|
953
|
+
Or transfer NIGHT from another wallet.`);r.onMessage(`Balance is 0. Airdropping ${e} NIGHT from genesis...`);let f=Buffer.from(rt,"hex"),p=Se(f,n);await er({seedBuffer:f,networkConfig:s,recipientAddress:a,amountNight:e,onSync(m,h){},onDust(m){r.onMessage(`Dust: ${m}`)},onProving(){r.onMessage("Generating ZK proof...")},onSubmitting(){r.onMessage("Submitting airdrop transaction...")},onSyncWarning(m,h){r.onMessage(`Syncing genesis... (${h})`)}}),r.onMessage(`Airdropped ${e} NIGHT`)}async function ah(e,t){let r=e.network??"undeployed",{config:n}=ce({args:{command:"test",subcommand:void 0,positionals:[],flags:{network:r}}});await Qe(r,n);let s=ie(re()),o=Buffer.from(s.seed,"hex"),i=s.addresses[r],a=Te(),c=Pe(),d=wt(i,r),u=await Ye(o,n,d);try{if(t.onMessage("Syncing wallet..."),await ht(u,{syncMode:"lite"}),t.onMessage("Ensuring dust..."),(await et(u,(m)=>t.onMessage(`Dust: ${m}`))).alreadyAvailable){t.onMessage("Dust already available");try{await ot(i,r,u.facade)}catch{}return}t.onMessage("Dust registered. Waiting for coins to become available...");let f=await bn(u,tl);if(!Rt(f)){if(r!=="undeployed")throw Error(`Dust not available on ${r}. Register dust and wait for it to generate:
|
|
950
954
|
mn dust register
|
|
951
|
-
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${
|
|
952
|
-
`).filter(Boolean);e(`Found ${r.length} orphan chrome-devtools-mcp Chrome process(es), killing`);for(let n of r)try{
|
|
955
|
+
mn dust status (check until dustAvailable: true)`);throw Error(`Dust not available after ${tl/1000}s. The chain may be slow — try again.`)}t.onMessage("Dust is available");try{await ot(i,r,u.facade)}catch{}}finally{c(),a();try{await Fe(u)}catch{}}}async function ch(e,t,r){r.onMessage("Starting mn serve...");let n=await Gn({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 dh(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=rh(t,"tests","results",`build_${Date.now()}.log`),a=await Qd({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 tl=90000;var sl=T(()=>{It();Me();Ae();zt();He();It();_t();Be();ho();el()});import{execSync as ol,spawn as lh}from"node:child_process";import{createWriteStream as uh,existsSync as ph,mkdirSync as fh,readFileSync as mh}from"node:fs";import{dirname as gh,join as hh}from"node:path";import{homedir as wh}from"node:os";function yh(){let e=hh(wh(),".claude.json");if(!ph(e))return!1;try{let t=JSON.parse(mh(e,"utf-8"));return Boolean(t.mcpServers?.["chrome-devtools"])}catch{return!1}}function bh(e){let t;try{t=ol(`ps -ax -o pid,command | grep "${Sh}" | grep -v grep | awk '{print $1}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return}if(!t)return;let r=t.split(`
|
|
956
|
+
`).filter(Boolean);e(`Found ${r.length} orphan chrome-devtools-mcp Chrome process(es), killing`);for(let n of r)try{ol(`kill ${n}`,{stdio:"pipe"})}catch{}}function Co(e){let t=e.browserMode??"vision";if(t==="auto")return"vision";return t}async function il(e){let{suite:t,prompt:r,dappDir:n,logFile:s,onMessage:o=()=>{}}=e,i=(t.timeout??600)*1000,a=Co(t);if(a==="dom"||a==="script"){if(!yh())throw Error(`Browser mode "${a}" requires the chrome-devtools MCP server, which is not registered in ~/.claude.json.
|
|
953
957
|
|
|
954
958
|
Install it:
|
|
955
959
|
claude mcp add chrome-devtools --scope user npx chrome-devtools-mcp@latest
|
|
956
960
|
|
|
957
|
-
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");
|
|
958
|
-
`),s}function
|
|
961
|
+
Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision" `+"(no MCP needed, but slower — uses screenshots).");bh(o)}fh(gh(s),{recursive:!0});let c=uh(s),d=[];if(a==="vision")d.push("--chrome");if(d.push("--dangerously-skip-permissions"),t.model)d.push("--model",t.model);if(t.effort)d.push("--effort",t.effort);let u=r;if(a==="dom")u=vh+r;else if(a==="script")u=kh+r;return d.push("-p",u),o(`Launching Claude (mode: ${a}, model: ${t.model??"default"}, timeout: ${t.timeout??600}s)`),new Promise((l)=>{let f=lh("claude",d,{cwd:n,stdio:["inherit","pipe","inherit"]}),p=!1;f.stdout?.on("data",(h)=>{process.stdout.write(h),c.write(h)});let m=setTimeout(()=>{p=!0,o(`Timeout: test exceeded ${t.timeout??600}s`),f.kill("SIGTERM"),setTimeout(()=>{if(!f.killed)f.kill("SIGKILL")},1e4).unref()},i);f.on("close",(h)=>{clearTimeout(m),c.end(),l({exitCode:h??1,logFile:s,timedOut:p})}),f.on("error",(h)=>{clearTimeout(m),c.end(),o(`Claude process error: ${h.message}`),l({exitCode:1,logFile:s,timedOut:!1})})})}var Sh="chrome-devtools-mcp/chrome-profile",vh="## 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",kh="## 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 al=()=>{};import{existsSync as Ch,readFileSync as Eh}from"node:fs";import xh from"node:net";async function cl(e,t){let r=[];for(let n of e)try{let s=await Ah(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 Ah(e,t){switch(e.type){case"balance-changed":return Th(e,t);case"process-exit-code":return Nh(e,t);case"port-listening":return Rh(e);case"agent-report-no-failure":return Dh(e,t);default:throw Error(`Unsupported assertion type: "${e.type}" (available in v2)`)}}function Th(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 Nh(e,t){if(t.processExitCode===void 0)throw Error("Process exit code not available");let r=e.params.code;return t.processExitCode===r}function Rh(e){let t=e.params.port;return new Promise((r)=>{let n=new xh.Socket;n.setTimeout(2000),n.on("connect",()=>{n.destroy(),r(!0)}),n.on("timeout",()=>{n.destroy(),r(!1)}),n.on("error",()=>{r(!1)}),n.connect(t,"127.0.0.1")})}function Dh(e,t){let r=e.params??{},n=r.logPath??t.agentLogPath;if(!n||!Ch(n))return!0;let s;try{s=Eh(n,"utf-8")}catch{return!0}let o=_h(s),i=r.markers??Ih;for(let a of i)if(Ph(o,a))return!1;return!0}function Ph(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 _h(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"")}var Ih;var dl=T(()=>{Ih=["FAILED","❌","did not pass","test failed","overall: fail","result: fail"]});import{existsSync as $h,mkdirSync as Oh,writeFileSync as Mh,readFileSync as Fh,readdirSync as Lh}from"node:fs";import{join as Qn}from"node:path";function ul(e,t){let r=Qn(t,ll);Oh(r,{recursive:!0});let n=`${e.suite}_${e.timestamp.replace(/[:.]/g,"-")}.json`,s=Qn(r,n);return Mh(s,JSON.stringify(e,null,2)+`
|
|
962
|
+
`),s}function pl(e,t){let r=Eo(e,t);return r.length>0?r[0]:null}function Eo(e,t){let r=Qn(e,ll);if(!$h(r))return[];let n=Lh(r).filter((o)=>o.endsWith(".json")).filter((o)=>!t||o.startsWith(t+"_")),s=[];for(let o of n)try{let i=Fh(Qn(r,o),"utf-8");s.push(JSON.parse(i))}catch{}return s.sort((o,i)=>i.timestamp.localeCompare(o.timestamp)),s}var ll="tests/results";var fl=()=>{};import{execSync as Uh}from"node:child_process";async function xo(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)Wh(e.buildHandle.port,t)}function Wh(e,t){try{Uh(`osascript -e 'tell application "Google Chrome"
|
|
959
963
|
repeat with theWindow in every window
|
|
960
964
|
repeat with theTab in every tab of theWindow
|
|
961
965
|
if URL of theTab contains "localhost:${e}" then
|
|
@@ -963,7 +967,7 @@ Then re-run the suite. Alternatively, switch the suite to "browserMode": "vision
|
|
|
963
967
|
end if
|
|
964
968
|
end repeat
|
|
965
969
|
end repeat
|
|
966
|
-
end tell'`,{timeout:5000,stdio:"pipe"}),t?.(`Closed Chrome tabs for localhost:${e}`)}catch{}}var
|
|
970
|
+
end tell'`,{timeout:5000,stdio:"pipe"}),t?.(`Closed Chrome tabs for localhost:${e}`)}catch{}}var ml=()=>{};function gl(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(gl);default:return null}}function Ao(e){let t={};for(let r of e.arguments)t[r.name]=gl(r.type);return t}function To(e,t){if((t.strategy??"cli")==="browser"){if(!t.browser)throw Error("Browser strategy requires browser options (port, buildCmd, buildDir?, url?)");return Jh(t,t.browser)}return Vh(e,t)}function Vh(e,t){let r=t.suiteName??Bh,n=t.network??hl,s=t.servePort??wl;return{dappConfig:{name:t.contractName,network:n,prep:yl},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??Hh},actions:{actions:zh(e)},assertions:{post:[Sl(s)]},prompt:null,suiteName:r}}function Jh(e,t){let r=e.suiteName??jh,n=e.network??hl,s=e.servePort??wl,o=t.url??`http://localhost:${t.port}/`,i={name:e.contractName,network:n,port:t.port,buildCmd:t.buildCmd,url:o,prep:Kh};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??Gh,...t.browserMode?{browserMode:t.browserMode}:{}},actions:null,assertions:{post:[{id:"claude-exit-ok",type:"process-exit-code",params:{code:0},expect:"pass"},Sl(s),{id:"agent-no-failure",type:"agent-report-no-failure",params:{},expect:"pass"}]},prompt:qh(e.contractName,o),suiteName:r}}function Sl(e){return{id:"serve-port-listening",type:"port-listening",params:{port:e},expect:"pass"}}function qh(e,t){return`You are running an automated E2E test of ${e}.
|
|
967
971
|
|
|
968
972
|
The UI is at ${t} — open it in Chrome.
|
|
969
973
|
mn serve is running with --approve-all so contract calls will auto-approve.
|
|
@@ -993,44 +997,44 @@ Follow these steps:
|
|
|
993
997
|
|
|
994
998
|
If any step fails, report exactly what you see on screen and stop.
|
|
995
999
|
Take screenshots at each major step to document the test.
|
|
996
|
-
`}function
|
|
1000
|
+
`}function zh(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=Ao(n);t.push(s)}return t.push({id:"check-final",type:"contract-state"}),t}var hl="undeployed",Bh="cli-default",jh="ui-default",Hh=300,Gh=600,wl=9932,yl,Kh;var No=T(()=>{yl=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Kh=[...yl,"build-and-serve"]});import{existsSync as vl,mkdirSync as Xh,readFileSync as Yh,writeFileSync as bl}from"node:fs";import{join as lr}from"node:path";function kl(e,t){let{dappDir:r,force:n=!1}=t,s=lr(r,"tests","suites",e.suiteName),o=lr(r,"dapp.test.json"),i=[{path:lr(s,"suite.json"),kind:"json",body:e.suite},{path:lr(s,"assertions.json"),kind:"json",body:e.assertions}];if(e.actions)i.push({path:lr(s,"actions.json"),kind:"json",body:e.actions});if(e.prompt)i.push({path:lr(s,"prompt.md"),kind:"text",body:e.prompt});if(!n){let u=i.filter((l)=>vl(l.path)).map((l)=>l.path);if(u.length>0)throw Error(`Suite "${e.suiteName}" already exists at ${s}.
|
|
997
1001
|
Pick a different suite name (--suite <name>) or pass --force to overwrite.
|
|
998
1002
|
Existing files:
|
|
999
|
-
`+
|
|
1000
|
-
`))}let a=
|
|
1001
|
-
`),c.push(o);else d.push(o);for(let
|
|
1002
|
-
`:
|
|
1003
|
-
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
|
|
1004
|
-
`+
|
|
1005
|
-
`);for(;;){let e=(await
|
|
1006
|
-
`))}}async function
|
|
1003
|
+
`+u.map((l)=>` - ${l}`).join(`
|
|
1004
|
+
`))}let a=Zh(o,e,n);Xh(s,{recursive:!0});let c=[],d=[];if(a.action==="write")bl(o,JSON.stringify(e.dappConfig,null,2)+`
|
|
1005
|
+
`),c.push(o);else d.push(o);for(let u of i){let l=u.kind==="json"?JSON.stringify(u.body,null,2)+`
|
|
1006
|
+
`:u.body;bl(u.path,l),c.push(u.path)}return{written:c,preserved:d}}function Zh(e,t,r){if(r||!vl(e))return{action:"write"};let n;try{n=JSON.parse(Yh(e,"utf-8"))}catch(s){let o=s instanceof Error?s.message:String(s);throw Error(`${e} exists but is not valid JSON: ${o}
|
|
1007
|
+
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 Cl=()=>{};import{existsSync as xl,readdirSync as Qh,readFileSync as ew,statSync as tw}from"node:fs";import{basename as rw,extname as nw,join as Al,relative as sw}from"node:path";function Tl(e){let t=new Map;for(let r of ow){let n=Al(e,r);if(!xl(n))continue;Ro(n,e,t)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function Nl(e,t=e){if(!xl(e))return[];let r=new Map;return Ro(e,t,r),[...r.values()].sort((n,s)=>n.name.localeCompare(s.name))}function Ro(e,t,r){let n;try{n=Qh(e)}catch{return}for(let s of n){let o=Al(e,s),i;try{i=tw(o)}catch{continue}if(i.isDirectory()){if(iw.has(s.toLowerCase()))continue;Ro(o,t,r);continue}if(nw(s)!==El)continue;if(s.endsWith(".test.tsx")||s.endsWith(".spec.tsx"))continue;let a=rw(s,El);if(!aw(a,o))continue;let c=dw(a);if(r.has(c))continue;r.set(c,{name:c,component:a,path:o,relativePath:sw(t,o)})}}function aw(e,t){if(!/^[A-Z][A-Za-z0-9]*$/.test(e))return!1;let r;try{r=ew(t,"utf-8")}catch{return!1}return cw.test(r)}function dw(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}var ow,El=".tsx",iw,cw;var Io=T(()=>{ow=["src/components","src/pages","src/screens","src/views"];iw=new Set(["layout","layouts","shared","common","ui","icons","styles"]);cw=/\bexport\s+(default\b|const\s+[A-Z]|function\s+[A-Z])/});import{existsSync as lw,statSync as uw}from"node:fs";import*as Rl from"node:readline";function Il(){return process.stdin.isTTY===!0}function Ke(e,t){let r=Rl.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 Dl(){process.stderr.write(`
|
|
1008
|
+
`+H("Test scaffold setup")+`
|
|
1009
|
+
`);for(;;){let e=(await Ke("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".
|
|
1010
|
+
`))}}async function Pl(e={}){process.stderr.write(`
|
|
1007
1011
|
`+g("Browser test scaffold needs your dApp UI details:")+`
|
|
1008
|
-
`);let t=e.port!==void 0?String(e.port):await
|
|
1009
|
-
`+
|
|
1012
|
+
`);let t=e.port!==void 0?String(e.port):await Ke("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 Ke("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 Ke("Build dir (blank for project root)",""),o=s===""?void 0:s,i=e.url??await Ke("URL",`http://localhost:${r}/`),a=e.browserMode??await pw();return{port:r,buildCmd:n,buildDir:o,url:i,browserMode:a}}async function pw(){process.stderr.write(`
|
|
1013
|
+
`+H("Browser mode — how should Claude perceive the page?")+`
|
|
1010
1014
|
`),process.stderr.write(` ${g("1.")} dom ${g("— accessibility tree (text). Fast. HTML / React / Vue UIs.")}
|
|
1011
1015
|
`),process.stderr.write(` ${g("2.")} vision ${g("— screenshots. Slow. Canvas games (no DOM).")}
|
|
1012
1016
|
`),process.stderr.write(` ${g("3.")} script ${g("— direct JS. Fastest. Needs dApp-side hooks (advanced).")}
|
|
1013
1017
|
`),process.stderr.write(g(` dom and script need chrome-devtools-mcp installed.
|
|
1014
|
-
`));for(;;){let e=(await
|
|
1015
|
-
`))}}async function
|
|
1018
|
+
`));for(;;){let e=(await Ke("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(Y(` Pick 1 (dom), 2 (vision), or 3 (script).
|
|
1019
|
+
`))}}async function _l(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.
|
|
1016
1020
|
`));return}process.stderr.write(`
|
|
1017
|
-
`+
|
|
1021
|
+
`+H("Pick the circuit this suite will exercise:")+`
|
|
1018
1022
|
`);for(let r=0;r<t.length;r++)process.stderr.write(` ${g(`${r+1}.`)} ${t[r].name}
|
|
1019
1023
|
`);process.stderr.write(g(` (or type "skip" to scaffold all circuits without AI)
|
|
1020
|
-
`));for(;;){let r=(await
|
|
1021
|
-
`))}}async function
|
|
1022
|
-
`+
|
|
1024
|
+
`));for(;;){let r=(await Ke("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".
|
|
1025
|
+
`))}}async function Do(e){if(e.length===0)return fw();process.stderr.write(`
|
|
1026
|
+
`+H("Pick the screen this suite will test:")+`
|
|
1023
1027
|
`);for(let t=0;t<e.length;t++)process.stderr.write(` ${g(`${t+1}.`)} ${e[t].name} ${g(`(${e[t].relativePath})`)}
|
|
1024
1028
|
`);process.stderr.write(g(` (or type "skip" to scaffold a generic prompt.md without AI)
|
|
1025
|
-
`));for(;;){let t=(await
|
|
1026
|
-
`))}}async function
|
|
1029
|
+
`));for(;;){let t=(await Ke("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".
|
|
1030
|
+
`))}}async function fw(){process.stderr.write(g(`
|
|
1027
1031
|
Could not auto-discover screens (no src/components, src/pages, or src/screens under the build dir).
|
|
1028
|
-
`));for(;;){let e=(await
|
|
1029
|
-
`));continue}let t;try{t=
|
|
1030
|
-
`));continue}if(t.isDirectory()){let r=
|
|
1031
|
-
`));continue}return
|
|
1032
|
-
`));continue}return
|
|
1033
|
-
`))}}function
|
|
1032
|
+
`));for(;;){let e=(await Ke('Path to a .tsx file or a UI directory (or "skip")')).trim();if(e.toLowerCase()==="skip"||e==="")return;if(!lw(e)){process.stderr.write(g(` No such path: ${e}
|
|
1033
|
+
`));continue}let t;try{t=uw(e)}catch{process.stderr.write(g(` Cannot stat: ${e}
|
|
1034
|
+
`));continue}if(t.isDirectory()){let r=Nl(e);if(r.length===0){process.stderr.write(g(` No PascalCase .tsx components in ${e}
|
|
1035
|
+
`));continue}return Do(r)}if(!e.endsWith(".tsx")){process.stderr.write(g(` Not a .tsx file: ${e}
|
|
1036
|
+
`));continue}return gw(e)}}async function $l(){let e=(await Ke("What does success look like? (one line, optional)")).trim();return e===""?void 0:e}async function Po(e){for(;;){let t=(await Ke("Suite name",e)).trim();if(mw(t))return t;process.stderr.write(Y(` Suite names must be kebab-case (a–z, 0–9, dashes, underscores). Try again.
|
|
1037
|
+
`))}}function mw(e){return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e)}function gw(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 Ol=T(()=>{Io()});function Ll(e){let{contractName:t,contractSummary:r,contractSource:n,targetCircuit:s,goal:o,witnessDependentCircuits:i}=e,a=i&&i.size>0?`
|
|
1034
1038
|
## Circuits NOT testable from a CLI suite
|
|
1035
1039
|
|
|
1036
1040
|
These circuits call witnesses that read from private state. In a
|
|
@@ -1038,7 +1042,7 @@ CLI test the private state is empty (no UI to populate it), so
|
|
|
1038
1042
|
they crash with "Cannot read properties of undefined". Do NOT
|
|
1039
1043
|
include them as actions, even as setup steps:
|
|
1040
1044
|
|
|
1041
|
-
`+[...i.entries()].map(([l
|
|
1045
|
+
`+[...i.entries()].map(([u,l])=>` - ${u} (uses ${l.join(", ")})`).join(`
|
|
1042
1046
|
`)+`
|
|
1043
1047
|
${s&&i.has(s.name)?`
|
|
1044
1048
|
The user explicitly asked for "${s.name}" — try anyway,
|
|
@@ -1051,7 +1055,7 @@ Focus this suite on ONE circuit:
|
|
|
1051
1055
|
|
|
1052
1056
|
Circuit: ${s.name} (${s.pure?"pure":"impure"})
|
|
1053
1057
|
Args:
|
|
1054
|
-
${s.arguments.length===0?" (takes no arguments)":s.arguments.map((
|
|
1058
|
+
${s.arguments.length===0?" (takes no arguments)":s.arguments.map((u)=>` - ${u.name}: ${u.type["type-name"]}`).join(`
|
|
1055
1059
|
`)}
|
|
1056
1060
|
${e.startingArgs&&Object.keys(e.startingArgs).length>0?`
|
|
1057
1061
|
Starting args (REQUIRED — keep these exact field names; replace
|
|
@@ -1135,12 +1139,12 @@ Args coercion the runner applies (so JSON arg values can be):
|
|
|
1135
1139
|
- [0..255] int array → Uint8Array for Bytes<N>
|
|
1136
1140
|
- object → recurses into Struct fields
|
|
1137
1141
|
|
|
1138
|
-
${
|
|
1142
|
+
${Fl}
|
|
1139
1143
|
|
|
1140
|
-
Now produce the JSON.`}function
|
|
1141
|
-
--- ${
|
|
1142
|
-
${
|
|
1143
|
-
--- end ${
|
|
1144
|
+
Now produce the JSON.`}function Ul(e){let{contractName:t,contractSummary:r,screenComponent:n,screenSource:s,relatedSources:o,url:i,goal:a}=e,c=(o??[]).map((l)=>`
|
|
1145
|
+
--- ${l.path} ---
|
|
1146
|
+
${l.source}
|
|
1147
|
+
--- end ${l.path} ---`).join(`
|
|
1144
1148
|
`),d=n&&s?`## Target screen
|
|
1145
1149
|
|
|
1146
1150
|
Component: ${n}
|
|
@@ -1170,7 +1174,7 @@ Conventional patterns Midnight dApps follow that you can rely on:
|
|
|
1170
1174
|
- Toast or inline error messages on failure.
|
|
1171
1175
|
|
|
1172
1176
|
Use generic-but-specific selectors (\`getByRole('button', { name: /connect wallet/i })\`)
|
|
1173
|
-
in the prompt steps, since you don't have the actual JSX.`,
|
|
1177
|
+
in the prompt steps, since you don't have the actual JSX.`,u=a?`Success criterion (from the user):
|
|
1174
1178
|
> ${a}
|
|
1175
1179
|
`:n?`No specific success criterion was given. Infer one from the screen source: what is the obvious "happy path" outcome a user would see on success?
|
|
1176
1180
|
`:`No specific success criterion was given. Infer one from the contract circuits: what is the obvious "happy path" outcome the dApp exists to support?
|
|
@@ -1180,7 +1184,7 @@ drives Chrome and follows a prompt.md file.
|
|
|
1180
1184
|
|
|
1181
1185
|
${d}
|
|
1182
1186
|
|
|
1183
|
-
${
|
|
1187
|
+
${u}
|
|
1184
1188
|
|
|
1185
1189
|
## Contract context (so you know what circuits the dApp calls)
|
|
1186
1190
|
|
|
@@ -1214,104 +1218,104 @@ A JSON object with three keys:
|
|
|
1214
1218
|
chain (e.g. ledger-field on a contract-state read).
|
|
1215
1219
|
- description: one short sentence summarising what this suite verifies.
|
|
1216
1220
|
|
|
1217
|
-
${
|
|
1221
|
+
${Fl}
|
|
1218
1222
|
|
|
1219
|
-
Now produce the JSON.`}function
|
|
1220
|
-
`)}var
|
|
1223
|
+
Now produce the JSON.`}function _o(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(`
|
|
1224
|
+
`)}var Ml="```json",Fl;var Wl=T(()=>{Fl=`Output rules:
|
|
1221
1225
|
- Reply with EXACTLY one ${"```json"} ... \`\`\` fenced code block.
|
|
1222
1226
|
- Inside the fence: valid JSON, nothing else (no comments, no trailing text).
|
|
1223
1227
|
- Fields you don't know about: omit them. Don't invent fields.
|
|
1224
1228
|
- Use only the circuit / ledger field names that appear in the inputs below.
|
|
1225
|
-
- Be concise — fewer, well-named actions beat many vague ones.`});var dl={};L(dl,{analyzeWitnessDependencies:()=>Mr});function Mr(e,t){if(t.length===0)return{byCircuit:new Map};let r=Hh(e),n=Gh(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 Jh(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 Hh(e){return e.replace(jh,"").replace(Bh,"")}function Gh(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=Kh(i);t.set(o,{body:u,argNames:p,isCircuit:s==="circuit"})}return t}function Kh(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 Jh(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(Vh.has(o)||t.has(o))continue;r.add(o)}return r}var Bh,jh,Vh;var rs=R(()=>{Bh=/\/\/[^\n]*/g,jh=/\/\*[\s\S]*?\*\//g;Vh=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var Sl={};L(Sl,{claudeSubprocessRunner:()=>Ko,findContractSourcePath:()=>Jo,generateCliScaffoldWithAI:()=>ow,generateUiScaffoldWithAI:()=>iw,isClaudeAvailable:()=>ew});import{execFileSync as zh,spawn as qh}from"node:child_process";import{existsSync as Go,readdirSync as Xh,readFileSync as pl}from"node:fs";import{dirname as nr,join as ns}from"node:path";function ew(){try{return zh("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function hl(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${sl} ... \`\`\` 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 tw(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=nw(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)"}`);rw(s,o)}return{actions:r}}function rw(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 nw(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 sw(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 ow(e,t=Ko){let r=e.contractSourcePath&&Go(e.contractSourcePath)?pl(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?Mr(r,n).byCircuit:new Map,o=e.targetCircuit?ts(e.targetCircuit):void 0,i=il({contractName:e.contract.name,contractSummary:Ho({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=hl(a),d=tw(c,e.contract),l=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${yl(e.goal)??"ai"}`),u=e.network??fl,p=e.servePort??ml,m={name:e.contract.name,network:u,prep:gl},h={name:l,description:c.description,strategy:"cli",timeout:Yh},f=aw(c.assertions,p),w=[...s.entries()].filter(([y])=>y!==e.targetCircuit?.name).map(([y,S])=>({name:y,reason:`uses witness ${S.join(", ")} (private state — UI-only)`}));return{dappConfig:m,suite:h,actions:d,assertions:f,prompt:null,suiteName:l,excludedCircuits:w.length>0?w:void 0}}async function iw(e,t=Ko){let r=e.screen?pl(e.screen.path,"utf-8"):void 0,n=al({contractName:e.contract.name,contractSummary:Ho({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=hl(s);sw(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${yl(e.goal)??"ai"}`),a=e.network??fl,c=e.servePort??ml,d=e.url,l={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:Qh};if(e.buildDir)l.buildDir=e.buildDir;let u={name:i,description:o.description,strategy:"browser",timeout:Zh,...e.browserMode?{browserMode:e.browserMode}:{}},p=cw(o.assertions,c);return{dappConfig:l,suite:u,actions:null,assertions:p,prompt:o.prompt,suiteName:i}}function wl(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function aw(e,t){if(e.post.some((n)=>n.type==="port-listening"&&wl(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function cw(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"&&wl(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 yl(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 Jo(e){let t=e.split("/").pop(),r=[nr(e),ns(nr(e),"src"),nr(nr(e)),ns(nr(nr(e)),"src")];for(let n of r){if(!Go(n))continue;if(t){let i=ns(n,`${t}.compact`);if(Go(i))return i}let s;try{s=Xh(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return ns(n,o)}return}var fl="undeployed",ml=9932,Yh=300,Zh=600,gl,Qh,ll=300000,ul=4194304,Ko=(e)=>new Promise((t,r)=>{let n=qh("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${ll/1000}s`))},ll);n.stdout?.on("data",(d)=>{if(i+=d.length,i>ul){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 ${ul/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 Vo=R(()=>{cl();Lo();rs();gl=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Qh=[...gl,"build-and-serve"]});var El={};L(El,{diffState:()=>yw,runActions:()=>uw});import{existsSync as bl,readFileSync as vl,writeFileSync as dw,mkdirSync as lw}from"node:fs";import{join as kl}from"node:path";async function uw(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=Sw(n,s,p);let{info:h}=mt(n),f=ww(h),w;for(let y of t){c?.(y);let S=Date.now();if(w&&(y.type==="contract-call"||y.type==="contract-state")){let b={id:y.id,type:y.type,status:"skip",duration:0,message:`cascaded skip — depends on ${w}`};u.push(b),d?.(y,b);continue}try{let b=await pw(y,{dappDir:n,networkConfig:o,managedDir:h.managedDir,contractName:h.name,servePort:i,contractAddress:m,witnessDeps:f,onMessage:l});if(b.contractAddress){if(m=b.contractAddress,bw(n,s,p,m),y.type==="contract-deploy")w=void 0}let v=Date.now()-S,x={...b,duration:v};if(u.push(x),d?.(y,x),b.status==="skip"&&y.type==="contract-call")w=`skipped action "${y.id}"`}catch(b){let v=Date.now()-S,x={id:y.id,type:y.type,status:"fail",duration:v,message:b.message};u.push(x),d?.(y,x);break}}return u}async function pw(e,t){switch(e.type){case"contract-deploy":return fw(e,t);case"contract-call":return mw(e,t);case"contract-state":return gw(e,t);case"wallet-cmd":return hw(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function fw(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 Io({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 mw(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 Pr({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 Do({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 Pr({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 gw(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await Pr({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)zo(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);zo(s,a,o,n)}catch{zo(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1229
|
+
- Be concise — fewer, well-named actions beat many vague ones.`});function ur(e,t){if(t.length===0)return{byCircuit:new Map};let r=yw(e),n=Sw(r);if(n.size===0)return{byCircuit:new Map};let s=new Set(t),o=new Map,i=new Map;for(let[d,u]of n){o.set(d,new Set),i.set(d,new Set);for(let l of vw(u.body,u.argNames))if(s.has(l))o.get(d).add(l);else if(n.has(l))i.get(d).add(l)}let a=!0;while(a){a=!1;for(let[d,u]of i){let l=o.get(d);for(let f of u)for(let p of o.get(f)??[])if(!l.has(p))l.add(p),a=!0}}let c=new Map;for(let[d,u]of n){if(!u.isCircuit)continue;let l=o.get(d);if(l&&l.size>0)c.set(d,[...l].sort())}return{byCircuit:c}}function yw(e){return e.replace(ww,"").replace(hw,"")}function Sw(e){let t=new Map,r=/\b(circuit|function)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gms,n;while((n=r.exec(e))!==null){let s=n[1],o=n[2],i=n[3],a=n.index+n[0].length,c=e.indexOf("{",a);if(c<0)continue;let d=1,u=c+1;for(;u<e.length&&d>0;u++){let p=e[u];if(p==="{")d++;else if(p==="}")d--}if(d!==0)continue;let l=e.slice(c+1,u-1),f=bw(i);t.set(o,{body:l,argNames:f,isCircuit:s==="circuit"})}return t}function bw(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 vw(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(kw.has(o)||t.has(o))continue;r.add(o)}return r}var hw,ww,kw;var es=T(()=>{hw=/\/\/[^\n]*/g,ww=/\/\*[\s\S]*?\*\//g;kw=new Set(["if","for","while","switch","return","new","assert","disclose","transientHash","persistentHash","ownPublicKey","publicKey","Map","Set","Vector","Tuple","Option","Bytes","Field","Uint","Boolean"])});var Xl={};me(Xl,{claudeSubprocessRunner:()=>Oo,findContractSourcePath:()=>Mo,generateCliScaffoldWithAI:()=>$w,generateUiScaffoldWithAI:()=>Ow,isClaudeAvailable:()=>Rw});import{execFileSync as Cw,spawn as Ew}from"node:child_process";import{existsSync as $o,readdirSync as xw,readFileSync as Hl}from"node:fs";import{dirname as pr,join as ts}from"node:path";function Rw(){try{return Cw("claude",["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function Jl(e){let r=new RegExp("```json\\s*\\n([\\s\\S]*?)\\n```").exec(e);if(!r)throw Error(`Claude response did not contain a ${Ml} ... \`\`\` 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 Iw(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=Pw(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)"}`);Dw(s,o)}return{actions:r}}function Dw(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 Pw(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 _w(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 $w(e,t=Oo){let r=e.contractSourcePath&&$o(e.contractSourcePath)?Hl(e.contractSourcePath,"utf-8"):void 0,n=e.contract.witnesses.map((y)=>y.name),s=r?ur(r,n).byCircuit:new Map,o=e.targetCircuit?Ao(e.targetCircuit):void 0,i=Ll({contractName:e.contract.name,contractSummary:_o({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=Jl(a),d=Iw(c,e.contract),u=e.suiteName??(e.targetCircuit?`cli-${e.targetCircuit.name.toLowerCase().replace(/_/g,"-")}`:`cli-${zl(e.goal)??"ai"}`),l=e.network??Gl,f=e.servePort??Kl,p={name:e.contract.name,network:l,prep:Vl},m={name:u,description:c.description,strategy:"cli",timeout:Aw},h=Mw(c.assertions,f),w=[...s.entries()].filter(([y])=>y!==e.targetCircuit?.name).map(([y,S])=>({name:y,reason:`uses witness ${S.join(", ")} (private state — UI-only)`}));return{dappConfig:p,suite:m,actions:d,assertions:h,prompt:null,suiteName:u,excludedCircuits:w.length>0?w:void 0}}async function Ow(e,t=Oo){let r=e.screen?Hl(e.screen.path,"utf-8"):void 0,n=Ul({contractName:e.contract.name,contractSummary:_o({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=Jl(s);_w(o);let i=e.suiteName??(e.screen?`ui-${e.screen.name}`:`ui-${zl(e.goal)??"ai"}`),a=e.network??Gl,c=e.servePort??Kl,d=e.url,u={name:e.contract.name,network:a,port:e.port,buildCmd:e.buildCmd,url:d,prep:Nw};if(e.buildDir)u.buildDir=e.buildDir;let l={name:i,description:o.description,strategy:"browser",timeout:Tw,...e.browserMode?{browserMode:e.browserMode}:{}},f=Fw(o.assertions,c);return{dappConfig:u,suite:l,actions:null,assertions:f,prompt:o.prompt,suiteName:i}}function ql(e){let t=e.params;return typeof t?.port==="number"?t.port:void 0}function Mw(e,t){if(e.post.some((n)=>n.type==="port-listening"&&ql(n)===t))return e;return{...e,post:[...e.post,{id:"serve-port-listening",type:"port-listening",params:{port:t},expect:"pass"}]}}function Fw(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"&&ql(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 zl(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 Mo(e){let t=e.split("/").pop(),r=[pr(e),ts(pr(e),"src"),pr(pr(e)),ts(pr(pr(e)),"src")];for(let n of r){if(!$o(n))continue;if(t){let i=ts(n,`${t}.compact`);if($o(i))return i}let s;try{s=xw(n)}catch{continue}let o=s.find((i)=>i.endsWith(".compact"));if(o)return ts(n,o)}return}var Gl="undeployed",Kl=9932,Aw=300,Tw=600,Vl,Nw,Bl=300000,jl=4194304,Oo=(e)=>new Promise((t,r)=>{let n=Ew("claude",["--print"],{stdio:["pipe","pipe","pipe"]}),s="",o="",i=0,a=!1,c=setTimeout(()=>{n.kill("SIGTERM"),r(Error(`claude --print timed out after ${Bl/1000}s`))},Bl);n.stdout?.on("data",(d)=>{if(i+=d.length,i>jl){a=!0,n.kill("SIGTERM");return}s+=d.toString()}),n.stderr?.on("data",(d)=>{o+=d.toString()}),n.on("error",(d)=>{if(clearTimeout(c),d.code==="ENOENT"){r(Error("claude CLI not found on PATH. Install Claude Code (npm install -g @anthropic-ai/claude-code) or run mn test create without --goal / --screen for the deterministic scaffolder."));return}r(d)}),n.on("exit",(d,u)=>{if(clearTimeout(c),a){r(Error(`claude --print response exceeded ${jl/1024/1024}MB; aborted.`));return}if(u==="SIGTERM")return;if(d!==0){let l=o.trim().slice(0,300)||`(no stderr; exit ${d})`;r(Error(`claude --print exited with code ${d}: ${l}`));return}t(s)}),n.stdin?.write(e),n.stdin?.end()});var Fo=T(()=>{Wl();No();es();Vl=["cache-clear","localnet-up","balance:1000","dust","mn-serve"],Nw=[...Vl,"build-and-serve"]});import{existsSync as Yl,readFileSync as Zl,writeFileSync as Lw,mkdirSync as Uw}from"node:fs";import{join as Ql}from"node:path";async function eu(e){let{actions:t,config:r,dappDir:n,suiteName:s,networkConfig:o,servePort:i,redeploy:a,onActionStart:c,onActionComplete:d,onMessage:u}=e,l=[],f=r.network??"undeployed",p;if(!a)p=Vw(n,s,f);let{info:m}=ct(n),h=Kw(m),w;for(let y of t){c?.(y);let S=Date.now();if(w&&(y.type==="contract-call"||y.type==="contract-state")){let v={id:y.id,type:y.type,status:"skip",duration:0,message:`cascaded skip — depends on ${w}`};l.push(v),d?.(y,v);continue}try{let v=await Ww(y,{dappDir:n,networkConfig:o,managedDir:m.managedDir,contractName:m.name,servePort:i,contractAddress:p,witnessDeps:h,onMessage:u});if(v.contractAddress){if(p=v.contractAddress,Jw(n,s,f,p),y.type==="contract-deploy")w=void 0}let A=Date.now()-S,N={...v,duration:A};if(l.push(N),d?.(y,N),v.status==="skip"&&y.type==="contract-call")w=`skipped action "${y.id}"`}catch(v){let A=Date.now()-S,N={id:y.id,type:y.type,status:"fail",duration:A,message:v.message};l.push(N),d?.(y,N);break}}return l}async function Ww(e,t){switch(e.type){case"contract-deploy":return Bw(e,t);case"contract-call":return jw(e,t);case"contract-state":return Hw(e,t);case"wallet-cmd":return Gw(e,t);default:throw Error(`Unknown action type: ${e.type}`)}}async function Bw(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 jw(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 cr({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 zn({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 cr({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 Hw(e,t){if(!t.contractAddress)throw Error(`Action "${e.id}": no contract address. Add a contract-deploy action first.`);let r=await cr({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)Lo(s,BigInt(a.size),o,n);else n.push(`Field "${s}" not found in ledger state`);continue}try{let a=BigInt(i);Lo(s,a,o,n)}catch{Lo(s,i,o,n)}}if(n.length>0)throw Error(`State assertion failed:
|
|
1226
1230
|
${n.join(`
|
|
1227
|
-
`)}`)}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
|
|
1228
|
-
`)}var
|
|
1231
|
+
`)}`)}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 Lo(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 Gw(e,t){return{id:e.id,type:e.type,status:"pass",duration:0,message:`wallet-cmd: ${e.cmd??"no command"} (not yet implemented)`}}function Kw(e){if(e.witnesses.length===0)return new Map;let t=Mo(e.managedDir);if(!t||!Yl(t))return new Map;let r=Zl(t,"utf-8"),n=e.witnesses.map((s)=>s.name);return ur(r,n).byCircuit}function tu(e,t){if(!e||!t)return[];let r=[],n=new Set([...Object.keys(e.fields),...Object.keys(t.fields)]);for(let o of n){let i=e.fields[o]??"(absent)",a=t.fields[o]??"(absent)";if(i!==a)r.push({field:o,before:i,after:a})}let s=new Set([...Object.keys(e.maps),...Object.keys(t.maps)]);for(let o of s){let i=e.maps[o]?.size??"0",a=t.maps[o]?.size??"0";if(i!==a)r.push({field:`${o} (entries)`,before:i,after:a})}return r}function ru(e,t){return Ql(e,"tests","results",`.contract-cache-${t}.json`)}function Vw(e,t,r){let n=ru(e,t);if(!Yl(n))return;try{let s=JSON.parse(Zl(n,"utf-8"));if(s.network!==r)return;return s.address}catch{return}}function Jw(e,t,r,n){let s=ru(e,t);Uw(Ql(e,"tests","results"),{recursive:!0});let o={address:n,network:r,timestamp:new Date().toISOString()};Lw(s,JSON.stringify(o,null,2)+`
|
|
1232
|
+
`)}var nu=T(()=>{qr();jn();es();Fo()});var cu={};me(cu,{default:()=>iu});import{join as su}from"node:path";import{mkdirSync as qw}from"node:fs";function zw(e){return ou.includes(e)}async function iu(e,t){let r=e.subcommand;if(!r||!zw(r))throw new q(`Usage: midnight test <${ou.join("|")}>
|
|
1229
1233
|
|
|
1230
1234
|
create Generate dapp.test.json + a CLI test suite from the contract
|
|
1231
1235
|
run Run test suites for the current dApp
|
|
1232
1236
|
list List available test suites
|
|
1233
1237
|
results Show latest test results
|
|
1234
1238
|
|
|
1235
|
-
Run from the root of a dApp project containing dapp.test.json.`);let n=
|
|
1236
|
-
`+
|
|
1239
|
+
Run from the root of a dApp project containing dapp.test.json.`);let n=R(e,"json");switch(r){case"create":return ey(e,n);case"run":return sy(e,n,t);case"list":return oy(n);case"results":return iy(e,n)}}function Xw(e){let t=(e??"").toLowerCase();if(t==="")return;if(t==="cli"||t==="browser")return t;if(t==="ui")return"browser";throw new q(`Unknown strategy "${e}". Use "cli" or "ui".`)}function Yw(e){return e==="preprod"||e==="preview"||e==="undeployed"?e:void 0}function Zw(e){let t={},r=C(e,"port");if(r!==void 0){let a=parseInt(r,10);if(!Number.isFinite(a)||a<=0||a>65535)throw new q(`Invalid --port "${r}" — must be 1–65535.`);t.port=a}let n=C(e,"build-cmd");if(n!==void 0)t.buildCmd=n;let s=C(e,"build-dir");if(s!==void 0)t.buildDir=s;let o=C(e,"url");if(o!==void 0)t.url=o;let i=C(e,"browser-mode");if(i!==void 0){if(i!=="dom"&&i!=="vision"&&i!=="script"&&i!=="auto")throw new q(`Invalid --browser-mode "${i}" — must be dom, vision, or script.`);t.browserMode=i}return t}function Qw(e){if(e.port===void 0||e.buildCmd===void 0)throw new q("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 ey(e,t){let{resolve:r}=await import("node:path");await Promise.resolve().then(() => jn());await Promise.resolve().then(() => No());await Promise.resolve().then(() => Cl());let i=await Promise.resolve().then(() => (Ol(),{}));await Promise.resolve();let h=await Promise.resolve().then(() => (Fo(),Xl));await Promise.resolve().then(() => Io());let y=r(C(e,"path")??process.cwd()),S=C(e,"name"),v=C(e,"suite"),A=Yw(C(e,"network")),N=R(e,"force"),L=!t&&Il(),ee=C(e,"goal"),X=C(e,"screen"),V=R(e,"no-ai"),_=Xw(C(e,"strategy"))??(L?await Dl():"cli"),ne;if(_==="browser"){let ke=Zw(e);ne=L?await Pl(ke):Qw(ke)}let{info:de}=ct(y,S),Zr=!V&&h.isClaudeAvailable(),dt=!V&&(ee!==void 0||X!==void 0||L&&Zr),le=dt?await ty({strategy:_,info:de,dappDir:y,browser:ne,network:A,suiteName:v,goalFlag:ee,screenFlag:X,interactive:L,jsonMode:t,ai:h,promptCircuit:_l,promptScreen:Do,promptGoal:$l,promptSuiteName:Po,discoverScreens:Tl})??To(de.circuits,{contractName:de.name,suiteName:v,strategy:_,browser:ne,network:A}):To(de.circuits,{contractName:de.name,suiteName:v,strategy:_,browser:ne,network:A});if(L&&!v){let ke=await Po(le.suiteName);if(ke!==le.suiteName)le.suiteName=ke,le.suite.name=ke}let St=kl(le,{dappDir:y,force:N});if(t){I({subcommand:"create",contractName:de.name,suiteName:le.suiteName,strategy:_,aiAssisted:dt&&le.suiteName!=="cli-default"&&le.suiteName!=="ui-default",written:St.written,excludedCircuits:le.excludedCircuits});return}process.stderr.write(`
|
|
1240
|
+
`+W(`Test scaffold: ${de.name}`)+`
|
|
1237
1241
|
|
|
1238
|
-
`);for(let
|
|
1239
|
-
`);let
|
|
1242
|
+
`);for(let ke of St.written)process.stderr.write(` ${U("✓")} ${ke}
|
|
1243
|
+
`);let bt=_==="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(le.excludedCircuits&&le.excludedCircuits.length>0){process.stderr.write(`
|
|
1240
1244
|
`+g(" Skipped (not CLI-testable):")+`
|
|
1241
|
-
`);for(let
|
|
1245
|
+
`);for(let ke of le.excludedCircuits)process.stderr.write(` ${Y("!")} ${ke.name} ${g("— "+ke.reason)}
|
|
1242
1246
|
`);process.stderr.write(g(` These need the dApp UI to populate private state first.
|
|
1243
1247
|
`)),process.stderr.write(g(` Cover them with a browser-strategy suite (mn test create --strategy ui).
|
|
1244
1248
|
`))}process.stderr.write(`
|
|
1245
1249
|
`+g(" Next:")+`
|
|
1246
|
-
`),process.stderr.write(g(" Edit ")+
|
|
1247
|
-
`),process.stderr.write(g(" ")+g(
|
|
1248
|
-
`),process.stderr.write(g(" Run ")+
|
|
1249
|
-
`),process.stderr.write(g(" List ")+
|
|
1250
|
+
`),process.stderr.write(g(" Edit ")+H(`tests/suites/${le.suiteName}/${bt.file}`)+`
|
|
1251
|
+
`),process.stderr.write(g(" ")+g(bt.hint)+`
|
|
1252
|
+
`),process.stderr.write(g(" Run ")+H(`mn test run --suite ${le.suiteName}`)+`
|
|
1253
|
+
`),process.stderr.write(g(" List ")+H("mn test list")+g(" (see every suite in this project)")+`
|
|
1250
1254
|
|
|
1251
|
-
`)}async function
|
|
1255
|
+
`)}async function ty(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 ry(e,t);return await ny(e,t)}catch(t){return process.stderr.write(`
|
|
1252
1256
|
${g("AI scaffold failed, falling back to deterministic:")} ${t.message}
|
|
1253
|
-
`),null}}async function
|
|
1254
|
-
`+
|
|
1257
|
+
`),null}}async function au(e,t,r){if(!r)return t();let n=G(e);try{let s=await t();return n.stop(),s}catch(s){throw n.fail("AI scaffold failed"),s}}async function ry(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(() => es());let i=s(n,"utf-8"),a=e.info.witnesses.map((u)=>u.name),d=ur(i,a).byCircuit.get(r.name);if(d&&d.length>0)process.stderr.write(`
|
|
1258
|
+
`+Y("!")+` ${r.name} calls ${d.join(", ")} — a witness that reads private state.
|
|
1255
1259
|
`),process.stderr.write(g(` The CLI suite will deploy + run, but expect a "Cannot read properties of undefined" failure
|
|
1256
1260
|
`)+g(` unless the dApp UI populates that state first. Consider --strategy ui instead.
|
|
1257
|
-
`))}return
|
|
1258
|
-
`+
|
|
1259
|
-
|
|
1260
|
-
`),process.stderr.write(
|
|
1261
|
-
`),n.port)process.stderr.write(
|
|
1262
|
-
`);if(a){if(process.stderr.write(
|
|
1263
|
-
`),process.stderr.write(
|
|
1264
|
-
`),a.suite.strategy==="browser"){let
|
|
1261
|
+
`))}return au("Asking Claude to scaffold the test suite (30–60s)...",()=>e.ai.generateCliScaffoldWithAI({contract:e.info,contractSourcePath:n,targetCircuit:r,goal:t,network:e.network,suiteName:e.suiteName}),e.interactive&&!e.jsonMode)}async function ny(e,t){if(!e.browser)return null;let{join:r}=await import("node:path"),n=e.browser.buildDir?r(e.dappDir,e.browser.buildDir):e.dappDir,s=e.discoverScreens(n),o=e.screenFlag?s.find((i)=>i.name===e.screenFlag||i.component===e.screenFlag):e.interactive?await e.promptScreen(s):s[0];if(!o&&!t)return null;return au("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 sy(e,t,r){let{config:n,dappDir:s}=Zn(),o=ko(s),i=C(e,"suite"),a;if(i){if(a=o.find((p)=>p.suite.name===i),!a){let p=o.map((m)=>m.suite.name).join(", ")||"none found";throw new q(`Suite "${i}" not found. Available: ${p}`)}}else if(o.length>0)a=o[0];qw(su(s,"tests","results"),{recursive:!0});let c=Date.now(),d=new Date().toISOString();if(!t){if(process.stderr.write(`
|
|
1262
|
+
`+W(`E2E Test: ${n.name}`)+`
|
|
1263
|
+
|
|
1264
|
+
`),process.stderr.write(E("Network",n.network??"undeployed")+`
|
|
1265
|
+
`),n.port)process.stderr.write(E("Port",String(n.port))+`
|
|
1266
|
+
`);if(a){if(process.stderr.write(E("Suite",a.suite.name)+`
|
|
1267
|
+
`),process.stderr.write(E("Strategy",a.suite.strategy)+`
|
|
1268
|
+
`),a.suite.strategy==="browser"){let p=Co(a.suite);process.stderr.write(E("Browser Mode",p)+`
|
|
1265
1269
|
`)}}process.stderr.write(`
|
|
1266
|
-
`)}let
|
|
1267
|
-
`)};r?.addEventListener("abort",()=>
|
|
1268
|
-
`));let
|
|
1269
|
-
`);let
|
|
1270
|
+
`)}let u=Yd(),l=[],f=(p)=>{if(!t)process.stderr.write(g(` [teardown] ${p}`)+`
|
|
1271
|
+
`)};r?.addEventListener("abort",()=>xo(u,f),{once:!0});try{if(!t)process.stderr.write(P(` Prep
|
|
1272
|
+
`));let p=G("Starting prep..."),m=await nl(n,s,u,{onStepStart(O){p.update(`[prep] ${O}...`)},onStepComplete(O,_,ne,de){if(_==="pass")p.stop(`${U("✓")} ${O} (${ay(ne)})`);else p.stop(`${ae("✗")} ${O}: ${de??"failed"}`);p=G("")},onMessage(O){p.update(O)}});if(p.stop(""),l.push(...m),!t)process.stderr.write(`
|
|
1273
|
+
`);let h=0,w="";if(a){let O=a.suite;if(O.strategy==="browser"){let _=zd(a.suiteDir);if(!_)throw Error(`No prompt.md found in ${a.suiteDir} — required for browser strategy`);if(w=su(s,"tests","results",`${O.name}_${d.replace(/[:.]/g,"-")}_claude.log`),!t)process.stderr.write(P(` Browser Test
|
|
1270
1274
|
`)),process.stderr.write(g(` Claude will take over the terminal. Output is also logged.
|
|
1271
1275
|
|
|
1272
|
-
`));let ne=await
|
|
1273
|
-
`)}});if(
|
|
1276
|
+
`));let ne=await il({suite:O,prompt:_,dappDir:s,logFile:w,onMessage:(de)=>{if(!t)process.stderr.write(g(` ${de}`)+`
|
|
1277
|
+
`)}});if(h=ne.exitCode,!t)if(process.stderr.write(`
|
|
1274
1278
|
`),ne.timedOut)process.stderr.write(` ${ae("✗")} Browser test timed out
|
|
1275
|
-
`);else process.stderr.write(` ${
|
|
1276
|
-
`)}else if(O.strategy==="cli"){let
|
|
1277
|
-
`)),process.stderr.write(g(` Executing ${
|
|
1278
|
-
|
|
1279
|
-
`));
|
|
1280
|
-
`)}}},onMessage:(
|
|
1281
|
-
`);let
|
|
1282
|
-
`)}
|
|
1283
|
-
`));let y={processExitCode:
|
|
1279
|
+
`);else process.stderr.write(` ${h===0?U("✓"):ae("✗")} Claude exited with code ${h}
|
|
1280
|
+
`)}else if(O.strategy==="cli"){let _=qd(a.suiteDir);if(!_)throw Error(`No actions.json found in ${a.suiteDir} — required for CLI strategy`);if(!t)process.stderr.write(P(` CLI Test
|
|
1281
|
+
`)),process.stderr.write(g(` Executing ${_.actions.length} action(s)
|
|
1282
|
+
|
|
1283
|
+
`));await Promise.resolve().then(() => nu());await Promise.resolve().then(() => Ae());let dt=n.network??"undeployed",{config:le}=ce({args:{command:"test",subcommand:"run",positionals:[],flags:{network:dt}}});await Promise.resolve();let bt=u.serveHandle?.port??yr,ke=R(e,"redeploy"),vt=await eu({actions:_.actions,config:n,dappDir:s,suiteName:O.name,networkConfig:le,servePort:bt,redeploy:ke,onActionStart:(fe)=>{if(!t){let ye=G(`[${fe.id}] ${fe.type}${fe.circuit?` ${fe.circuit}`:""}...`);fe._spinner=ye}},onActionComplete:(fe,ye)=>{if(!t){let tt=fe._spinner;if(tt)if(ye.status==="pass")tt.stop(`${U("✓")} ${fe.id}: ${ye.message??"pass"}`);else if(ye.status==="skip")tt.stop(`${Y("⊘")} ${fe.id}: ${ye.message??"skipped"}`);else tt.stop(`${ae("✗")} ${fe.id}: ${ye.message??"fail"}`);if(ye.stateBefore&&ye.stateAfter){let k=tu(ye.stateBefore,ye.stateAfter);if(k.length>0)for(let b of k)process.stderr.write(g(` ${b.field}: ${b.before} → `)+H(b.after)+`
|
|
1284
|
+
`)}}},onMessage:(fe)=>{}});if(h=vt.some((fe)=>fe.status==="fail")?1:0,!t){process.stderr.write(`
|
|
1285
|
+
`);let fe=vt.filter((b)=>b.status==="pass").length,ye=vt.filter((b)=>b.status==="skip").length,tt=vt.filter((b)=>b.status==="fail").length,k=U(String(fe)+" passed");if(ye>0)k+=`, ${Y(String(ye)+" skipped")}`;if(tt>0)k+=`, ${ae(String(tt)+" failed")}`;process.stderr.write(` Actions: ${k}
|
|
1286
|
+
`)}u._actionResults=vt}}else if(!t)process.stderr.write(g(` No test suites found — only prep was run
|
|
1287
|
+
`));let y={processExitCode:h,agentLogPath:w},S=[];if(a){let O=Jd(a.suiteDir);if(O&&O.post.length>0){if(!t)process.stderr.write(`
|
|
1284
1288
|
`+P(` Assertions
|
|
1285
|
-
`));if(S=await
|
|
1286
|
-
`)}}}let
|
|
1287
|
-
`+
|
|
1288
|
-
`),process.stderr.write(` ${
|
|
1289
|
-
`),process.stderr.write(g(` Results: ${
|
|
1289
|
+
`));if(S=await cl(O.post,y),!t)for(let _ of S){let ne=_.status==="pass"?U("✓"):ae("✗"),de=_.message?g(` — ${_.message}`):"";process.stderr.write(` ${ne} ${_.id}${de}
|
|
1290
|
+
`)}}}let v=Math.round((Date.now()-c)/1000),A=l.every((O)=>O.status==="pass"),N=S.every((O)=>O.status==="pass"),L=A&&N&&h===0?"pass":"fail",ee=u._actionResults,X={id:`${n.name}_${d}`,dapp:n.name,suite:a?.suite.name??"prep-only",timestamp:d,duration:v,network:n.network??"undeployed",strategy:a?.suite.strategy??"none",model:a?.suite.model,status:L,prep:l,actions:ee?.map((O)=>({id:O.id,type:O.type,status:O.status,duration:O.duration,message:O.message,contractAddress:O.contractAddress})),assertions:S,testOutput:w?{exitCode:h,logFile:w}:void 0},V=ul(X,s);if(t)I(X);else process.stderr.write(`
|
|
1291
|
+
`+K()+`
|
|
1292
|
+
`),process.stderr.write(` ${L==="pass"?U(P("PASS")):ae(P("FAIL"))} — ${n.name} (${v}s)
|
|
1293
|
+
`),process.stderr.write(g(` Results: ${V}`)+`
|
|
1290
1294
|
|
|
1291
|
-
`);if(
|
|
1292
|
-
`+
|
|
1295
|
+
`);if(L==="fail")process.exitCode=1}finally{await xo(u,f)}}function oy(e){let{config:t,dappDir:r}=Zn(),n=ko(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(`
|
|
1296
|
+
`+W(`Tests: ${t.name}`)+`
|
|
1293
1297
|
|
|
1294
1298
|
`),n.length===0)process.stderr.write(g(` No test suites found.
|
|
1295
1299
|
`)),process.stderr.write(g(` Create tests/suites/<name>/suite.json to add one.
|
|
1296
|
-
`));else for(let{suite:s}of n)process.stderr.write(` ${P(
|
|
1300
|
+
`));else for(let{suite:s}of n)process.stderr.write(` ${P(H(s.name))}
|
|
1297
1301
|
`),process.stderr.write(` ${g(s.description)}
|
|
1298
1302
|
`),process.stderr.write(g(` strategy: ${s.strategy}`)+(s.timeout?g(`, timeout: ${s.timeout}s`):"")+`
|
|
1299
1303
|
|
|
1300
1304
|
`);process.stderr.write(`
|
|
1301
|
-
`)}function
|
|
1302
|
-
`+
|
|
1305
|
+
`)}function iy(e,t){let{config:r,dappDir:n}=Zn(),s=R(e,"all"),o=C(e,"suite"),i=s?Eo(n,o):(()=>{let a=pl(n,o);return a?[a]:[]})();if(t){I(s?{dapp:r.name,results:i}:i[0]??{});return}if(process.stderr.write(`
|
|
1306
|
+
`+W(`Results: ${r.name}`)+`
|
|
1303
1307
|
|
|
1304
1308
|
`),i.length===0)process.stderr.write(g(` No test results found.
|
|
1305
1309
|
`)),process.stderr.write(g(` Run "midnight test run" to generate results.
|
|
1306
|
-
`));else for(let a of i){let c=a.status==="pass"?
|
|
1310
|
+
`));else for(let a of i){let c=a.status==="pass"?U("✓"):ae("✗"),d=a.status==="pass"?U(P("PASS")):ae(P("FAIL"));process.stderr.write(` ${c} ${P(a.suite)} — ${d} (${a.duration}s)
|
|
1307
1311
|
`),process.stderr.write(g(` ${a.timestamp} | ${a.network} | ${a.strategy}`)+`
|
|
1308
|
-
`);let
|
|
1309
|
-
`);let
|
|
1312
|
+
`);let u=a.prep.filter((f)=>f.status==="fail");if(u.length>0)process.stderr.write(ae(` prep: ${u.length} failed`)+`
|
|
1313
|
+
`);let l=a.assertions.filter((f)=>f.status==="fail");if(l.length>0)process.stderr.write(ae(` assertions: ${l.length} failed`)+`
|
|
1310
1314
|
`);process.stderr.write(`
|
|
1311
1315
|
`)}process.stderr.write(`
|
|
1312
|
-
`)}function
|
|
1316
|
+
`)}function ay(e){if(e<1000)return`${e}ms`;return`${(e/1000).toFixed(1)}s`}var ou;var du=T(()=>{ze();ue();at();Xd();sl();al();dl();fl();ml();ou=["run","list","results","create"]});import{readFileSync as lu}from"node:fs";import{fileURLToPath as fu}from"node:url";import{Server as cy}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as dy}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as ly,CallToolRequestSchema as uy,ListResourcesRequestSchema as py,ReadResourceRequestSchema as fy}from"@modelcontextprotocol/sdk/types.js";async function J(e,t,r){let n=[];os((s)=>n.push(s));try{if(t.flags.json=!0,!(Qr in t.flags))t.flags[Qr]=!0;await e(t,r);let s=n.join("").trim();if(!s)return{};return JSON.parse(s)}finally{os(null)}}var pe={INVALID_ARGS:"INVALID_ARGS",WALLET_NOT_FOUND:"WALLET_NOT_FOUND",NETWORK_ERROR:"NETWORK_ERROR",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",TX_REJECTED:"TX_REJECTED",STALE_UTXO:"STALE_UTXO",STALE_CACHE:"STALE_CACHE",PROOF_TIMEOUT:"PROOF_TIMEOUT",PROOF_FAILURE:"PROOF_FAILURE",INVALID_DUST_PROOF:"INVALID_DUST_PROOF",DUST_REQUIRED:"DUST_REQUIRED",SYNC_TIMEOUT:"SYNC_TIMEOUT",CANCELLED:"CANCELLED",UNSUPPORTED_LEDGER:"UNSUPPORTED_LEDGER",LOCALNET_UNAVAILABLE:"LOCALNET_UNAVAILABLE",LOCAL_STACK_UNREACHABLE:"LOCAL_STACK_UNREACHABLE",AMBIGUOUS_LOCAL_STACKS:"AMBIGUOUS_LOCAL_STACKS",UNKNOWN:"UNKNOWN"},ku=new Set([pe.UNSUPPORTED_LEDGER,pe.LOCALNET_UNAVAILABLE,pe.LOCAL_STACK_UNREACHABLE,pe.AMBIGUOUS_LOCAL_STACKS]);function Ho(e){let t=e.code;if(typeof t==="string"&&ku.has(t))return{exitCode:4,errorCode:t};let r=(e.message??"").toLowerCase();if(r.includes("operation cancelled")||r.includes("operation aborted")||r==="cancelled"||r==="aborted")return{exitCode:7,errorCode:pe.CANCELLED};if(r.includes("wallet file not found")||r.includes("wallet")&&r.includes("not found"))return{exitCode:3,errorCode:pe.WALLET_NOT_FOUND};if(r.includes("missing required flag")||r.includes("missing amount")||r.includes("missing recipient")||r.includes("missing config key")||r.includes("missing or invalid subcommand")||r.includes("unknown command")||r.includes("cannot specify both")||r.includes("invalid bip-39")||r.includes("seed must be")||r.includes("key index must be")||r.includes("shielded balances are private")||r.includes("shielded is unavailable")||r.includes("belongs to")&&r.includes("--network is")||r.includes("usage:"))return{exitCode:2,errorCode:pe.INVALID_ARGS};if(r.includes("proof")&&r.includes("timeout"))return{exitCode:6,errorCode:pe.PROOF_TIMEOUT};if(r.includes("stale utxo")||r.includes("error code 115")||r.includes("errorcode: 115"))return{exitCode:6,errorCode:pe.STALE_UTXO};if(r.includes("error 170")||r.includes("errorcode: 170")||r.includes("invaliddustspendproof"))return{exitCode:6,errorCode:pe.INVALID_DUST_PROOF};if(r.includes("stale cache")||r.includes("chain reset")||r.includes("chainid mismatch")||r.includes("applied > highest"))return{exitCode:6,errorCode:pe.STALE_CACHE};if(r.includes("failed to prove"))return{exitCode:6,errorCode:pe.PROOF_FAILURE};if(r.includes("wallet sync timed out")||r.includes("sync timed out")||r.includes("timed out waiting for dust")||r.includes("did not respond within")||r.includes("did not produce a block")||r.includes("did not report funds"))return{exitCode:4,errorCode:pe.SYNC_TIMEOUT};if(r.includes("no dust")||r.includes("dust")&&(r.includes("required")||r.includes("available")||r.includes("insufficient")))return{exitCode:5,errorCode:pe.DUST_REQUIRED};if(r.includes("insufficient")||r.includes("not enough"))return{exitCode:5,errorCode:pe.INSUFFICIENT_BALANCE};if(r.includes("rejected")||r.includes("transaction failed"))return{exitCode:6,errorCode:pe.TX_REJECTED};if(r.includes("econnrefused")||r.includes("enotfound")||r.includes("etimedout")||r.includes("websocket")||r.includes("connection refused")||r.includes("request to ")&&r.includes(" failed, reason:")||r.includes("network")&&r.includes("error"))return{exitCode:4,errorCode:pe.NETWORK_ERROR};return{exitCode:1,errorCode:pe.UNKNOWN}}function Go(e){let t=e.split(`
|
|
1313
1317
|
|
|
1314
1318
|
`)[0].trim(),r=t.split(`
|
|
1315
1319
|
`),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(`
|
|
1316
|
-
`).trim()||t}var Br={name:"midnight-wallet-cli",version:"0.5.2",type:"module",description:"Git-style CLI wallet for the Midnight blockchain",license:"Apache-2.0",author:"Norman Lopez (https://github.com/nel349)",homepage:"https://github.com/nel349/midnight-wallet-cli#readme",repository:{type:"git",url:"git+https://github.com/nel349/midnight-wallet-cli.git"},bugs:{url:"https://github.com/nel349/midnight-wallet-cli/issues"},keywords:["midnight","blockchain","wallet","cli","zk","zero-knowledge","compact","mcp","ai-agent"],workspaces:["packages/connector"],bin:{midnight:"dist/wallet.js",mn:"dist/wallet.js","midnight-wallet-cli":"dist/wallet.js","midnight-wallet-mcp":"dist/mcp-server.js"},files:["dist","docs/SKILL.md","NOTICE"],engines:{node:">=20",bun:">=1.3.0"},scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",link:"bun link",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/compact-runtime":"^0.16.0","@midnight-ntwrk/dapp-connector-api":"^4.0.1","@midnight-ntwrk/ledger-v8":"^8.1.0","@midnight-ntwrk/midnight-js-contracts":"^4.1.1","@midnight-ntwrk/midnight-js-http-client-proof-provider":"^4.1.1","@midnight-ntwrk/midnight-js-indexer-public-data-provider":"^4.1.1","@midnight-ntwrk/midnight-js-level-private-state-provider":"^4.1.1","@midnight-ntwrk/midnight-js-network-id":"^4.1.1","@midnight-ntwrk/midnight-js-node-zk-config-provider":"^4.1.1","@midnight-ntwrk/midnight-js-types":"^4.1.1","@midnight-ntwrk/midnight-js-utils":"^4.1.1","@midnight-ntwrk/wallet-sdk-abstractions":"^2.0.0","@midnight-ntwrk/wallet-sdk-address-format":"^3.1.0","@midnight-ntwrk/wallet-sdk-capabilities":"^3.2.0","@midnight-ntwrk/wallet-sdk-dust-wallet":"^4.0.0","@midnight-ntwrk/wallet-sdk-facade":"^4.0.0","@midnight-ntwrk/wallet-sdk-hd":"^3.0.1","@midnight-ntwrk/wallet-sdk-shielded":"^3.0.0","@midnight-ntwrk/wallet-sdk-unshielded-wallet":"^3.0.0","@modelcontextprotocol/sdk":"^1.27.1","@scure/bip39":"^2.0.1",rxjs:"^7.8.1",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"},optionalDependencies:{"@nel349/dust-sync-darwin-arm64":"0.5.2","@nel349/dust-sync-darwin-x64":"0.5.2","@nel349/dust-sync-linux-x64":"0.5.2","@nel349/dust-sync-linux-arm64":"0.5.2","@nel349/dust-sync-win32-x64":"0.5.2"}};var sy=Br.name,ss=Br.version,oy=Br.description;import{randomUUID as Kl}from"node:crypto";var Jl=300000;function ei(e={}){let t=e.ttlMs??Jl,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=Kl(),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 Yl from"node:v8";import Zl from"node:os";import{spawn as Ql}from"node:child_process";var vs="MN_HEAP_BUMPED",eu="MN_MAX_OLD_SPACE_MB",ti=1048576;function tu(e){let t=e.desiredMb??ps,r=e.ramFraction??fs,n=e.minGainMb??ms;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 ri(){if(process.env[vs]){nu();return}let e=process.env[eu],t=e!==void 0?Number(e):void 0,r=tu({totalMb:Math.floor(Zl.totalmem()/ti),currentLimitMb:Math.floor(Yl.getHeapStatistics().heap_size_limit/ti),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=Ql(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[vs]:"1"}});ru(s),s.on("error",()=>{process.env[vs]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function ru(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 nu(){let e=process.ppid;if(!e||e<=1)return;setInterval(()=>{if(process.ppid!==e)try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},2000).unref()}var Ml="midnight-wallet://skill/core",Fl="midnight-wallet://skill/full",Bw="midnight-wallet://skill",jw=Ol(new URL("../docs/SKILL-CORE.md",import.meta.url)),Hw=Ol(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"?sr: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 Gw={generate:()=>Promise.resolve().then(() => (Ai(),Ei)),info:()=>Promise.resolve().then(() => (Ni(),Ti)),balance:()=>Promise.resolve().then(() => (wa(),ha)),address:()=>Promise.resolve().then(() => (ba(),Sa)),"genesis-address":()=>Promise.resolve().then(() => (Ca(),ka)),"inspect-cost":()=>Promise.resolve().then(() => (Ta(),xa)),airdrop:()=>Promise.resolve().then(() => (Pa(),Da)),transfer:()=>Promise.resolve().then(() => (Fa(),Ma)),dust:()=>Promise.resolve().then(() => (ja(),Ba)),cache:()=>Promise.resolve().then(() => (Ka(),Ga)),config:()=>Promise.resolve().then(() => (za(),Va)),localnet:()=>Promise.resolve().then(() => (dc(),cc)),wallet:()=>Promise.resolve().then(() => (mc(),fc)),status:()=>Promise.resolve().then(() => (bc(),Sc)),contract:()=>Promise.resolve().then(() => (ld(),dd)),test:()=>Promise.resolve().then(() => (Dl(),Il))};async function Z(e){let t=Gw[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}var Ul=[{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[sr]=!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[sr]=!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")}}],Kw=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),_l=ei();function Jw(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 Fr=new Ow({name:"midnight-wallet-cli",version:ss},{capabilities:{tools:{},resources:{}}});Fr.setRequestHandler(Lw,async()=>({resources:[{uri:Ml,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:Fl,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"}]}));Fr.setRequestHandler(Ww,async(e)=>{let t=e.params.uri;if(t===Ml){let r=Pl(jw,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===Fl||t===Bw){let r=Pl(Hw,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Fr.setRequestHandler(Fw,async()=>({tools:Ul.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Fr.setRequestHandler(Uw,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=_l.redeem(s);if(!o)return qo(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return $l(o.tool,o.args)}if(Kw.has(t)){let s=_l.create({tool:t,args:n,description:Jw(t,n)});return{content:[{type:"text",text:JSON.stringify(Xo({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 $l(t,n)});function Xo(e){return{...e,_serverVersion:ss}}async function $l(e,t){let r=Ul.find((n)=>n.name===e);if(!r)return qo(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(Xo(n),null,2)}]}}catch(n){return qo(n instanceof Error?n:Error(String(n)))}}function qo(e){let{errorCode:t}=Zo(e);return{content:[{type:"text",text:JSON.stringify(Xo({error:!0,code:t,message:Qo(e.message)}))}],isError:!0}}async function Vw(){await ri();let e=new Mw;await Fr.connect(e)}Vw().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1320
|
+
`).trim()||t}var tn={name:"midnight-wallet-cli",version:"0.6.0-rc.1",type:"module",description:"Git-style CLI wallet for the Midnight blockchain",license:"Apache-2.0",author:"Norman Lopez (https://github.com/nel349)",homepage:"https://github.com/nel349/midnight-wallet-cli#readme",repository:{type:"git",url:"git+https://github.com/nel349/midnight-wallet-cli.git"},bugs:{url:"https://github.com/nel349/midnight-wallet-cli/issues"},keywords:["midnight","blockchain","wallet","cli","zk","zero-knowledge","compact","mcp","ai-agent"],workspaces:["packages/connector"],bin:{midnight:"dist/wallet.js",mn:"dist/wallet.js","midnight-wallet-cli":"dist/wallet.js","midnight-wallet-mcp":"dist/mcp-server.js"},files:["dist","docs/SKILL.md","docs/SKILL-CORE.md","NOTICE"],engines:{node:">=20",bun:">=1.3.0"},scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",link:"bun link",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/compact-runtime":"0.20.0","@midnight-ntwrk/ledger-v8":"^8.1.0","@midnight-ntwrk/midnight-js-contracts":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-http-client-proof-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-indexer-public-data-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-level-private-state-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-network-id":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-node-zk-config-provider":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-protocol":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-types":"5.0.0-rc.1","@midnight-ntwrk/midnight-js-utils":"5.0.0-rc.1","@midnightntwrk/dapp-connector-api":"4.1.0-beta.1","@midnightntwrk/ledger-v9":"1.0.0-rc.5","@midnightntwrk/onchain-runtime-v4":"4.0.0-rc.3","@midnightntwrk/wallet-sdk":"2.0.0-rc.0","@modelcontextprotocol/sdk":"^1.27.1","@scure/bip39":"^2.0.1",rxjs:"^7.8.1",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"}};var Py=tn.name,is=tn.version,_y=tn.description;import{randomUUID as Eu}from"node:crypto";var xu=300000;function Ko(e={}){let t=e.ttlMs??xu,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=Eu(),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 Au from"node:v8";import Tu from"node:os";import{spawn as Nu}from"node:child_process";var hs="MN_HEAP_BUMPED",Ru="MN_MAX_OLD_SPACE_MB",ci=1048576;function Iu(e){let t=e.desiredMb??Qo,r=e.ramFraction??ei,n=e.minGainMb??ti;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 di(){if(process.env[hs]){Pu();return}let e=process.env[Ru],t=e!==void 0?Number(e):void 0,r=Iu({totalMb:Math.floor(Tu.totalmem()/ci),currentLimitMb:Math.floor(Au.getHeapStatistics().heap_size_limit/ci),desiredMb:t});if(r===null)return;return new Promise((n)=>{let s=Nu(process.execPath,[`--max-old-space-size=${r}`,...process.execArgv,process.argv[1],...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,[hs]:"1"}});Du(s),s.on("error",()=>{process.env[hs]="1",n()}),s.on("exit",(o,i)=>process.exit(i?1:o??0))})}function Du(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 Pu(){let e=process.ppid;if(!e||e<=1)return;setInterval(()=>{if(process.ppid!==e)try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},2000).unref()}var mu="midnight-wallet://skill/core",gu="midnight-wallet://skill/full",my="midnight-wallet://skill",gy=fu(new URL("../docs/SKILL-CORE.md",import.meta.url)),hy=fu(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"?fr:o;if(typeof i==="boolean"){if(i)n[a]=!0}else n[a]=String(i)}return{command:e,subcommand:r,positionals:s,flags:n}}var wy={generate:()=>Promise.resolve().then(() => (_i(),Pi)),info:()=>Promise.resolve().then(() => (Mi(),Oi)),balance:()=>Promise.resolve().then(() => (_a(),Pa)),address:()=>Promise.resolve().then(() => (Ma(),Oa)),"genesis-address":()=>Promise.resolve().then(() => (Ua(),La)),"inspect-cost":()=>Promise.resolve().then(() => (Ha(),ja)),airdrop:()=>Promise.resolve().then(() => (qa(),Ja)),transfer:()=>Promise.resolve().then(() => (Qa(),Za)),dust:()=>Promise.resolve().then(() => (sc(),nc)),cache:()=>Promise.resolve().then(() => (ac(),ic)),config:()=>Promise.resolve().then(() => (lc(),dc)),localnet:()=>Promise.resolve().then(() => (Ic(),Rc)),wallet:()=>Promise.resolve().then(() => (Oc(),$c)),status:()=>Promise.resolve().then(() => (Bc(),Wc)),contract:()=>Promise.resolve().then(() => (jd(),Bd)),test:()=>Promise.resolve().then(() => (du(),cu))};async function z(e){let t=wy[e];if(!t)throw Error(`Unknown command handler: ${e}`);return(await t()).default}var hu=[{name:"midnight_wallet_generate",description:"Create wallet.",annotations:{destructiveHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},network:{type:"string",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"64 or 128 hex chars (32-byte raw or 64-byte BIP-39)"},mnemonic:{type:"string",description:"BIP-39 24 words"},force:{type:"string"}},required:["name"]},async handler(e){let t=e.name,r=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 J(n,r)}},{name:"midnight_wallet_list",description:"List wallets. Default: per-wallet { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the 3-network addresses + shieldedAddresses maps.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Return full per-network addresses + shieldedAddresses maps (the same shape `mn wallet list --json` emits). Default false (slim)."}}},async handler({full:e}={}){let t={json:!0};if(e)t[fr]=!0;let r={command:"wallet",subcommand:"list",positionals:[],flags:t},n=await z("wallet");return J(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 J(n,r)}},{name:"midnight_wallet_info",description:"Show wallet details. Default: { name, active, network, address, shieldedAddress } scoped to the active network. Pass { full: true } for the per-network maps + createdAt + file path.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{name:{type:"string"},full:{type:"boolean",description:"Return the full per-network addresses + shieldedAddresses maps and bookkeeping fields (matches `mn wallet info <name> --json`). Default false (slim)."}}},async handler(e){let{name:t,full:r}=e,n={json:!0};if(r)n[fr]=!0;let s={command:"wallet",subcommand:"info",positionals:t?[t]:[],flags:n},o=await z("wallet");return J(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 J(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 J(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 J(n,r)}},{name:"midnight_address",description:"Derive address from seed.",annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{seed:{type:"string",description:"64 or 128 hex chars (32-byte raw or 64-byte BIP-39)"},network:{type:"string",enum:["preprod","preview","undeployed"]},index:{type:"string"}},required:["seed"]},async handler(e){let t=we("address",e),r=await z("address");return J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(n,r)}},{name:"midnight_localnet_up",description:"Refused on this ledger-9 build: mn's localnet is ledger 8 and no ledger-9 indexer image is published. Run a ledger-9 stack yourself and point mn at it (config_set node / indexer-ws / proof-server).",annotations:{openWorldHint:!0},inputSchema:{type:"object",properties:{}},async handler(){let e={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},t=await z("localnet");return J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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 J(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")}}],yy=new Set(["midnight_transfer","midnight_contract_deploy","midnight_contract_call"]),uu=Ko();function Sy(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 Yr=new cy({name:"midnight-wallet-cli",version:is},{capabilities:{tools:{},resources:{}}});Yr.setRequestHandler(py,async()=>({resources:[{uri:mu,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:gu,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"}]}));Yr.setRequestHandler(fy,async(e)=>{let t=e.params.uri;if(t===mu){let r=lu(gy,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}if(t===gu||t===my){let r=lu(hy,"utf-8");return{contents:[{uri:t,mimeType:"text/markdown",text:r}]}}throw Error(`Unknown resource: ${t}`)});Yr.setRequestHandler(ly,async()=>({tools:hu.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.annotations?{annotations:e.annotations}:{}}))}));Yr.setRequestHandler(uy,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=uu.redeem(s);if(!o)return Uo(Error("Unknown or expired confirmation token. The first-step tool call may need to be re-issued."));return pu(o.tool,o.args)}if(yy.has(t)){let s=uu.create({tool:t,args:n,description:Sy(t,n)});return{content:[{type:"text",text:JSON.stringify(Wo({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 Wo(e){return{...e,_serverVersion:is}}async function pu(e,t){let r=hu.find((n)=>n.name===e);if(!r)return Uo(Error(`Unknown tool: ${e}`));try{let n=await r.handler(t);return{content:[{type:"text",text:JSON.stringify(Wo(n),null,2)}]}}catch(n){return Uo(n instanceof Error?n:Error(String(n)))}}function Uo(e){let{errorCode:t}=Ho(e);return{content:[{type:"text",text:JSON.stringify(Wo({error:!0,code:t,message:Go(e.message)}))}],isError:!0}}async function by(){await di();let e=new dy;await Yr.connect(e)}by().catch((e)=>{process.stderr.write(`MCP server error: ${e.message}
|
|
1317
1321
|
`),process.exit(1)});
|